Rewrite tags setting functions
[org-mode/org-tableheadings.git] / lisp / org.el
blobcabd5cb999c911dd50c2c2d754de64492faa3edf
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)
187 (defvar org-indent-indentation-per-level)
189 ;; load languages based on value of `org-babel-load-languages'
190 (defvar org-babel-load-languages)
192 ;;;###autoload
193 (defun org-babel-do-load-languages (sym value)
194 "Load the languages defined in `org-babel-load-languages'."
195 (set-default sym value)
196 (dolist (pair org-babel-load-languages)
197 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
198 (if active
199 (require (intern (concat "ob-" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-execute:" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-expand-body:" lang)))))))
205 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
206 ;;;###autoload
207 (defun org-babel-load-file (file &optional compile)
208 "Load Emacs Lisp source code blocks in the Org FILE.
209 This function exports the source code using `org-babel-tangle'
210 and then loads the resulting file using `load-file'. With prefix
211 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
212 file to byte-code before it is loaded."
213 (interactive "fFile to load: \nP")
214 (let* ((age (lambda (file)
215 (float-time
216 (time-subtract (current-time)
217 (nth 5 (or (file-attributes (file-truename file))
218 (file-attributes file)))))))
219 (base-name (file-name-sans-extension file))
220 (exported-file (concat base-name ".el")))
221 ;; tangle if the Org file is newer than the elisp file
222 (unless (and (file-exists-p exported-file)
223 (> (funcall age file) (funcall age exported-file)))
224 ;; Tangle-file traversal returns reversed list of tangled files
225 ;; and we want to evaluate the first target.
226 (setq exported-file
227 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
228 (message "%s %s"
229 (if compile
230 (progn (byte-compile-file exported-file 'load)
231 "Compiled and loaded")
232 (progn (load-file exported-file) "Loaded"))
233 exported-file)))
235 (defcustom org-babel-load-languages '((emacs-lisp . t))
236 "Languages which can be evaluated in Org buffers.
237 This list can be used to load support for any of the languages
238 below, note that each language will depend on a different set of
239 system executables and/or Emacs modes. When a language is
240 \"loaded\", then code blocks in that language can be evaluated
241 with `org-babel-execute-src-block' bound by default to C-c
242 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
243 be set to remove code block evaluation from the C-c C-c
244 keybinding. By default only Emacs Lisp (which has no
245 requirements) is loaded."
246 :group 'org-babel
247 :set 'org-babel-do-load-languages
248 :version "24.1"
249 :type '(alist :tag "Babel Languages"
250 :key-type
251 (choice
252 (const :tag "Awk" awk)
253 (const :tag "C" C)
254 (const :tag "R" R)
255 (const :tag "Asymptote" asymptote)
256 (const :tag "Calc" calc)
257 (const :tag "Clojure" clojure)
258 (const :tag "CSS" css)
259 (const :tag "Ditaa" ditaa)
260 (const :tag "Dot" dot)
261 (const :tag "Ebnf2ps" ebnf2ps)
262 (const :tag "Emacs Lisp" emacs-lisp)
263 (const :tag "Forth" forth)
264 (const :tag "Fortran" fortran)
265 (const :tag "Gnuplot" gnuplot)
266 (const :tag "Haskell" haskell)
267 (const :tag "hledger" hledger)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "Vala" vala))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 \\<org-mode-map>
376 A deadline is this string, followed by a time stamp. It must be
377 a word, terminated by a colon. You can insert a schedule keyword
378 and a timestamp with `\\[org-deadline]'.")
380 (defvar org-scheduled-string "SCHEDULED:"
381 "String to mark scheduled TODO entries.
382 \\<org-mode-map>
383 A schedule is this string, followed by a time stamp. It must be
384 a word, terminated by a colon. You can insert a schedule keyword
385 and a timestamp with `\\[org-schedule]'.")
387 (defconst org-ds-keyword-length
388 (+ 2
389 (apply #'max
390 (mapcar #'length
391 (list org-deadline-string org-scheduled-string
392 org-clock-string org-closed-string))))
393 "Maximum length of the DEADLINE and SCHEDULED keywords.")
395 (defconst org-planning-line-re
396 (concat "^[ \t]*"
397 (regexp-opt
398 (list org-closed-string org-deadline-string org-scheduled-string)
400 "Matches a line with planning info.
401 Matched keyword is in group 1.")
403 (defconst org-clock-line-re
404 (concat "^[ \t]*" org-clock-string)
405 "Matches a line with clock info.")
407 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
408 "Matches the DEADLINE keyword.")
410 (defconst org-deadline-time-regexp
411 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
412 "Matches the DEADLINE keyword together with a time stamp.")
414 (defconst org-deadline-time-hour-regexp
415 (concat "\\<" org-deadline-string
416 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
417 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
419 (defconst org-deadline-line-regexp
420 (concat "\\<\\(" org-deadline-string "\\).*")
421 "Matches the DEADLINE keyword and the rest of the line.")
423 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
424 "Matches the SCHEDULED keyword.")
426 (defconst org-scheduled-time-regexp
427 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
428 "Matches the SCHEDULED keyword together with a time stamp.")
430 (defconst org-scheduled-time-hour-regexp
431 (concat "\\<" org-scheduled-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
435 (defconst org-closed-time-regexp
436 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
437 "Matches the CLOSED keyword together with a time stamp.")
439 (defconst org-keyword-time-regexp
440 (concat "\\<"
441 (regexp-opt
442 (list org-scheduled-string org-deadline-string org-closed-string
443 org-clock-string)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 4 keywords, together with the time stamp.")
448 (defconst org-keyword-time-not-clock-regexp
449 (concat
450 "\\<"
451 (regexp-opt
452 (list org-scheduled-string org-deadline-string org-closed-string) t)
453 " *[[<]\\([^]>]+\\)[]>]")
454 "Matches any of the 3 keywords, together with the time stamp.")
456 (defconst org-maybe-keyword-time-regexp
457 (concat "\\(\\<"
458 (regexp-opt
459 (list org-scheduled-string org-deadline-string org-closed-string
460 org-clock-string)
462 "\\)?"
463 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
464 "\\|"
465 "<%%([^\r\n>]*>\\)")
466 "Matches a timestamp, possibly preceded by a keyword.")
468 (defconst org-all-time-keywords
469 (mapcar (lambda (w) (substring w 0 -1))
470 (list org-scheduled-string org-deadline-string
471 org-clock-string org-closed-string))
472 "List of time keywords.")
474 ;;;; Drawer
476 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
477 "Matches first or last line of a hidden block.
478 Group 1 contains drawer's name or \"END\".")
480 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
481 "Regular expression matching the first line of a property drawer.")
483 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a property drawer.")
486 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
487 "Regular expression matching the first line of a clock drawer.")
489 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
490 "Regular expression matching the last line of a clock drawer.")
492 (defconst org-property-drawer-re
493 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
494 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
495 "[ \t]*:END:[ \t]*$")
496 "Matches an entire property drawer.")
498 (defconst org-clock-drawer-re
499 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
500 org-clock-drawer-end-re "\\)\n?")
501 "Matches an entire clock drawer.")
503 ;;;; Headline
505 (defconst org-heading-keyword-regexp-format
506 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
507 "Printf format for a regexp matching a headline with some keyword.
508 This regexp will match the headline of any node which has the
509 exact keyword that is put into the format. The keyword isn't in
510 any group by default, but the stars and the body are.")
512 (defconst org-heading-keyword-maybe-regexp-format
513 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
514 "Printf format for a regexp matching a headline, possibly with some keyword.
515 This regexp can match any headline with the specified keyword, or
516 without a keyword. The keyword isn't in any group by default,
517 but the stars and the body are.")
519 (defconst org-archive-tag "ARCHIVE"
520 "The tag that marks a subtree as archived.
521 An archived subtree does not open during visibility cycling, and does
522 not contribute to the agenda listings.")
524 (defconst org-tag-re "[[:alnum:]_@#%]+"
525 "Regexp matching a single tag.")
527 (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
528 "Regexp matching the tag group at the end of a line, with leading spaces.
529 Tags are stored in match group 1. Match group 2 stores the tags
530 without the enclosing colons.")
532 (defconst org-tag-line-re
533 "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
534 "Regexp matching tags in a headline.
535 Tags are stored in match group 1. Match group 2 stores the tags
536 without the enclosing colons.")
538 (eval-and-compile
539 (defconst org-comment-string "COMMENT"
540 "Entries starting with this keyword will never be exported.
541 \\<org-mode-map>
542 An entry can be toggled between COMMENT and normal with
543 `\\[org-toggle-comment]'."))
546 ;;;; LaTeX Environments and Fragments
548 (defconst org-latex-regexps
549 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
550 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
551 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
552 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
553 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
554 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
555 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
556 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
557 "Regular expressions for matching embedded LaTeX.")
559 ;;;; Node Property
561 (defconst org-effort-property "Effort"
562 "The property that is being used to keep track of effort estimates.
563 Effort estimates given in this property need to have the format H:MM.")
565 ;;;; Table
567 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
568 "Detect an org-type or table-type table.")
570 (defconst org-table-line-regexp "^[ \t]*|"
571 "Detect an org-type table line.")
573 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
574 "Detect an org-type table line.")
576 (defconst org-table-hline-regexp "^[ \t]*|-"
577 "Detect an org-type table hline.")
579 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
580 "Detect a table-type table hline.")
582 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
583 "Detect the first line outside a table when searching from within it.
584 This works for both table types.")
586 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
587 "Detect a #+TBLFM line.")
589 ;;;; Timestamp
591 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
592 "Regular expression for fast time stamp matching.")
594 (defconst org-ts-regexp-inactive
595 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
596 "Regular expression for fast inactive time stamp matching.")
598 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
599 "Regular expression for fast time stamp matching.")
601 (defconst org-ts-regexp0
602 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
603 "Regular expression matching time strings for analysis.
604 This one does not require the space after the date, so it can be used
605 on a string that terminates immediately after the date.")
607 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
608 "Regular expression matching time strings for analysis.")
610 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
611 "Regular expression matching time stamps, with groups.")
613 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
614 "Regular expression matching time stamps (also [..]), with groups.")
616 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
617 "Regular expression matching a time stamp range.")
619 (defconst org-tr-regexp-both
620 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
621 "Regular expression matching a time stamp range.")
623 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
624 org-ts-regexp "\\)?")
625 "Regular expression matching a time stamp or time stamp range.")
627 (defconst org-tsr-regexp-both
628 (concat org-ts-regexp-both "\\(--?-?"
629 org-ts-regexp-both "\\)?")
630 "Regular expression matching a time stamp or time stamp range.
631 The time stamps may be either active or inactive.")
633 (defconst org-repeat-re
634 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
635 "Regular expression for specifying repeated events.
636 After a match, group 1 contains the repeat expression.")
638 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
639 "Formats for `format-time-string' which are used for time stamps.")
642 ;;; The custom variables
644 (defgroup org nil
645 "Outline-based notes management and organizer."
646 :tag "Org"
647 :group 'outlines
648 :group 'calendar)
650 (defcustom org-mode-hook nil
651 "Mode hook for Org mode, run after the mode was turned on."
652 :group 'org
653 :type 'hook)
655 (defcustom org-load-hook nil
656 "Hook that is run after org.el has been loaded."
657 :group 'org
658 :type 'hook)
660 (defcustom org-log-buffer-setup-hook nil
661 "Hook that is run after an Org log buffer is created."
662 :group 'org
663 :version "24.1"
664 :type 'hook)
666 (defvar org-modules) ; defined below
667 (defvar org-modules-loaded nil
668 "Have the modules been loaded already?")
670 (defun org-load-modules-maybe (&optional force)
671 "Load all extensions listed in `org-modules'."
672 (when (or force (not org-modules-loaded))
673 (dolist (ext org-modules)
674 (condition-case nil (require ext)
675 (error (message "Problems while trying to load feature `%s'" ext))))
676 (setq org-modules-loaded t)))
678 (defun org-set-modules (var value)
679 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
680 (set var value)
681 (when (featurep 'org)
682 (org-load-modules-maybe 'force)
683 (org-element-cache-reset 'all)))
685 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
686 "Modules that should always be loaded together with org.el.
688 If a description starts with <C>, the file is not part of Emacs
689 and loading it will require that you have downloaded and properly
690 installed the Org mode distribution.
692 You can also use this system to load external packages (i.e. neither Org
693 core modules, nor modules from the CONTRIB directory). Just add symbols
694 to the end of the list. If the package is called org-xyz.el, then you need
695 to add the symbol `xyz', and the package must have a call to:
697 (provide \\='org-xyz)
699 For export specific modules, see also `org-export-backends'."
700 :group 'org
701 :set 'org-set-modules
702 :version "24.4"
703 :package-version '(Org . "8.0")
704 :type
705 '(set :greedy t
706 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
707 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
708 (const :tag " crypt: Encryption of subtrees" org-crypt)
709 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
710 (const :tag " docview: Links to doc-view buffers" org-docview)
711 (const :tag " eww: Store link to url of eww" org-eww)
712 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
713 (const :tag " habit: Track your consistency with habits" org-habit)
714 (const :tag " id: Global IDs for identifying entries" org-id)
715 (const :tag " info: Links to Info nodes" org-info)
716 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
717 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
718 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
719 (const :tag " mouse: Additional mouse support" org-mouse)
720 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
721 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
722 (const :tag " tempo: Fast completion for structures" org-tempo)
723 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
725 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
726 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
727 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
728 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
729 (const :tag "C collector: Collect properties into tables" org-collector)
730 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
731 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
732 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
733 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
734 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
735 (const :tag "C eval: Include command output as text" org-eval)
736 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
737 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
738 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
739 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
740 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
741 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
742 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
743 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
744 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
745 (const :tag "C man: Support for links to manpages in Org mode" org-man)
746 (const :tag "C mew: Links to Mew folders/messages" org-mew)
747 (const :tag "C mtags: Support for muse-like tags" org-mtags)
748 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
749 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
750 (const :tag "C registry: A registry for Org links" org-registry)
751 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
752 (const :tag "C secretary: Team management with Org" org-secretary)
753 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
754 (const :tag "C toc: Table of contents for Org buffer" org-toc)
755 (const :tag "C track: Keep up with Org mode development" org-track)
756 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
757 (const :tag "C vm: Links to VM folders/messages" org-vm)
758 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
759 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
760 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
762 (defvar org-export-registered-backends) ; From ox.el.
763 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
764 (declare-function org-export-backend-name "ox" (backend) t)
765 (defcustom org-export-backends '(ascii html icalendar latex odt)
766 "List of export back-ends that should be always available.
768 If a description starts with <C>, the file is not part of Emacs
769 and loading it will require that you have downloaded and properly
770 installed the Org mode distribution.
772 Unlike to `org-modules', libraries in this list will not be
773 loaded along with Org, but only once the export framework is
774 needed.
776 This variable needs to be set before org.el is loaded. If you
777 need to make a change while Emacs is running, use the customize
778 interface or run the following code, where VAL stands for the new
779 value of the variable, after updating it:
781 (progn
782 (setq org-export-registered-backends
783 (cl-remove-if-not
784 (lambda (backend)
785 (let ((name (org-export-backend-name backend)))
786 (or (memq name val)
787 (catch \\='parentp
788 (dolist (b val)
789 (and (org-export-derived-backend-p b name)
790 (throw \\='parentp t)))))))
791 org-export-registered-backends))
792 (let ((new-list (mapcar #\\='org-export-backend-name
793 org-export-registered-backends)))
794 (dolist (backend val)
795 (cond
796 ((not (load (format \"ox-%s\" backend) t t))
797 (message \"Problems while trying to load export back-end \\=`%s\\='\"
798 backend))
799 ((not (memq backend new-list)) (push backend new-list))))
800 (set-default \\='org-export-backends new-list)))
802 Adding a back-end to this list will also pull the back-end it
803 depends on, if any."
804 :group 'org
805 :group 'org-export
806 :version "26.1"
807 :package-version '(Org . "9.0")
808 :initialize 'custom-initialize-set
809 :set (lambda (var val)
810 (if (not (featurep 'ox)) (set-default var val)
811 ;; Any back-end not required anymore (not present in VAL and not
812 ;; a parent of any back-end in the new value) is removed from the
813 ;; list of registered back-ends.
814 (setq org-export-registered-backends
815 (cl-remove-if-not
816 (lambda (backend)
817 (let ((name (org-export-backend-name backend)))
818 (or (memq name val)
819 (catch 'parentp
820 (dolist (b val)
821 (and (org-export-derived-backend-p b name)
822 (throw 'parentp t)))))))
823 org-export-registered-backends))
824 ;; Now build NEW-LIST of both new back-ends and required
825 ;; parents.
826 (let ((new-list (mapcar #'org-export-backend-name
827 org-export-registered-backends)))
828 (dolist (backend val)
829 (cond
830 ((not (load (format "ox-%s" backend) t t))
831 (message "Problems while trying to load export back-end `%s'"
832 backend))
833 ((not (memq backend new-list)) (push backend new-list))))
834 ;; Set VAR to that list with fixed dependencies.
835 (set-default var new-list))))
836 :type '(set :greedy t
837 (const :tag " ascii Export buffer to ASCII format" ascii)
838 (const :tag " beamer Export buffer to Beamer presentation" beamer)
839 (const :tag " html Export buffer to HTML format" html)
840 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
841 (const :tag " latex Export buffer to LaTeX format" latex)
842 (const :tag " man Export buffer to MAN format" man)
843 (const :tag " md Export buffer to Markdown format" md)
844 (const :tag " odt Export buffer to ODT format" odt)
845 (const :tag " org Export buffer to Org format" org)
846 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
847 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
848 (const :tag "C deck Export buffer to deck.js presentations" deck)
849 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
850 (const :tag "C groff Export buffer to Groff format" groff)
851 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
852 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
853 (const :tag "C s5 Export buffer to s5 presentations" s5)
854 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
856 (eval-after-load 'ox
857 '(dolist (backend org-export-backends)
858 (condition-case nil (require (intern (format "ox-%s" backend)))
859 (error (message "Problems while trying to load export back-end `%s'"
860 backend)))))
862 (defcustom org-support-shift-select nil
863 "Non-nil means make shift-cursor commands select text when possible.
864 \\<org-mode-map>\
866 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
867 start selecting a region, or enlarge regions started in this way.
868 In Org mode, in special contexts, these same keys are used for
869 other purposes, important enough to compete with shift selection.
870 Org tries to balance these needs by supporting `shift-select-mode'
871 outside these special contexts, under control of this variable.
873 The default of this variable is nil, to avoid confusing behavior. Shifted
874 cursor keys will then execute Org commands in the following contexts:
875 - on a headline, changing TODO state (left/right) and priority (up/down)
876 - on a time stamp, changing the time
877 - in a plain list item, changing the bullet type
878 - in a property definition line, switching between allowed values
879 - in the BEGIN line of a clock table (changing the time block).
880 Outside these contexts, the commands will throw an error.
882 When this variable is t and the cursor is not in a special
883 context, Org mode will support shift-selection for making and
884 enlarging regions. To make this more effective, the bullet
885 cycling will no longer happen anywhere in an item line, but only
886 if the cursor is exactly on the bullet.
888 If you set this variable to the symbol `always', then the keys
889 will not be special in headlines, property lines, and item lines,
890 to make shift selection work there as well. If this is what you
891 want, you can use the following alternative commands:
892 `\\[org-todo]' and `\\[org-priority]' \
893 to change TODO state and priority,
894 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
895 can be used to switch TODO sets,
896 `\\[org-ctrl-c-minus]' to cycle item bullet types,
897 and properties can be edited by hand or in column view.
899 However, when the cursor is on a timestamp, shift-cursor commands
900 will still edit the time stamp - this is just too good to give up."
901 :group 'org
902 :type '(choice
903 (const :tag "Never" nil)
904 (const :tag "When outside special context" t)
905 (const :tag "Everywhere except timestamps" always)))
907 (defcustom org-loop-over-headlines-in-active-region nil
908 "Shall some commands act upon headlines in the active region?
910 When set to t, some commands will be performed in all headlines
911 within the active region.
913 When set to `start-level', some commands will be performed in all
914 headlines within the active region, provided that these headlines
915 are of the same level than the first one.
917 When set to a string, those commands will be performed on the
918 matching headlines within the active region. Such string must be
919 a tags/property/todo match as it is used in the agenda tags view.
921 The list of commands is: `org-schedule', `org-deadline',
922 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
923 `org-archive-to-archive-sibling'. The archiving commands skip
924 already archived entries."
925 :type '(choice (const :tag "Don't loop" nil)
926 (const :tag "All headlines in active region" t)
927 (const :tag "In active region, headlines at the same level than the first one" start-level)
928 (string :tag "Tags/Property/Todo matcher"))
929 :version "24.1"
930 :group 'org-todo
931 :group 'org-archive)
933 (defcustom org-startup-folded t
934 "Non-nil means entering Org mode will switch to OVERVIEW.
936 This can also be configured on a per-file basis by adding one of
937 the following lines anywhere in the buffer:
939 #+STARTUP: fold (or `overview', this is equivalent)
940 #+STARTUP: nofold (or `showall', this is equivalent)
941 #+STARTUP: content
942 #+STARTUP: showeverything
944 Set `org-agenda-inhibit-startup' to a non-nil value if you want
945 to ignore this option when Org opens agenda files for the first
946 time."
947 :group 'org-startup
948 :type '(choice
949 (const :tag "nofold: show all" nil)
950 (const :tag "fold: overview" t)
951 (const :tag "content: all headlines" content)
952 (const :tag "show everything, even drawers" showeverything)))
954 (defcustom org-startup-truncated t
955 "Non-nil means entering Org mode will set `truncate-lines'.
956 This is useful since some lines containing links can be very long and
957 uninteresting. Also tables look terrible when wrapped.
959 The variable `org-startup-truncated' allows to configure
960 truncation for Org mode different to the other modes that use the
961 variable `truncate-lines' and as a shortcut instead of putting
962 the variable `truncate-lines' into the `org-mode-hook'. If one
963 wants to configure truncation for Org mode not statically but
964 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
965 the variable `truncate-lines' has to be used because in such a
966 case it is too late to set the variable `org-startup-truncated'."
967 :group 'org-startup
968 :type 'boolean)
970 (defcustom org-startup-indented nil
971 "Non-nil means turn on `org-indent-mode' on startup.
972 This can also be configured on a per-file basis by adding one of
973 the following lines anywhere in the buffer:
975 #+STARTUP: indent
976 #+STARTUP: noindent"
977 :group 'org-structure
978 :type '(choice
979 (const :tag "Not" nil)
980 (const :tag "Globally (slow on startup in large files)" t)))
982 (defcustom org-use-sub-superscripts t
983 "Non-nil means interpret \"_\" and \"^\" for display.
985 If you want to control how Org exports those characters, see
986 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
987 used to be an alias for `org-export-with-sub-superscripts' in
988 Org <8.0, it is not anymore.
990 When this option is turned on, you can use TeX-like syntax for
991 sub- and superscripts within the buffer. Several characters after
992 \"_\" or \"^\" will be considered as a single item - so grouping
993 with {} is normally not needed. For example, the following things
994 will be parsed as single sub- or superscripts:
996 10^24 or 10^tau several digits will be considered 1 item.
997 10^-12 or 10^-tau a leading sign with digits or a word
998 x^2-y^3 will be read as x^2 - y^3, because items are
999 terminated by almost any nonword/nondigit char.
1000 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1002 Still, ambiguity is possible. So when in doubt, use {} to enclose
1003 the sub/superscript. If you set this variable to the symbol `{}',
1004 the braces are *required* in order to trigger interpretations as
1005 sub/superscript. This can be helpful in documents that need \"_\"
1006 frequently in plain text."
1007 :group 'org-startup
1008 :version "24.4"
1009 :package-version '(Org . "8.0")
1010 :type '(choice
1011 (const :tag "Always interpret" t)
1012 (const :tag "Only with braces" {})
1013 (const :tag "Never interpret" nil)))
1015 (defcustom org-startup-with-beamer-mode nil
1016 "Non-nil means turn on `org-beamer-mode' on startup.
1017 This can also be configured on a per-file basis by adding one of
1018 the following lines anywhere in the buffer:
1020 #+STARTUP: beamer"
1021 :group 'org-startup
1022 :version "24.1"
1023 :type 'boolean)
1025 (defcustom org-startup-align-all-tables nil
1026 "Non-nil means align all tables when visiting a file.
1027 This can also be configured on a per-file basis by adding one of
1028 the following lines anywhere in the buffer:
1029 #+STARTUP: align
1030 #+STARTUP: noalign"
1031 :group 'org-startup
1032 :type 'boolean)
1034 (defcustom org-startup-shrink-all-tables nil
1035 "Non-nil means shrink all table columns with a width cookie.
1036 This can also be configured on a per-file basis by adding one of
1037 the following lines anywhere in the buffer:
1038 #+STARTUP: shrink"
1039 :group 'org-startup
1040 :type 'boolean
1041 :version "27.1"
1042 :package-version '(Org . "9.2")
1043 :safe #'booleanp)
1045 (defcustom org-startup-with-inline-images nil
1046 "Non-nil means show inline images when loading a new Org file.
1047 This can also be configured on a per-file basis by adding one of
1048 the following lines anywhere in the buffer:
1049 #+STARTUP: inlineimages
1050 #+STARTUP: noinlineimages"
1051 :group 'org-startup
1052 :version "24.1"
1053 :type 'boolean)
1055 (defcustom org-startup-with-latex-preview nil
1056 "Non-nil means preview LaTeX fragments when loading a new Org file.
1058 This can also be configured on a per-file basis by adding one of
1059 the following lines anywhere in the buffer:
1060 #+STARTUP: latexpreview
1061 #+STARTUP: nolatexpreview"
1062 :group 'org-startup
1063 :version "24.4"
1064 :package-version '(Org . "8.0")
1065 :type 'boolean)
1067 (defcustom org-insert-mode-line-in-empty-file nil
1068 "Non-nil means insert the first line setting Org mode in empty files.
1069 When the function `org-mode' is called interactively in an empty file, this
1070 normally means that the file name does not automatically trigger Org mode.
1071 To ensure that the file will always be in Org mode in the future, a
1072 line enforcing Org mode will be inserted into the buffer, if this option
1073 has been set."
1074 :group 'org-startup
1075 :type 'boolean)
1077 (defcustom org-replace-disputed-keys nil
1078 "Non-nil means use alternative key bindings for some keys.
1080 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1081 These keys are also used by other packages like Shift Select mode,
1082 CUA mode or Windmove. If you want to use Org mode together with
1083 one of these other modes, or more generally if you would like to
1084 move some Org mode commands to other keys, set this variable and
1085 configure the keys with the variable `org-disputed-keys'.
1087 This option is only relevant at load-time of Org mode, and must be set
1088 *before* org.el is loaded. Changing it requires a restart of Emacs to
1089 become effective."
1090 :group 'org-startup
1091 :type 'boolean)
1093 (defcustom org-use-extra-keys nil
1094 "Non-nil means use extra key sequence definitions for certain commands.
1095 This happens automatically if `window-system' is nil. This
1096 variable lets you do the same manually. You must set it before
1097 loading Org."
1098 :group 'org-startup
1099 :type 'boolean)
1101 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1103 (defcustom org-disputed-keys
1104 '(([(shift up)] . [(meta p)])
1105 ([(shift down)] . [(meta n)])
1106 ([(shift left)] . [(meta -)])
1107 ([(shift right)] . [(meta +)])
1108 ([(control shift right)] . [(meta shift +)])
1109 ([(control shift left)] . [(meta shift -)]))
1110 "Keys for which Org mode and other modes compete.
1111 This is an alist, cars are the default keys, second element specifies
1112 the alternative to use when `org-replace-disputed-keys' is t.
1114 Keys can be specified in any syntax supported by `define-key'.
1115 The value of this option takes effect only at Org mode startup,
1116 therefore you'll have to restart Emacs to apply it after changing."
1117 :group 'org-startup
1118 :type 'alist)
1120 (defun org-key (key)
1121 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1122 Or return the original if not disputed."
1123 (when org-replace-disputed-keys
1124 (let* ((nkey (key-description key))
1125 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1126 org-disputed-keys)))
1127 (setq key (if x (cdr x) key))))
1128 key)
1130 (defun org-defkey (keymap key def)
1131 "Define a key, possibly translated, as returned by `org-key'."
1132 (define-key keymap (org-key key) def))
1134 (defcustom org-ellipsis nil
1135 "The ellipsis to use in the Org mode outline.
1137 When nil, just use the standard three dots. When a non-empty string,
1138 use that string instead.
1140 The change affects only Org mode (which will then use its own display table).
1141 Changing this requires executing `\\[org-mode]' in a buffer to become
1142 effective."
1143 :group 'org-startup
1144 :type '(choice (const :tag "Default" nil)
1145 (string :tag "String" :value "...#"))
1146 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1148 (defvar org-display-table nil
1149 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1151 (defgroup org-keywords nil
1152 "Keywords in Org mode."
1153 :tag "Org Keywords"
1154 :group 'org)
1156 (defcustom org-closed-keep-when-no-todo nil
1157 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1158 :group 'org-todo
1159 :group 'org-keywords
1160 :version "24.4"
1161 :package-version '(Org . "8.0")
1162 :type 'boolean)
1164 (defgroup org-structure nil
1165 "Options concerning the general structure of Org files."
1166 :tag "Org Structure"
1167 :group 'org)
1169 (defgroup org-reveal-location nil
1170 "Options about how to make context of a location visible."
1171 :tag "Org Reveal Location"
1172 :group 'org-structure)
1174 (defcustom org-show-context-detail '((agenda . local)
1175 (bookmark-jump . lineage)
1176 (isearch . lineage)
1177 (default . ancestors))
1178 "Alist between context and visibility span when revealing a location.
1180 \\<org-mode-map>Some actions may move point into invisible
1181 locations. As a consequence, Org always expose a neighborhood
1182 around point. How much is shown depends on the initial action,
1183 or context. Valid contexts are
1185 agenda when exposing an entry from the agenda
1186 org-goto when using the command `org-goto' (`\\[org-goto]')
1187 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1188 tags-tree when constructing a sparse tree based on tags matches
1189 link-search when exposing search matches associated with a link
1190 mark-goto when exposing the jump goal of a mark
1191 bookmark-jump when exposing a bookmark location
1192 isearch when exiting from an incremental search
1193 default default for all contexts not set explicitly
1195 Allowed visibility spans are
1197 minimal show current headline; if point is not on headline,
1198 also show entry
1200 local show current headline, entry and next headline
1202 ancestors show current headline and its direct ancestors; if
1203 point is not on headline, also show entry
1205 lineage show current headline, its direct ancestors and all
1206 their children; if point is not on headline, also show
1207 entry and first child
1209 tree show current headline, its direct ancestors and all
1210 their children; if point is not on headline, also show
1211 entry and all children
1213 canonical show current headline, its direct ancestors along with
1214 their entries and children; if point is not located on
1215 the headline, also show current entry and all children
1217 As special cases, a nil or t value means show all contexts in
1218 `minimal' or `canonical' view, respectively.
1220 Some views can make displayed information very compact, but also
1221 make it harder to edit the location of the match. In such
1222 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1223 more context."
1224 :group 'org-reveal-location
1225 :version "26.1"
1226 :package-version '(Org . "9.0")
1227 :type '(choice
1228 (const :tag "Canonical" t)
1229 (const :tag "Minimal" nil)
1230 (repeat :greedy t :tag "Individual contexts"
1231 (cons
1232 (choice :tag "Context"
1233 (const agenda)
1234 (const org-goto)
1235 (const occur-tree)
1236 (const tags-tree)
1237 (const link-search)
1238 (const mark-goto)
1239 (const bookmark-jump)
1240 (const isearch)
1241 (const default))
1242 (choice :tag "Detail level"
1243 (const minimal)
1244 (const local)
1245 (const ancestors)
1246 (const lineage)
1247 (const tree)
1248 (const canonical))))))
1250 (defcustom org-indirect-buffer-display 'other-window
1251 "How should indirect tree buffers be displayed?
1253 This applies to indirect buffers created with the commands
1254 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1256 Valid values are:
1257 current-window Display in the current window
1258 other-window Just display in another window.
1259 dedicated-frame Create one new frame, and re-use it each time.
1260 new-frame Make a new frame each time. Note that in this case
1261 previously-made indirect buffers are kept, and you need to
1262 kill these buffers yourself."
1263 :group 'org-structure
1264 :group 'org-agenda-windows
1265 :type '(choice
1266 (const :tag "In current window" current-window)
1267 (const :tag "In current frame, other window" other-window)
1268 (const :tag "Each time a new frame" new-frame)
1269 (const :tag "One dedicated frame" dedicated-frame)))
1271 (defcustom org-use-speed-commands nil
1272 "Non-nil means activate single letter commands at beginning of a headline.
1273 This may also be a function to test for appropriate locations where speed
1274 commands should be active.
1276 For example, to activate speed commands when the point is on any
1277 star at the beginning of the headline, you can do this:
1279 (setq org-use-speed-commands
1280 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1281 :group 'org-structure
1282 :type '(choice
1283 (const :tag "Never" nil)
1284 (const :tag "At beginning of headline stars" t)
1285 (function)))
1287 (defcustom org-speed-commands-user nil
1288 "Alist of additional speed commands.
1289 This list will be checked before `org-speed-commands-default'
1290 when the variable `org-use-speed-commands' is non-nil
1291 and when the cursor is at the beginning of a headline.
1292 The car of each entry is a string with a single letter, which must
1293 be assigned to `self-insert-command' in the global map.
1294 The cdr is either a command to be called interactively, a function
1295 to be called, or a form to be evaluated.
1296 An entry that is just a list with a single string will be interpreted
1297 as a descriptive headline that will be added when listing the speed
1298 commands in the Help buffer using the `?' speed command."
1299 :group 'org-structure
1300 :type '(repeat :value ("k" . ignore)
1301 (choice :value ("k" . ignore)
1302 (list :tag "Descriptive Headline" (string :tag "Headline"))
1303 (cons :tag "Letter and Command"
1304 (string :tag "Command letter")
1305 (choice
1306 (function)
1307 (sexp))))))
1309 (defcustom org-bookmark-names-plist
1310 '(:last-capture "org-capture-last-stored"
1311 :last-refile "org-refile-last-stored"
1312 :last-capture-marker "org-capture-last-stored-marker")
1313 "Names for bookmarks automatically set by some Org commands.
1314 This can provide strings as names for a number of bookmarks Org sets
1315 automatically. The following keys are currently implemented:
1316 :last-capture
1317 :last-capture-marker
1318 :last-refile
1319 When a key does not show up in the property list, the corresponding bookmark
1320 is not set."
1321 :group 'org-structure
1322 :type 'plist)
1324 (defgroup org-cycle nil
1325 "Options concerning visibility cycling in Org mode."
1326 :tag "Org Cycle"
1327 :group 'org-structure)
1329 (defcustom org-cycle-skip-children-state-if-no-children t
1330 "Non-nil means skip CHILDREN state in entries that don't have any."
1331 :group 'org-cycle
1332 :type 'boolean)
1334 (defcustom org-cycle-max-level nil
1335 "Maximum level which should still be subject to visibility cycling.
1336 Levels higher than this will, for cycling, be treated as text, not a headline.
1337 When `org-odd-levels-only' is set, a value of N in this variable actually
1338 means 2N-1 stars as the limiting headline.
1339 When nil, cycle all levels.
1340 Note that the limiting level of cycling is also influenced by
1341 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1342 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1343 than its value."
1344 :group 'org-cycle
1345 :type '(choice
1346 (const :tag "No limit" nil)
1347 (integer :tag "Maximum level")))
1349 (defcustom org-hide-block-startup nil
1350 "Non-nil means entering Org mode will fold all blocks.
1351 This can also be set in on a per-file basis with
1353 #+STARTUP: hideblocks
1354 #+STARTUP: showblocks"
1355 :group 'org-startup
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-global-at-bob nil
1360 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1362 This makes it possible to do global cycling without having to use `S-TAB'
1363 or `\\[universal-argument] TAB'. For this special case to work, the first \
1364 line of the buffer
1365 must not be a headline -- it may be empty or some other text.
1367 When used in this way, `org-cycle-hook' is disabled temporarily to make
1368 sure the cursor stays at the beginning of the buffer.
1370 When this option is nil, don't do anything special at the beginning of
1371 the buffer."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-level-after-item/entry-creation t
1376 "Non-nil means cycle entry level or item indentation in new empty entries.
1378 When the cursor is at the end of an empty headline, i.e., with only stars
1379 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1380 and then all possible ancestor states, before returning to the original state.
1381 This makes data entry extremely fast: M-RET to create a new headline,
1382 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1384 When the cursor is at the end of an empty plain list item, one TAB will
1385 make it a subitem, two or more tabs will back up to make this an item
1386 higher up in the item hierarchy."
1387 :group 'org-cycle
1388 :type 'boolean)
1390 (defcustom org-cycle-emulate-tab t
1391 "Where should `org-cycle' emulate TAB.
1392 nil Never
1393 white Only in completely white lines
1394 whitestart Only at the beginning of lines, before the first non-white char
1395 t Everywhere except in headlines
1396 exc-hl-bol Everywhere except at the start of a headline
1397 If TAB is used in a place where it does not emulate TAB, the current subtree
1398 visibility is cycled."
1399 :group 'org-cycle
1400 :type '(choice (const :tag "Never" nil)
1401 (const :tag "Only in completely white lines" white)
1402 (const :tag "Before first char in a line" whitestart)
1403 (const :tag "Everywhere except in headlines" t)
1404 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1406 (defcustom org-cycle-separator-lines 2
1407 "Number of empty lines needed to keep an empty line between collapsed trees.
1408 If you leave an empty line between the end of a subtree and the following
1409 headline, this empty line is hidden when the subtree is folded.
1410 Org mode will leave (exactly) one empty line visible if the number of
1411 empty lines is equal or larger to the number given in this variable.
1412 So the default 2 means at least 2 empty lines after the end of a subtree
1413 are needed to produce free space between a collapsed subtree and the
1414 following headline.
1416 If the number is negative, and the number of empty lines is at least -N,
1417 all empty lines are shown.
1419 Special case: when 0, never leave empty lines in collapsed view."
1420 :group 'org-cycle
1421 :type 'integer)
1422 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1424 (defcustom org-pre-cycle-hook nil
1425 "Hook that is run before visibility cycling is happening.
1426 The function(s) in this hook must accept a single argument which indicates
1427 the new state that will be set right after running this hook. The
1428 argument is a symbol. Before a global state change, it can have the values
1429 `overview', `content', or `all'. Before a local state change, it can have
1430 the values `folded', `children', or `subtree'."
1431 :group 'org-cycle
1432 :type 'hook)
1434 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1435 org-cycle-show-empty-lines
1436 org-optimize-window-after-visibility-change)
1437 "Hook that is run after `org-cycle' has changed the buffer visibility.
1438 The function(s) in this hook must accept a single argument which indicates
1439 the new state that was set by the most recent `org-cycle' command. The
1440 argument is a symbol. After a global state change, it can have the values
1441 `overview', `contents', or `all'. After a local state change, it can have
1442 the values `folded', `children', or `subtree'."
1443 :group 'org-cycle
1444 :type 'hook
1445 :version "26.1"
1446 :package-version '(Org . "8.3"))
1448 (defgroup org-edit-structure nil
1449 "Options concerning structure editing in Org mode."
1450 :tag "Org Edit Structure"
1451 :group 'org-structure)
1453 (defcustom org-odd-levels-only nil
1454 "Non-nil means skip even levels and only use odd levels for the outline.
1455 This has the effect that two stars are being added/taken away in
1456 promotion/demotion commands. It also influences how levels are
1457 handled by the exporters.
1458 Changing it requires restart of `font-lock-mode' to become effective
1459 for fontification also in regions already fontified.
1460 You may also set this on a per-file basis by adding one of the following
1461 lines to the buffer:
1463 #+STARTUP: odd
1464 #+STARTUP: oddeven"
1465 :group 'org-edit-structure
1466 :group 'org-appearance
1467 :type 'boolean)
1469 (defcustom org-adapt-indentation t
1470 "Non-nil means adapt indentation to outline node level.
1472 When this variable is set, Org assumes that you write outlines by
1473 indenting text in each node to align with the headline (after the
1474 stars). The following issues are influenced by this variable:
1476 - The indentation is increased by one space in a demotion
1477 command, and decreased by one in a promotion command. However,
1478 in the latter case, if shifting some line in the entry body
1479 would alter document structure (e.g., insert a new headline),
1480 indentation is not changed at all.
1482 - Property drawers and planning information is inserted indented
1483 when this variable is set. When nil, they will not be indented.
1485 - TAB indents a line relative to current level. The lines below
1486 a headline will be indented when this variable is set.
1488 Note that this is all about true indentation, by adding and
1489 removing space characters. See also \"org-indent.el\" which does
1490 level-dependent indentation in a virtual way, i.e. at display
1491 time in Emacs."
1492 :group 'org-edit-structure
1493 :type 'boolean
1494 :safe #'booleanp)
1496 (defcustom org-special-ctrl-a/e nil
1497 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1499 When t, `C-a' will bring back the cursor to the beginning of the
1500 headline text, i.e. after the stars and after a possible TODO
1501 keyword. In an item, this will be the position after bullet and
1502 check-box, if any. When the cursor is already at that position,
1503 another `C-a' will bring it to the beginning of the line.
1505 `C-e' will jump to the end of the headline, ignoring the presence
1506 of tags in the headline. A second `C-e' will then jump to the
1507 true end of the line, after any tags. This also means that, when
1508 this variable is non-nil, `C-e' also will never jump beyond the
1509 end of the heading of a folded section, i.e. not after the
1510 ellipses.
1512 When set to the symbol `reversed', the first `C-a' or `C-e' works
1513 normally, going to the true line boundary first. Only a directly
1514 following, identical keypress will bring the cursor to the
1515 special positions.
1517 This may also be a cons cell where the behavior for `C-a' and
1518 `C-e' is set separately."
1519 :group 'org-edit-structure
1520 :type '(choice
1521 (const :tag "off" nil)
1522 (const :tag "on: after stars/bullet and before tags first" t)
1523 (const :tag "reversed: true line boundary first" reversed)
1524 (cons :tag "Set C-a and C-e separately"
1525 (choice :tag "Special C-a"
1526 (const :tag "off" nil)
1527 (const :tag "on: after stars/bullet first" t)
1528 (const :tag "reversed: before stars/bullet first" reversed))
1529 (choice :tag "Special C-e"
1530 (const :tag "off" nil)
1531 (const :tag "on: before tags first" t)
1532 (const :tag "reversed: after tags first" reversed)))))
1533 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1535 (defcustom org-special-ctrl-k nil
1536 "Non-nil means `C-k' will behave specially in headlines.
1537 When nil, `C-k' will call the default `kill-line' command.
1538 When t, the following will happen while the cursor is in the headline:
1540 - When the cursor is at the beginning of a headline, kill the entire
1541 line and possible the folded subtree below the line.
1542 - When in the middle of the headline text, kill the headline up to the tags.
1543 - When after the headline text, kill the tags."
1544 :group 'org-edit-structure
1545 :type 'boolean)
1547 (defcustom org-ctrl-k-protect-subtree nil
1548 "Non-nil means, do not delete a hidden subtree with C-k.
1549 When set to the symbol `error', simply throw an error when C-k is
1550 used to kill (part-of) a headline that has hidden text behind it.
1551 Any other non-nil value will result in a query to the user, if it is
1552 OK to kill that hidden subtree. When nil, kill without remorse."
1553 :group 'org-edit-structure
1554 :version "24.1"
1555 :type '(choice
1556 (const :tag "Do not protect hidden subtrees" nil)
1557 (const :tag "Protect hidden subtrees with a security query" t)
1558 (const :tag "Never kill a hidden subtree with C-k" error)))
1560 (defcustom org-special-ctrl-o t
1561 "Non-nil means, make `C-o' insert a row in tables."
1562 :group 'org-edit-structure
1563 :type 'boolean)
1565 (defcustom org-catch-invisible-edits nil
1566 "Check if in invisible region before inserting or deleting a character.
1567 Valid values are:
1569 nil Do not check, so just do invisible edits.
1570 error Throw an error and do nothing.
1571 show Make point visible, and do the requested edit.
1572 show-and-error Make point visible, then throw an error and abort the edit.
1573 smart Make point visible, and do insertion/deletion if it is
1574 adjacent to visible text and the change feels predictable.
1575 Never delete a previously invisible character or add in the
1576 middle or right after an invisible region. Basically, this
1577 allows insertion and backward-delete right before ellipses.
1578 FIXME: maybe in this case we should not even show?"
1579 :group 'org-edit-structure
1580 :version "24.1"
1581 :type '(choice
1582 (const :tag "Do not check" nil)
1583 (const :tag "Throw error when trying to edit" error)
1584 (const :tag "Unhide, but do not do the edit" show-and-error)
1585 (const :tag "Show invisible part and do the edit" show)
1586 (const :tag "Be smart and do the right thing" smart)))
1588 (defcustom org-yank-folded-subtrees t
1589 "Non-nil means when yanking subtrees, fold them.
1590 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1591 it starts with a heading and all other headings in it are either children
1592 or siblings, then fold all the subtrees. However, do this only if no
1593 text after the yank would be swallowed into a folded tree by this action."
1594 :group 'org-edit-structure
1595 :type 'boolean)
1597 (defcustom org-yank-adjusted-subtrees nil
1598 "Non-nil means when yanking subtrees, adjust the level.
1599 With this setting, `org-paste-subtree' is used to insert the subtree, see
1600 this function for details."
1601 :group 'org-edit-structure
1602 :type 'boolean)
1604 (defcustom org-M-RET-may-split-line '((default . t))
1605 "Non-nil means M-RET will split the line at the cursor position.
1606 When nil, it will go to the end of the line before making a
1607 new line.
1608 You may also set this option in a different way for different
1609 contexts. Valid contexts are:
1611 headline when creating a new headline
1612 item when creating a new item
1613 table in a table field
1614 default the value to be used for all contexts not explicitly
1615 customized"
1616 :group 'org-structure
1617 :group 'org-table
1618 :type '(choice
1619 (const :tag "Always" t)
1620 (const :tag "Never" nil)
1621 (repeat :greedy t :tag "Individual contexts"
1622 (cons
1623 (choice :tag "Context"
1624 (const headline)
1625 (const item)
1626 (const table)
1627 (const default))
1628 (boolean)))))
1631 (defcustom org-insert-heading-respect-content nil
1632 "Non-nil means insert new headings after the current subtree.
1633 \\<org-mode-map>
1634 When nil, the new heading is created directly after the current line.
1635 The commands `\\[org-insert-heading-respect-content]' and \
1636 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1637 for the duration of the command."
1638 :group 'org-structure
1639 :type 'boolean)
1641 (defcustom org-blank-before-new-entry '((heading . auto)
1642 (plain-list-item . auto))
1643 "Should `org-insert-heading' leave a blank line before new heading/item?
1644 The value is an alist, with `heading' and `plain-list-item' as CAR,
1645 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1646 which case Org will look at the surrounding headings/items and try to
1647 make an intelligent decision whether to insert a blank line or not."
1648 :group 'org-edit-structure
1649 :type '(list
1650 (cons (const heading)
1651 (choice (const :tag "Never" nil)
1652 (const :tag "Always" t)
1653 (const :tag "Auto" auto)))
1654 (cons (const plain-list-item)
1655 (choice (const :tag "Never" nil)
1656 (const :tag "Always" t)
1657 (const :tag "Auto" auto)))))
1659 (defcustom org-insert-heading-hook nil
1660 "Hook being run after inserting a new heading."
1661 :group 'org-edit-structure
1662 :type 'hook)
1664 (defcustom org-enable-fixed-width-editor t
1665 "Non-nil means lines starting with \":\" are treated as fixed-width.
1666 This currently only means they are never auto-wrapped.
1667 When nil, such lines will be treated like ordinary lines."
1668 :group 'org-edit-structure
1669 :type 'boolean)
1671 (defgroup org-sparse-trees nil
1672 "Options concerning sparse trees in Org mode."
1673 :tag "Org Sparse Trees"
1674 :group 'org-structure)
1676 (defcustom org-highlight-sparse-tree-matches t
1677 "Non-nil means highlight all matches that define a sparse tree.
1678 The highlights will automatically disappear the next time the buffer is
1679 changed by an edit command."
1680 :group 'org-sparse-trees
1681 :type 'boolean)
1683 (defcustom org-remove-highlights-with-change t
1684 "Non-nil means any change to the buffer will remove temporary highlights.
1685 \\<org-mode-map>\
1686 Such highlights are created by `org-occur' and `org-clock-display'.
1687 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1688 to get rid of the highlights.
1689 The highlights created by `org-toggle-latex-fragment' always need
1690 `\\[org-toggle-latex-fragment]' to be removed."
1691 :group 'org-sparse-trees
1692 :group 'org-time
1693 :type 'boolean)
1695 (defcustom org-occur-case-fold-search t
1696 "Non-nil means `org-occur' should be case-insensitive.
1697 If set to `smart' the search will be case-insensitive only if it
1698 doesn't specify any upper case character."
1699 :group 'org-sparse-trees
1700 :version "26.1"
1701 :type '(choice
1702 (const :tag "Case-sensitive" nil)
1703 (const :tag "Case-insensitive" t)
1704 (const :tag "Case-insensitive for lower case searches only" smart)))
1706 (defcustom org-occur-hook '(org-first-headline-recenter)
1707 "Hook that is run after `org-occur' has constructed a sparse tree.
1708 This can be used to recenter the window to show as much of the structure
1709 as possible."
1710 :group 'org-sparse-trees
1711 :type 'hook)
1713 (defgroup org-table nil
1714 "Options concerning tables in Org mode."
1715 :tag "Org Table"
1716 :group 'org)
1718 (defcustom org-self-insert-cluster-for-undo nil
1719 "Non-nil means cluster self-insert commands for undo when possible.
1720 If this is set, then, like in the Emacs command loop, 20 consecutive
1721 characters will be undone together.
1722 This is configurable, because there is some impact on typing performance."
1723 :group 'org-table
1724 :type 'boolean)
1726 (defcustom org-table-tab-recognizes-table.el t
1727 "Non-nil means TAB will automatically notice a table.el table.
1728 When it sees such a table, it moves point into it and - if necessary -
1729 calls `table-recognize-table'."
1730 :group 'org-table-editing
1731 :type 'boolean)
1733 (defgroup org-link nil
1734 "Options concerning links in Org mode."
1735 :tag "Org Link"
1736 :group 'org)
1738 (defvar-local org-link-abbrev-alist-local nil
1739 "Buffer-local version of `org-link-abbrev-alist', which see.
1740 The value of this is taken from the #+LINK lines.")
1742 (defcustom org-link-parameters
1743 '(("doi" :follow org--open-doi-link)
1744 ("elisp" :follow org--open-elisp-link)
1745 ("file" :complete org-file-complete-link)
1746 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1747 ("help" :follow org--open-help-link)
1748 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1749 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1750 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1751 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1752 ("shell" :follow org--open-shell-link))
1753 "An alist of properties that defines all the links in Org mode.
1754 The key in each association is a string of the link type.
1755 Subsequent optional elements make up a p-list of link properties.
1757 :follow - A function that takes the link path as an argument.
1759 :export - A function that takes the link path, description and
1760 export-backend as arguments.
1762 :store - A function responsible for storing the link. See the
1763 function `org-store-link-functions'.
1765 :complete - A function that inserts a link with completion. The
1766 function takes one optional prefix arg.
1768 :face - A face for the link, or a function that returns a face.
1769 The function takes one argument which is the link path. The
1770 default face is `org-link'.
1772 :mouse-face - The mouse-face. The default is `highlight'.
1774 :display - `full' will not fold the link in descriptive
1775 display. Default is `org-link'.
1777 :help-echo - A string or function that takes (window object position)
1778 as arguments and returns a string.
1780 :keymap - A keymap that is active on the link. The default is
1781 `org-mouse-map'.
1783 :htmlize-link - A function for the htmlize-link. Defaults
1784 to (list :uri \"type:path\")
1786 :activate-func - A function to run at the end of font-lock
1787 activation. The function must accept (link-start link-end path bracketp)
1788 as arguments."
1789 :group 'org-link
1790 :type '(alist :tag "Link display parameters"
1791 :value-type plist)
1792 :version "26.1"
1793 :package-version '(Org . "9.1"))
1795 (defun org-link-get-parameter (type key)
1796 "Get TYPE link property for KEY.
1797 TYPE is a string and KEY is a plist keyword."
1798 (plist-get
1799 (cdr (assoc type org-link-parameters))
1800 key))
1802 (defun org-link-set-parameters (type &rest parameters)
1803 "Set link TYPE properties to PARAMETERS.
1804 PARAMETERS should be :key val pairs."
1805 (let ((data (assoc type org-link-parameters)))
1806 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1807 (push (cons type parameters) org-link-parameters)
1808 (org-make-link-regexps)
1809 (org-element-update-syntax))))
1811 (defun org-link-types ()
1812 "Return a list of known link types."
1813 (mapcar #'car org-link-parameters))
1815 (defcustom org-link-abbrev-alist nil
1816 "Alist of link abbreviations.
1817 The car of each element is a string, to be replaced at the start of a link.
1818 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1819 links in Org buffers can have an optional tag after a double colon, e.g.,
1821 [[linkkey:tag][description]]
1823 The `linkkey' must be a single word, starting with a letter, followed
1824 by letters, numbers, `-' or `_'.
1826 If REPLACE is a string, the tag will simply be appended to create the link.
1827 If the string contains \"%s\", the tag will be inserted there. If the string
1828 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1829 at that point (see the function `url-hexify-string'). If the string contains
1830 the specifier \"%(my-function)\", then the custom function `my-function' will
1831 be invoked: this function takes the tag as its only argument and must return
1832 a string.
1834 REPLACE may also be a function that will be called with the tag as the
1835 only argument to create the link, which should be returned as a string.
1837 See the manual for examples."
1838 :group 'org-link
1839 :type '(repeat
1840 (cons
1841 (string :tag "Protocol")
1842 (choice
1843 (string :tag "Format")
1844 (function)))))
1846 (defcustom org-descriptive-links t
1847 "Non-nil means Org will display descriptive links.
1848 E.g. [[https://orgmode.org][Org website]] will be displayed as
1849 \"Org Website\", hiding the link itself and just displaying its
1850 description. When set to nil, Org will display the full links
1851 literally.
1853 You can interactively set the value of this variable by calling
1854 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1855 :group 'org-link
1856 :type 'boolean)
1858 (defcustom org-link-file-path-type 'adaptive
1859 "How the path name in file links should be stored.
1860 Valid values are:
1862 relative Relative to the current directory, i.e. the directory of the file
1863 into which the link is being inserted.
1864 absolute Absolute path, if possible with ~ for home directory.
1865 noabbrev Absolute path, no abbreviation of home directory.
1866 adaptive Use relative path for files in the current directory and sub-
1867 directories of it. For other files, use an absolute path."
1868 :group 'org-link
1869 :type '(choice
1870 (const relative)
1871 (const absolute)
1872 (const noabbrev)
1873 (const adaptive)))
1875 (defvaralias 'org-activate-links 'org-highlight-links)
1876 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1877 "Types of links that should be highlighted in Org files.
1879 This is a list of symbols, each one of them leading to the
1880 highlighting of a certain link type.
1882 You can still open links that are not highlighted.
1884 In principle, it does not hurt to turn on highlighting for all
1885 link types. There may be a small gain when turning off unused
1886 link types. The types are:
1888 bracket The recommended [[link][description]] or [[link]] links with hiding.
1889 angle Links in angular brackets that may contain whitespace like
1890 <bbdb:Carsten Dominik>.
1891 plain Plain links in normal text, no whitespace, like http://google.com.
1892 radio Text that is matched by a radio target, see manual for details.
1893 tag Tag settings in a headline (link to tag search).
1894 date Time stamps (link to calendar).
1895 footnote Footnote labels.
1897 If you set this variable during an Emacs session, use `org-mode-restart'
1898 in the Org buffer so that the change takes effect."
1899 :group 'org-link
1900 :group 'org-appearance
1901 :type '(set :greedy t
1902 (const :tag "Double bracket links" bracket)
1903 (const :tag "Angular bracket links" angle)
1904 (const :tag "Plain text links" plain)
1905 (const :tag "Radio target matches" radio)
1906 (const :tag "Tags" tag)
1907 (const :tag "Timestamps" date)
1908 (const :tag "Footnotes" footnote)))
1910 (defcustom org-make-link-description-function nil
1911 "Function to use for generating link descriptions from links.
1912 This function must take two parameters: the first one is the
1913 link, the second one is the description generated by
1914 `org-insert-link'. The function should return the description to
1915 use."
1916 :group 'org-link
1917 :type '(choice (const nil) (function)))
1919 (defgroup org-link-store nil
1920 "Options concerning storing links in Org mode."
1921 :tag "Org Store Link"
1922 :group 'org-link)
1924 (defcustom org-url-hexify-p t
1925 "When non-nil, hexify URL when creating a link."
1926 :type 'boolean
1927 :version "24.3"
1928 :group 'org-link-store)
1930 (defcustom org-email-link-description-format "Email %c: %.30s"
1931 "Format of the description part of a link to an email or usenet message.
1932 The following %-escapes will be replaced by corresponding information:
1934 %F full \"From\" field
1935 %f name, taken from \"From\" field, address if no name
1936 %T full \"To\" field
1937 %t first name in \"To\" field, address if no name
1938 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1939 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1940 %s subject
1941 %d date
1942 %m message-id.
1944 You may use normal field width specification between the % and the letter.
1945 This is for example useful to limit the length of the subject.
1947 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1948 :group 'org-link-store
1949 :type 'string)
1951 (defcustom org-from-is-user-regexp
1952 (let (r1 r2)
1953 (when (and user-mail-address (not (string= user-mail-address "")))
1954 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1955 (when (and user-full-name (not (string= user-full-name "")))
1956 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1957 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1958 "Regexp matched against the \"From:\" header of an email or usenet message.
1959 It should match if the message is from the user him/herself."
1960 :group 'org-link-store
1961 :type 'regexp)
1963 (defcustom org-context-in-file-links t
1964 "Non-nil means file links from `org-store-link' contain context.
1965 \\<org-mode-map>
1966 A search string will be added to the file name with :: as separator
1967 and used to find the context when the link is activated by the command
1968 `org-open-at-point'. When this option is t, the entire active region
1969 will be placed in the search string of the file link. If set to a
1970 positive integer, only the first n lines of context will be stored.
1972 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1973 \\[org-store-link]')
1974 negates this setting for the duration of the command."
1975 :group 'org-link-store
1976 :type '(choice boolean integer))
1978 (defcustom org-keep-stored-link-after-insertion nil
1979 "Non-nil means keep link in list for entire session.
1980 \\<org-mode-map>
1981 The command `org-store-link' adds a link pointing to the current
1982 location to an internal list. These links accumulate during a session.
1983 The command `org-insert-link' can be used to insert links into any
1984 Org file (offering completion for all stored links).
1986 When this option is nil, every link which has been inserted once using
1987 `\\[org-insert-link]' will be removed from the list, to make completing the \
1988 unused
1989 links more efficient."
1990 :group 'org-link-store
1991 :type 'boolean)
1993 (defgroup org-link-follow nil
1994 "Options concerning following links in Org mode."
1995 :tag "Org Follow Link"
1996 :group 'org-link)
1998 (defcustom org-link-translation-function nil
1999 "Function to translate links with different syntax to Org syntax.
2000 This can be used to translate links created for example by the Planner
2001 or emacs-wiki packages to Org syntax.
2002 The function must accept two parameters, a TYPE containing the link
2003 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2004 which is everything after the link protocol. It should return a cons
2005 with possibly modified values of type and path.
2006 Org contains a function for this, so if you set this variable to
2007 `org-translate-link-from-planner', you should be able follow many
2008 links created by planner."
2009 :group 'org-link-follow
2010 :type '(choice (const nil) (function)))
2012 (defcustom org-follow-link-hook nil
2013 "Hook that is run after a link has been followed."
2014 :group 'org-link-follow
2015 :type 'hook)
2017 (defcustom org-tab-follows-link nil
2018 "Non-nil means on links TAB will follow the link.
2019 Needs to be set before org.el is loaded.
2020 This really should not be used, it does not make sense, and the
2021 implementation is bad."
2022 :group 'org-link-follow
2023 :type 'boolean)
2025 (defcustom org-return-follows-link nil
2026 "Non-nil means on links RET will follow the link.
2027 In tables, the special behavior of RET has precedence."
2028 :group 'org-link-follow
2029 :type 'boolean)
2031 (defcustom org-mouse-1-follows-link
2032 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2033 "Non-nil means mouse-1 on a link will follow the link.
2034 A longer mouse click will still set point. Needs to be set
2035 before org.el is loaded."
2036 :group 'org-link-follow
2037 :version "26.1"
2038 :package-version '(Org . "8.3")
2039 :type '(choice
2040 (const :tag "A double click follows the link" double)
2041 (const :tag "Unconditionally follow the link with mouse-1" t)
2042 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2044 (defcustom org-mark-ring-length 4
2045 "Number of different positions to be recorded in the ring.
2046 Changing this requires a restart of Emacs to work correctly."
2047 :group 'org-link-follow
2048 :type 'integer)
2050 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2051 "Non-nil means internal fuzzy links can only match headlines.
2053 When nil, the a fuzzy link may point to a target or a named
2054 construct in the document. When set to the special value
2055 `query-to-create', offer to create a new headline when none
2056 matched.
2058 Spaces and statistics cookies are ignored during heading searches."
2059 :group 'org-link-follow
2060 :version "24.1"
2061 :type '(choice
2062 (const :tag "Use fuzzy text search" nil)
2063 (const :tag "Match only exact headline" t)
2064 (const :tag "Match exact headline or query to create it"
2065 query-to-create))
2066 :safe #'symbolp)
2068 (defcustom org-link-frame-setup
2069 '((vm . vm-visit-folder-other-frame)
2070 (vm-imap . vm-visit-imap-folder-other-frame)
2071 (gnus . org-gnus-no-new-news)
2072 (file . find-file-other-window)
2073 (wl . wl-other-frame))
2074 "Setup the frame configuration for following links.
2075 When following a link with Emacs, it may often be useful to display
2076 this link in another window or frame. This variable can be used to
2077 set this up for the different types of links.
2078 For VM, use any of
2079 `vm-visit-folder'
2080 `vm-visit-folder-other-window'
2081 `vm-visit-folder-other-frame'
2082 For Gnus, use any of
2083 `gnus'
2084 `gnus-other-frame'
2085 `org-gnus-no-new-news'
2086 For FILE, use any of
2087 `find-file'
2088 `find-file-other-window'
2089 `find-file-other-frame'
2090 For Wanderlust use any of
2091 `wl'
2092 `wl-other-frame'
2093 For the calendar, use the variable `calendar-setup'.
2094 For BBDB, it is currently only possible to display the matches in
2095 another window."
2096 :group 'org-link-follow
2097 :type '(list
2098 (cons (const vm)
2099 (choice
2100 (const vm-visit-folder)
2101 (const vm-visit-folder-other-window)
2102 (const vm-visit-folder-other-frame)))
2103 (cons (const vm-imap)
2104 (choice
2105 (const vm-visit-imap-folder)
2106 (const vm-visit-imap-folder-other-window)
2107 (const vm-visit-imap-folder-other-frame)))
2108 (cons (const gnus)
2109 (choice
2110 (const gnus)
2111 (const gnus-other-frame)
2112 (const org-gnus-no-new-news)))
2113 (cons (const file)
2114 (choice
2115 (const find-file)
2116 (const find-file-other-window)
2117 (const find-file-other-frame)))
2118 (cons (const wl)
2119 (choice
2120 (const wl)
2121 (const wl-other-frame)))))
2123 (defcustom org-display-internal-link-with-indirect-buffer nil
2124 "Non-nil means use indirect buffer to display infile links.
2125 Activating internal links (from one location in a file to another location
2126 in the same file) normally just jumps to the location. When the link is
2127 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2128 is displayed in
2129 another window. When this option is set, the other window actually displays
2130 an indirect buffer clone of the current buffer, to avoid any visibility
2131 changes to the current buffer."
2132 :group 'org-link-follow
2133 :type 'boolean)
2135 (defcustom org-open-non-existing-files nil
2136 "Non-nil means `org-open-file' will open non-existing files.
2137 When nil, an error will be generated.
2138 This variable applies only to external applications because they
2139 might choke on non-existing files. If the link is to a file that
2140 will be opened in Emacs, the variable is ignored."
2141 :group 'org-link-follow
2142 :type 'boolean)
2144 (defcustom org-open-directory-means-index-dot-org nil
2145 "Non-nil means a link to a directory really means to index.org.
2146 When nil, following a directory link will run dired or open a finder/explorer
2147 window on that directory."
2148 :group 'org-link-follow
2149 :type 'boolean)
2151 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2152 "Non-nil means ask for confirmation before executing shell links.
2153 Shell links can be dangerous: just think about a link
2155 [[shell:rm -rf ~/*][Google Search]]
2157 This link would show up in your Org document as \"Google Search\",
2158 but really it would remove your entire home directory.
2159 Therefore we advise against setting this variable to nil.
2160 Just change it to `y-or-n-p' if you want to confirm with a
2161 single keystroke rather than having to type \"yes\"."
2162 :group 'org-link-follow
2163 :type '(choice
2164 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2165 (const :tag "with y-or-n (faster)" y-or-n-p)
2166 (const :tag "no confirmation (dangerous)" nil)))
2167 (put 'org-confirm-shell-link-function
2168 'safe-local-variable
2169 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2171 (defcustom org-confirm-shell-link-not-regexp ""
2172 "A regexp to skip confirmation for shell links."
2173 :group 'org-link-follow
2174 :version "24.1"
2175 :type 'regexp)
2177 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2178 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2179 Elisp links can be dangerous: just think about a link
2181 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2183 This link would show up in your Org document as \"Google Search\",
2184 but really it would remove your entire home directory.
2185 Therefore we advise against setting this variable to nil.
2186 Just change it to `y-or-n-p' if you want to confirm with a
2187 single keystroke rather than having to type \"yes\"."
2188 :group 'org-link-follow
2189 :type '(choice
2190 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2191 (const :tag "with y-or-n (faster)" y-or-n-p)
2192 (const :tag "no confirmation (dangerous)" nil)))
2193 (put 'org-confirm-shell-link-function
2194 'safe-local-variable
2195 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2197 (defcustom org-confirm-elisp-link-not-regexp ""
2198 "A regexp to skip confirmation for Elisp links."
2199 :group 'org-link-follow
2200 :version "24.1"
2201 :type 'regexp)
2203 (defconst org-file-apps-defaults-gnu
2204 '((remote . emacs)
2205 (system . mailcap)
2206 (t . mailcap))
2207 "Default file applications on a UNIX or GNU/Linux system.
2208 See `org-file-apps'.")
2210 (defconst org-file-apps-defaults-macosx
2211 '((remote . emacs)
2212 (system . "open %s")
2213 ("ps.gz" . "gv %s")
2214 ("eps.gz" . "gv %s")
2215 ("dvi" . "xdvi %s")
2216 ("fig" . "xfig %s")
2217 (t . "open %s"))
2218 "Default file applications on a macOS system.
2219 The system \"open\" is known as a default, but we use X11 applications
2220 for some files for which the OS does not have a good default.
2221 See `org-file-apps'.")
2223 (defconst org-file-apps-defaults-windowsnt
2224 (list '(remote . emacs)
2225 (cons 'system (lambda (file _path)
2226 (with-no-warnings (w32-shell-execute "open" file))))
2227 (cons t (lambda (file _path)
2228 (with-no-warnings (w32-shell-execute "open" file)))))
2229 "Default file applications on a Windows NT system.
2230 The system \"open\" is used for most files.
2231 See `org-file-apps'.")
2233 (defcustom org-file-apps
2234 '((auto-mode . emacs)
2235 ("\\.mm\\'" . default)
2236 ("\\.x?html?\\'" . default)
2237 ("\\.pdf\\'" . default))
2238 "External applications for opening `file:path' items in a document.
2239 \\<org-mode-map>\
2241 Org mode uses system defaults for different file types, but
2242 you can use this variable to set the application for a given file
2243 extension. The entries in this list are cons cells where the car identifies
2244 files and the cdr the corresponding command.
2246 Possible values for the file identifier are:
2248 \"string\" A string as a file identifier can be interpreted in different
2249 ways, depending on its contents:
2251 - Alphanumeric characters only:
2252 Match links with this file extension.
2253 Example: (\"pdf\" . \"evince %s\")
2254 to open PDFs with evince.
2256 - Regular expression: Match links where the
2257 filename matches the regexp. If you want to
2258 use groups here, use shy groups.
2260 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2261 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2262 to open *.html and *.xhtml with firefox.
2264 - Regular expression which contains (non-shy) groups:
2265 Match links where the whole link, including \"::\", and
2266 anything after that, matches the regexp.
2267 In a custom command string, %1, %2, etc. are replaced with
2268 the parts of the link that were matched by the groups.
2269 For backwards compatibility, if a command string is given
2270 that does not use any of the group matches, this case is
2271 handled identically to the second one (i.e. match against
2272 file name only).
2273 In a custom function, you can access the group matches with
2274 (match-string n link).
2276 Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
2277 \"evince -p %1 %s\")
2278 to open [[file:document.pdf::5]] with evince at page 5.
2280 `directory' Matches a directory
2281 `remote' Matches a remote file, accessible through tramp or efs.
2282 Remote files most likely should be visited through Emacs
2283 because external applications cannot handle such paths.
2284 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2285 so all files Emacs knows how to handle. Using this with
2286 command `emacs' will open most files in Emacs. Beware that this
2287 will also open html files inside Emacs, unless you add
2288 (\"html\" . default) to the list as well.
2289 `system' The system command to open files, like `open' on Windows
2290 and macOS, and mailcap under GNU/Linux. This is the command
2291 that will be selected if you call `org-open-at-point' with a
2292 double prefix argument (`\\[universal-argument] \
2293 \\[universal-argument] \\[org-open-at-point]').
2294 t Default for files not matched by any of the other options.
2296 Possible values for the command are:
2298 `emacs' The file will be visited by the current Emacs process.
2299 `default' Use the default application for this file type, which is the
2300 association for t in the list, most likely in the system-specific
2301 part. This can be used to overrule an unwanted setting in the
2302 system-specific variable.
2303 `system' Use the system command for opening files, like \"open\".
2304 This command is specified by the entry whose car is `system'.
2305 Most likely, the system-specific version of this variable
2306 does define this command, but you can overrule/replace it
2307 here.
2308 `mailcap' Use command specified in the mailcaps.
2309 string A command to be executed by a shell; %s will be replaced
2310 by the path to the file.
2311 function A Lisp function, which will be called with two arguments:
2312 the file path and the original link string, without the
2313 \"file:\" prefix.
2315 For more examples, see the system specific constants
2316 `org-file-apps-defaults-macosx'
2317 `org-file-apps-defaults-windowsnt'
2318 `org-file-apps-defaults-gnu'."
2319 :group 'org-link-follow
2320 :type '(repeat
2321 (cons (choice :value ""
2322 (string :tag "Extension")
2323 (const :tag "System command to open files" system)
2324 (const :tag "Default for unrecognized files" t)
2325 (const :tag "Remote file" remote)
2326 (const :tag "Links to a directory" directory)
2327 (const :tag "Any files that have Emacs modes"
2328 auto-mode))
2329 (choice :value ""
2330 (const :tag "Visit with Emacs" emacs)
2331 (const :tag "Use default" default)
2332 (const :tag "Use the system command" system)
2333 (string :tag "Command")
2334 (function :tag "Function")))))
2336 (defcustom org-doi-server-url "http://dx.doi.org/"
2337 "The URL of the DOI server."
2338 :type 'string
2339 :version "24.3"
2340 :group 'org-link-follow)
2342 (defgroup org-refile nil
2343 "Options concerning refiling entries in Org mode."
2344 :tag "Org Refile"
2345 :group 'org)
2347 (defcustom org-directory "~/org"
2348 "Directory with Org files.
2349 This is just a default location to look for Org files. There is no need
2350 at all to put your files into this directory. It is used in the
2351 following situations:
2353 1. When a capture template specifies a target file that is not an
2354 absolute path. The path will then be interpreted relative to
2355 `org-directory'
2356 2. When the value of variable `org-agenda-files' is a single file, any
2357 relative paths in this file will be taken as relative to
2358 `org-directory'."
2359 :group 'org-refile
2360 :group 'org-capture
2361 :type 'directory)
2363 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2364 "Default target for storing notes.
2365 Used as a fall back file for org-capture.el, for templates that
2366 do not specify a target file."
2367 :group 'org-refile
2368 :group 'org-capture
2369 :type 'file)
2371 (defcustom org-reverse-note-order nil
2372 "Non-nil means store new notes at the beginning of a file or entry.
2373 When nil, new notes will be filed to the end of a file or entry.
2374 This can also be a list with cons cells of regular expressions that
2375 are matched against file names, and values."
2376 :group 'org-capture
2377 :group 'org-refile
2378 :type '(choice
2379 (const :tag "Reverse always" t)
2380 (const :tag "Reverse never" nil)
2381 (repeat :tag "By file name regexp"
2382 (cons regexp boolean))))
2384 (defcustom org-log-refile nil
2385 "Information to record when a task is refiled.
2387 Possible values are:
2389 nil Don't add anything
2390 time Add a time stamp to the task
2391 note Prompt for a note and add it with template `org-log-note-headings'
2393 This option can also be set with on a per-file-basis with
2395 #+STARTUP: nologrefile
2396 #+STARTUP: logrefile
2397 #+STARTUP: lognoterefile
2399 You can have local logging settings for a subtree by setting the LOGGING
2400 property to one or more of these keywords.
2402 When bulk-refiling from the agenda, the value `note' is forbidden and
2403 will temporarily be changed to `time'."
2404 :group 'org-refile
2405 :group 'org-progress
2406 :version "24.1"
2407 :type '(choice
2408 (const :tag "No logging" nil)
2409 (const :tag "Record timestamp" time)
2410 (const :tag "Record timestamp with note." note)))
2412 (defcustom org-refile-targets nil
2413 "Targets for refiling entries with `\\[org-refile]'.
2414 This is a list of cons cells. Each cell contains:
2415 - a specification of the files to be considered, either a list of files,
2416 or a symbol whose function or variable value will be used to retrieve
2417 a file name or a list of file names. If you use `org-agenda-files' for
2418 that, all agenda files will be scanned for targets. Nil means consider
2419 headings in the current buffer.
2420 - A specification of how to find candidate refile targets. This may be
2421 any of:
2422 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2423 This tag has to be present in all target headlines, inheritance will
2424 not be considered.
2425 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2426 todo keyword.
2427 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2428 headlines that are refiling targets.
2429 - a cons cell (:level . N). Any headline of level N is considered a target.
2430 Note that, when `org-odd-levels-only' is set, level corresponds to
2431 order in hierarchy, not to the number of stars.
2432 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2433 Note that, when `org-odd-levels-only' is set, level corresponds to
2434 order in hierarchy, not to the number of stars.
2436 Each element of this list generates a set of possible targets.
2437 The union of these sets is presented (with completion) to
2438 the user by `org-refile'.
2440 You can set the variable `org-refile-target-verify-function' to a function
2441 to verify each headline found by the simple criteria above.
2443 When this variable is nil, all top-level headlines in the current buffer
2444 are used, equivalent to the value `((nil . (:level . 1))'."
2445 :group 'org-refile
2446 :type '(repeat
2447 (cons
2448 (choice :value org-agenda-files
2449 (const :tag "All agenda files" org-agenda-files)
2450 (const :tag "Current buffer" nil)
2451 (function) (variable) (file))
2452 (choice :tag "Identify target headline by"
2453 (cons :tag "Specific tag" (const :value :tag) (string))
2454 (cons :tag "TODO keyword" (const :value :todo) (string))
2455 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2456 (cons :tag "Level number" (const :value :level) (integer))
2457 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2459 (defcustom org-refile-target-verify-function nil
2460 "Function to verify if the headline at point should be a refile target.
2461 The function will be called without arguments, with point at the
2462 beginning of the headline. It should return t and leave point
2463 where it is if the headline is a valid target for refiling.
2465 If the target should not be selected, the function must return nil.
2466 In addition to this, it may move point to a place from where the search
2467 should be continued. For example, the function may decide that the entire
2468 subtree of the current entry should be excluded and move point to the end
2469 of the subtree."
2470 :group 'org-refile
2471 :type '(choice
2472 (const nil)
2473 (function)))
2475 (defcustom org-refile-use-cache nil
2476 "Non-nil means cache refile targets to speed up the process.
2477 \\<org-mode-map>\
2478 The cache for a particular file will be updated automatically when
2479 the buffer has been killed, or when any of the marker used for flagging
2480 refile targets no longer points at a live buffer.
2481 If you have added new entries to a buffer that might themselves be targets,
2482 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2483 if you find that easier, \
2484 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2485 \\[org-refile]'."
2486 :group 'org-refile
2487 :version "24.1"
2488 :type 'boolean)
2490 (defcustom org-refile-use-outline-path nil
2491 "Non-nil means provide refile targets as paths.
2492 So a level 3 headline will be available as level1/level2/level3.
2494 When the value is `file', also include the file name (without directory)
2495 into the path. In this case, you can also stop the completion after
2496 the file name, to get entries inserted as top level in the file.
2498 When `full-file-path', include the full file path.
2500 When `buffer-name', use the buffer name."
2501 :group 'org-refile
2502 :type '(choice
2503 (const :tag "Not" nil)
2504 (const :tag "Yes" t)
2505 (const :tag "Start with file name" file)
2506 (const :tag "Start with full file path" full-file-path)
2507 (const :tag "Start with buffer name" buffer-name)))
2509 (defcustom org-outline-path-complete-in-steps t
2510 "Non-nil means complete the outline path in hierarchical steps.
2511 When Org uses the refile interface to select an outline path (see
2512 `org-refile-use-outline-path'), the completion of the path can be
2513 done in a single go, or it can be done in steps down the headline
2514 hierarchy. Going in steps is probably the best if you do not use
2515 a special completion package like `ido' or `icicles'. However,
2516 when using these packages, going in one step can be very fast,
2517 while still showing the whole path to the entry."
2518 :group 'org-refile
2519 :type 'boolean)
2521 (defcustom org-refile-allow-creating-parent-nodes nil
2522 "Non-nil means allow the creation of new nodes as refile targets.
2523 New nodes are then created by adding \"/new node name\" to the completion
2524 of an existing node. When the value of this variable is `confirm',
2525 new node creation must be confirmed by the user (recommended).
2526 When nil, the completion must match an existing entry.
2528 Note that, if the new heading is not seen by the criteria
2529 listed in `org-refile-targets', multiple instances of the same
2530 heading would be created by trying again to file under the new
2531 heading."
2532 :group 'org-refile
2533 :type '(choice
2534 (const :tag "Never" nil)
2535 (const :tag "Always" t)
2536 (const :tag "Prompt for confirmation" confirm)))
2538 (defcustom org-refile-active-region-within-subtree nil
2539 "Non-nil means also refile active region within a subtree.
2541 By default `org-refile' doesn't allow refiling regions if they
2542 don't contain a set of subtrees, but it might be convenient to
2543 do so sometimes: in that case, the first line of the region is
2544 converted to a headline before refiling."
2545 :group 'org-refile
2546 :version "24.1"
2547 :type 'boolean)
2549 (defgroup org-todo nil
2550 "Options concerning TODO items in Org mode."
2551 :tag "Org TODO"
2552 :group 'org)
2554 (defgroup org-progress nil
2555 "Options concerning Progress logging in Org mode."
2556 :tag "Org Progress"
2557 :group 'org-time)
2559 (defvar org-todo-interpretation-widgets
2560 '((:tag "Sequence (cycling hits every state)" sequence)
2561 (:tag "Type (cycling directly to DONE)" type))
2562 "The available interpretation symbols for customizing `org-todo-keywords'.
2563 Interested libraries should add to this list.")
2565 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2566 "List of TODO entry keyword sequences and their interpretation.
2567 \\<org-mode-map>This is a list of sequences.
2569 Each sequence starts with a symbol, either `sequence' or `type',
2570 indicating if the keywords should be interpreted as a sequence of
2571 action steps, or as different types of TODO items. The first
2572 keywords are states requiring action - these states will select a headline
2573 for inclusion into the global TODO list Org produces. If one of the
2574 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2575 signify that no further action is necessary. If \"|\" is not found,
2576 the last keyword is treated as the only DONE state of the sequence.
2578 The command `\\[org-todo]' cycles an entry through these states, and one
2579 additional state where no keyword is present. For details about this
2580 cycling, see the manual.
2582 TODO keywords and interpretation can also be set on a per-file basis with
2583 the special #+SEQ_TODO and #+TYP_TODO lines.
2585 Each keyword can optionally specify a character for fast state selection
2586 \(in combination with the variable `org-use-fast-todo-selection')
2587 and specifiers for state change logging, using the same syntax that
2588 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2589 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2590 indicates to record a time stamp each time this state is selected.
2592 Each keyword may also specify if a timestamp or a note should be
2593 recorded when entering or leaving the state, by adding additional
2594 characters in the parenthesis after the keyword. This looks like this:
2595 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2596 record only the time of the state change. With X and Y being either
2597 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2598 Y when leaving the state if and only if the *target* state does not
2599 define X. You may omit any of the fast-selection key or X or /Y,
2600 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2602 For backward compatibility, this variable may also be just a list
2603 of keywords. In this case the interpretation (sequence or type) will be
2604 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2605 :group 'org-todo
2606 :group 'org-keywords
2607 :type '(choice
2608 (repeat :tag "Old syntax, just keywords"
2609 (string :tag "Keyword"))
2610 (repeat :tag "New syntax"
2611 (cons
2612 (choice
2613 :tag "Interpretation"
2614 ;;Quick and dirty way to see
2615 ;;`org-todo-interpretations'. This takes the
2616 ;;place of item arguments
2617 :convert-widget
2618 (lambda (widget)
2619 (widget-put widget
2620 :args (mapcar
2621 (lambda (x)
2622 (widget-convert
2623 (cons 'const x)))
2624 org-todo-interpretation-widgets))
2625 widget))
2626 (repeat
2627 (string :tag "Keyword"))))))
2629 (defvar-local org-todo-keywords-1 nil
2630 "All TODO and DONE keywords active in a buffer.")
2631 (defvar org-todo-keywords-for-agenda nil)
2632 (defvar org-done-keywords-for-agenda nil)
2633 (defvar org-todo-keyword-alist-for-agenda nil)
2634 (defvar org-tag-alist-for-agenda nil
2635 "Alist of all tags from all agenda files.")
2636 (defvar org-tag-groups-alist-for-agenda nil
2637 "Alist of all groups tags from all current agenda files.")
2638 (defvar-local org-tag-groups-alist nil)
2639 (defvar org-agenda-contributing-files nil)
2640 (defvar-local org-current-tag-alist nil
2641 "Alist of all tag groups in current buffer.
2642 This variable takes into consideration `org-tag-alist',
2643 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2644 (defvar-local org-not-done-keywords nil)
2645 (defvar-local org-done-keywords nil)
2646 (defvar-local org-todo-heads nil)
2647 (defvar-local org-todo-sets nil)
2648 (defvar-local org-todo-log-states nil)
2649 (defvar-local org-todo-kwd-alist nil)
2650 (defvar-local org-todo-key-alist nil)
2651 (defvar-local org-todo-key-trigger nil)
2653 (defcustom org-todo-interpretation 'sequence
2654 "Controls how TODO keywords are interpreted.
2655 This variable is in principle obsolete and is only used for
2656 backward compatibility, if the interpretation of todo keywords is
2657 not given already in `org-todo-keywords'. See that variable for
2658 more information."
2659 :group 'org-todo
2660 :group 'org-keywords
2661 :type '(choice (const sequence)
2662 (const type)))
2664 (defcustom org-use-fast-todo-selection t
2665 "\\<org-mode-map>\
2666 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2667 This variable describes if and under what circumstances the cycling
2668 mechanism for TODO keywords will be replaced by a single-key, direct
2669 selection scheme.
2671 When nil, fast selection is never used.
2673 When the symbol `prefix', it will be used when `org-todo' is called
2674 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2675 in an Org buffer, and
2676 `\\[universal-argument] t' in an agenda buffer.
2678 When t, fast selection is used by default. In this case, the prefix
2679 argument forces cycling instead.
2681 In all cases, the special interface is only used if access keys have
2682 actually been assigned by the user, i.e. if keywords in the configuration
2683 are followed by a letter in parenthesis, like TODO(t)."
2684 :group 'org-todo
2685 :type '(choice
2686 (const :tag "Never" nil)
2687 (const :tag "By default" t)
2688 (const :tag "Only with C-u C-c C-t" prefix)))
2690 (defcustom org-provide-todo-statistics t
2691 "Non-nil means update todo statistics after insert and toggle.
2692 ALL-HEADLINES means update todo statistics by including headlines
2693 with no TODO keyword as well, counting them as not done.
2694 A list of TODO keywords means the same, but skip keywords that are
2695 not in this list.
2696 When set to a list of two lists, the first list contains keywords
2697 to consider as TODO keywords, the second list contains keywords
2698 to consider as DONE keywords.
2700 When this is set, todo statistics is updated in the parent of the
2701 current entry each time a todo state is changed."
2702 :group 'org-todo
2703 :type '(choice
2704 (const :tag "Yes, only for TODO entries" t)
2705 (const :tag "Yes, including all entries" all-headlines)
2706 (repeat :tag "Yes, for TODOs in this list"
2707 (string :tag "TODO keyword"))
2708 (list :tag "Yes, for TODOs and DONEs in these lists"
2709 (repeat (string :tag "TODO keyword"))
2710 (repeat (string :tag "DONE keyword")))
2711 (other :tag "No TODO statistics" nil)))
2713 (defcustom org-hierarchical-todo-statistics t
2714 "Non-nil means TODO statistics covers just direct children.
2715 When nil, all entries in the subtree are considered.
2716 This has only an effect if `org-provide-todo-statistics' is set.
2717 To set this to nil for only a single subtree, use a COOKIE_DATA
2718 property and include the word \"recursive\" into the value."
2719 :group 'org-todo
2720 :type 'boolean)
2722 (defcustom org-after-todo-state-change-hook nil
2723 "Hook which is run after the state of a TODO item was changed.
2724 The new state (a string with a TODO keyword, or nil) is available in the
2725 Lisp variable `org-state'."
2726 :group 'org-todo
2727 :type 'hook)
2729 (defvar org-blocker-hook nil
2730 "Hook for functions that are allowed to block a state change.
2732 Functions in this hook should not modify the buffer.
2733 Each function gets as its single argument a property list,
2734 see `org-trigger-hook' for more information about this list.
2736 If any of the functions in this hook returns nil, the state change
2737 is blocked.")
2739 (defvar org-trigger-hook nil
2740 "Hook for functions that are triggered by a state change.
2742 Each function gets as its single argument a property list with at
2743 least the following elements:
2745 (:type type-of-change :position pos-at-entry-start
2746 :from old-state :to new-state)
2748 Depending on the type, more properties may be present.
2750 This mechanism is currently implemented for:
2752 TODO state changes
2753 ------------------
2754 :type todo-state-change
2755 :from previous state (keyword as a string), or nil, or a symbol
2756 `todo' or `done', to indicate the general type of state.
2757 :to new state, like in :from")
2759 (defcustom org-enforce-todo-dependencies nil
2760 "Non-nil means undone TODO entries will block switching the parent to DONE.
2761 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2762 be blocked if any prior sibling is not yet done.
2763 Finally, if the parent is blocked because of ordered siblings of its own,
2764 the child will also be blocked."
2765 :set (lambda (var val)
2766 (set var val)
2767 (if val
2768 (add-hook 'org-blocker-hook
2769 'org-block-todo-from-children-or-siblings-or-parent)
2770 (remove-hook 'org-blocker-hook
2771 'org-block-todo-from-children-or-siblings-or-parent)))
2772 :group 'org-todo
2773 :type 'boolean)
2775 (defcustom org-enforce-todo-checkbox-dependencies nil
2776 "Non-nil means unchecked boxes will block switching the parent to DONE.
2777 When this is nil, checkboxes have no influence on switching TODO states.
2778 When non-nil, you first need to check off all check boxes before the TODO
2779 entry can be switched to DONE.
2780 This variable needs to be set before org.el is loaded, and you need to
2781 restart Emacs after a change to make the change effective. The only way
2782 to change is while Emacs is running is through the customize interface."
2783 :set (lambda (var val)
2784 (set var val)
2785 (if val
2786 (add-hook 'org-blocker-hook
2787 'org-block-todo-from-checkboxes)
2788 (remove-hook 'org-blocker-hook
2789 'org-block-todo-from-checkboxes)))
2790 :group 'org-todo
2791 :type 'boolean)
2793 (defcustom org-treat-insert-todo-heading-as-state-change nil
2794 "Non-nil means inserting a TODO heading is treated as state change.
2795 So when the command `\\[org-insert-todo-heading]' is used, state change
2796 logging will apply if appropriate. When nil, the new TODO item will
2797 be inserted directly, and no logging will take place."
2798 :group 'org-todo
2799 :type 'boolean)
2801 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2802 "Non-nil means switching TODO states with S-cursor counts as state change.
2803 This is the default behavior. However, setting this to nil allows a
2804 convenient way to select a TODO state and bypass any logging associated
2805 with that."
2806 :group 'org-todo
2807 :type 'boolean)
2809 (defcustom org-todo-state-tags-triggers nil
2810 "Tag changes that should be triggered by TODO state changes.
2811 This is a list. Each entry is
2813 (state-change (tag . flag) .......)
2815 State-change can be a string with a state, and empty string to indicate the
2816 state that has no TODO keyword, or it can be one of the symbols `todo'
2817 or `done', meaning any not-done or done state, respectively."
2818 :group 'org-todo
2819 :group 'org-tags
2820 :type '(repeat
2821 (cons (choice :tag "When changing to"
2822 (const :tag "Not-done state" todo)
2823 (const :tag "Done state" done)
2824 (string :tag "State"))
2825 (repeat
2826 (cons :tag "Tag action"
2827 (string :tag "Tag")
2828 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2830 (defcustom org-log-done nil
2831 "Information to record when a task moves to the DONE state.
2833 Possible values are:
2835 nil Don't add anything, just change the keyword
2836 time Add a time stamp to the task
2837 note Prompt for a note and add it with template `org-log-note-headings'
2839 This option can also be set with on a per-file-basis with
2841 #+STARTUP: nologdone
2842 #+STARTUP: logdone
2843 #+STARTUP: lognotedone
2845 You can have local logging settings for a subtree by setting the LOGGING
2846 property to one or more of these keywords."
2847 :group 'org-todo
2848 :group 'org-progress
2849 :type '(choice
2850 (const :tag "No logging" nil)
2851 (const :tag "Record CLOSED timestamp" time)
2852 (const :tag "Record CLOSED timestamp with note." note)))
2854 ;; Normalize old uses of org-log-done.
2855 (cond
2856 ((eq org-log-done t) (setq org-log-done 'time))
2857 ((and (listp org-log-done) (memq 'done org-log-done))
2858 (setq org-log-done 'note)))
2860 (defcustom org-log-reschedule nil
2861 "Information to record when the scheduling date of a tasks is modified.
2863 Possible values are:
2865 nil Don't add anything, just change the date
2866 time Add a time stamp to the task
2867 note Prompt for a note and add it with template `org-log-note-headings'
2869 This option can also be set with on a per-file-basis with
2871 #+STARTUP: nologreschedule
2872 #+STARTUP: logreschedule
2873 #+STARTUP: lognotereschedule"
2874 :group 'org-todo
2875 :group 'org-progress
2876 :type '(choice
2877 (const :tag "No logging" nil)
2878 (const :tag "Record timestamp" time)
2879 (const :tag "Record timestamp with note." note)))
2881 (defcustom org-log-redeadline nil
2882 "Information to record when the deadline date of a tasks is modified.
2884 Possible values are:
2886 nil Don't add anything, just change the date
2887 time Add a time stamp to the task
2888 note Prompt for a note and add it with template `org-log-note-headings'
2890 This option can also be set with on a per-file-basis with
2892 #+STARTUP: nologredeadline
2893 #+STARTUP: logredeadline
2894 #+STARTUP: lognoteredeadline
2896 You can have local logging settings for a subtree by setting the LOGGING
2897 property to one or more of these keywords."
2898 :group 'org-todo
2899 :group 'org-progress
2900 :type '(choice
2901 (const :tag "No logging" nil)
2902 (const :tag "Record timestamp" time)
2903 (const :tag "Record timestamp with note." note)))
2905 (defcustom org-log-note-clock-out nil
2906 "Non-nil means record a note when clocking out of an item.
2907 This can also be configured on a per-file basis by adding one of
2908 the following lines anywhere in the buffer:
2910 #+STARTUP: lognoteclock-out
2911 #+STARTUP: nolognoteclock-out"
2912 :group 'org-todo
2913 :group 'org-progress
2914 :type 'boolean)
2916 (defcustom org-log-done-with-time t
2917 "Non-nil means the CLOSED time stamp will contain date and time.
2918 When nil, only the date will be recorded."
2919 :group 'org-progress
2920 :type 'boolean)
2922 (defcustom org-log-note-headings
2923 '((done . "CLOSING NOTE %t")
2924 (state . "State %-12s from %-12S %t")
2925 (note . "Note taken on %t")
2926 (reschedule . "Rescheduled from %S on %t")
2927 (delschedule . "Not scheduled, was %S on %t")
2928 (redeadline . "New deadline from %S on %t")
2929 (deldeadline . "Removed deadline, was %S on %t")
2930 (refile . "Refiled on %t")
2931 (clock-out . ""))
2932 "Headings for notes added to entries.
2934 The value is an alist, with the car being a symbol indicating the
2935 note context, and the cdr is the heading to be used. The heading
2936 may also be the empty string. The following placeholders can be
2937 used:
2939 %t a time stamp.
2940 %T an active time stamp instead the default inactive one
2941 %d a short-format time stamp.
2942 %D an active short-format time stamp.
2943 %s the new TODO state or time stamp (inactive), in double quotes.
2944 %S the old TODO state or time stamp (inactive), in double quotes.
2945 %u the user name.
2946 %U full user name.
2948 In fact, it is not a good idea to change the `state' entry,
2949 because Agenda Log mode depends on the format of these entries."
2950 :group 'org-todo
2951 :group 'org-progress
2952 :type '(list :greedy t
2953 (cons (const :tag "Heading when closing an item" done) string)
2954 (cons (const :tag
2955 "Heading when changing todo state (todo sequence only)"
2956 state) string)
2957 (cons (const :tag "Heading when just taking a note" note) string)
2958 (cons (const :tag "Heading when rescheduling" reschedule) string)
2959 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2960 (cons (const :tag "Heading when changing deadline" redeadline) string)
2961 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2962 (cons (const :tag "Heading when refiling" refile) string)
2963 (cons (const :tag "Heading when clocking out" clock-out) string)))
2965 (unless (assq 'note org-log-note-headings)
2966 (push '(note . "%t") org-log-note-headings))
2968 (defcustom org-log-into-drawer nil
2969 "Non-nil means insert state change notes and time stamps into a drawer.
2970 When nil, state changes notes will be inserted after the headline and
2971 any scheduling and clock lines, but not inside a drawer.
2973 The value of this variable should be the name of the drawer to use.
2974 LOGBOOK is proposed as the default drawer for this purpose, you can
2975 also set this to a string to define the drawer of your choice.
2977 A value of t is also allowed, representing \"LOGBOOK\".
2979 A value of t or nil can also be set with on a per-file-basis with
2981 #+STARTUP: logdrawer
2982 #+STARTUP: nologdrawer
2984 If this variable is set, `org-log-state-notes-insert-after-drawers'
2985 will be ignored.
2987 You can set the property LOG_INTO_DRAWER to overrule this setting for
2988 a subtree.
2990 Do not check directly this variable in a Lisp program. Call
2991 function `org-log-into-drawer' instead."
2992 :group 'org-todo
2993 :group 'org-progress
2994 :type '(choice
2995 (const :tag "Not into a drawer" nil)
2996 (const :tag "LOGBOOK" t)
2997 (string :tag "Other")))
2999 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3001 (defun org-log-into-drawer ()
3002 "Name of the log drawer, as a string, or nil.
3003 This is the value of `org-log-into-drawer'. However, if the
3004 current entry has or inherits a LOG_INTO_DRAWER property, it will
3005 be used instead of the default value."
3006 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3007 (cond ((equal p "nil") nil)
3008 ((equal p "t") "LOGBOOK")
3009 ((stringp p) p)
3010 (p "LOGBOOK")
3011 ((stringp org-log-into-drawer) org-log-into-drawer)
3012 (org-log-into-drawer "LOGBOOK"))))
3014 (defcustom org-log-state-notes-insert-after-drawers nil
3015 "Non-nil means insert state change notes after any drawers in entry.
3016 Only the drawers that *immediately* follow the headline and the
3017 deadline/scheduled line are skipped.
3018 When nil, insert notes right after the heading and perhaps the line
3019 with deadline/scheduling if present.
3021 This variable will have no effect if `org-log-into-drawer' is
3022 set."
3023 :group 'org-todo
3024 :group 'org-progress
3025 :type 'boolean)
3027 (defcustom org-log-states-order-reversed t
3028 "Non-nil means the latest state note will be directly after heading.
3029 When nil, the state change notes will be ordered according to time.
3031 This option can also be set with on a per-file-basis with
3033 #+STARTUP: logstatesreversed
3034 #+STARTUP: nologstatesreversed"
3035 :group 'org-todo
3036 :group 'org-progress
3037 :type 'boolean)
3039 (defcustom org-todo-repeat-to-state nil
3040 "The TODO state to which a repeater should return the repeating task.
3041 By default this is the first task of a TODO sequence or the
3042 previous state of a TYPE_TODO set. But you can specify to use
3043 the previous state in a TODO sequence or a string.
3045 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3046 entry, which has precedence over this option."
3047 :group 'org-todo
3048 :version "24.1"
3049 :type '(choice (const :tag "Use the previous TODO state" t)
3050 (const :tag "Use the head of the TODO sequence" nil)
3051 (string :tag "Use a specific TODO state")))
3053 (defcustom org-log-repeat 'time
3054 "Non-nil means record moving through the DONE state when triggering repeat.
3055 An auto-repeating task is immediately switched back to TODO when
3056 marked DONE. If you are not logging state changes (by adding \"@\"
3057 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3058 record a closing note, there will be no record of the task moving
3059 through DONE. This variable forces taking a note anyway.
3061 nil Don't force a record
3062 time Record a time stamp
3063 note Prompt for a note and add it with template `org-log-note-headings'
3065 This option can also be set with on a per-file-basis with
3067 #+STARTUP: nologrepeat
3068 #+STARTUP: logrepeat
3069 #+STARTUP: lognoterepeat
3071 You can have local logging settings for a subtree by setting the LOGGING
3072 property to one or more of these keywords."
3073 :group 'org-todo
3074 :group 'org-progress
3075 :type '(choice
3076 (const :tag "Don't force a record" nil)
3077 (const :tag "Force recording the DONE state" time)
3078 (const :tag "Force recording a note with the DONE state" note)))
3081 (defgroup org-priorities nil
3082 "Priorities in Org mode."
3083 :tag "Org Priorities"
3084 :group 'org-todo)
3086 (defcustom org-enable-priority-commands t
3087 "Non-nil means priority commands are active.
3088 When nil, these commands will be disabled, so that you never accidentally
3089 set a priority."
3090 :group 'org-priorities
3091 :type 'boolean)
3093 (defcustom org-highest-priority ?A
3094 "The highest priority of TODO items. A character like ?A, ?B etc.
3095 Must have a smaller ASCII number than `org-lowest-priority'."
3096 :group 'org-priorities
3097 :type 'character)
3099 (defcustom org-lowest-priority ?C
3100 "The lowest priority of TODO items. A character like ?A, ?B etc.
3101 Must have a larger ASCII number than `org-highest-priority'."
3102 :group 'org-priorities
3103 :type 'character)
3105 (defcustom org-default-priority ?B
3106 "The default priority of TODO items.
3107 This is the priority an item gets if no explicit priority is given.
3108 When starting to cycle on an empty priority the first step in the cycle
3109 depends on `org-priority-start-cycle-with-default'. The resulting first
3110 step priority must not exceed the range from `org-highest-priority' to
3111 `org-lowest-priority' which means that `org-default-priority' has to be
3112 in this range exclusive or inclusive the range boundaries. Else the
3113 first step refuses to set the default and the second will fall back
3114 to (depending on the command used) the highest or lowest priority."
3115 :group 'org-priorities
3116 :type 'character)
3118 (defcustom org-priority-start-cycle-with-default t
3119 "Non-nil means start with default priority when starting to cycle.
3120 When this is nil, the first step in the cycle will be (depending on the
3121 command used) one higher or lower than the default priority.
3122 See also `org-default-priority'."
3123 :group 'org-priorities
3124 :type 'boolean)
3126 (defcustom org-get-priority-function nil
3127 "Function to extract the priority from a string.
3128 The string is normally the headline. If this is nil Org computes the
3129 priority from the priority cookie like [#A] in the headline. It returns
3130 an integer, increasing by 1000 for each priority level.
3131 The user can set a different function here, which should take a string
3132 as an argument and return the numeric priority."
3133 :group 'org-priorities
3134 :version "24.1"
3135 :type '(choice
3136 (const nil)
3137 (function)))
3139 (defgroup org-time nil
3140 "Options concerning time stamps and deadlines in Org mode."
3141 :tag "Org Time"
3142 :group 'org)
3144 (defcustom org-time-stamp-rounding-minutes '(0 5)
3145 "Number of minutes to round time stamps to.
3146 \\<org-mode-map>\
3147 These are two values, the first applies when first creating a time stamp.
3148 The second applies when changing it with the commands `S-up' and `S-down'.
3149 When changing the time stamp, this means that it will change in steps
3150 of N minutes, as given by the second value.
3152 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3153 numbers should be factors of 60, so for example 5, 10, 15.
3155 When this is larger than 1, you can still force an exact time stamp by using
3156 a double prefix argument to a time stamp command like \
3157 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3158 and by using a prefix arg to `S-up/down' to specify the exact number
3159 of minutes to shift."
3160 :group 'org-time
3161 :get (lambda (var) ; Make sure both elements are there
3162 (if (integerp (default-value var))
3163 (list (default-value var) 5)
3164 (default-value var)))
3165 :type '(list
3166 (integer :tag "when inserting times")
3167 (integer :tag "when modifying times")))
3169 ;; Normalize old customizations of this variable.
3170 (when (integerp org-time-stamp-rounding-minutes)
3171 (setq org-time-stamp-rounding-minutes
3172 (list org-time-stamp-rounding-minutes
3173 org-time-stamp-rounding-minutes)))
3175 (defcustom org-display-custom-times nil
3176 "Non-nil means overlay custom formats over all time stamps.
3177 The formats are defined through the variable `org-time-stamp-custom-formats'.
3178 To turn this on on a per-file basis, insert anywhere in the file:
3179 #+STARTUP: customtime"
3180 :group 'org-time
3181 :set 'set-default
3182 :type 'sexp)
3183 (make-variable-buffer-local 'org-display-custom-times)
3185 (defcustom org-time-stamp-custom-formats
3186 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3187 "Custom formats for time stamps. See `format-time-string' for the syntax.
3188 These are overlaid over the default ISO format if the variable
3189 `org-display-custom-times' is set. Time like %H:%M should be at the
3190 end of the second format. The custom formats are also honored by export
3191 commands, if custom time display is turned on at the time of export."
3192 :group 'org-time
3193 :type 'sexp)
3195 (defun org-time-stamp-format (&optional long inactive)
3196 "Get the right format for a time string."
3197 (let ((f (if long (cdr org-time-stamp-formats)
3198 (car org-time-stamp-formats))))
3199 (if inactive
3200 (concat "[" (substring f 1 -1) "]")
3201 f)))
3203 (defcustom org-deadline-warning-days 14
3204 "Number of days before expiration during which a deadline becomes active.
3205 This variable governs the display in sparse trees and in the agenda.
3206 When 0 or negative, it means use this number (the absolute value of it)
3207 even if a deadline has a different individual lead time specified.
3209 Custom commands can set this variable in the options section."
3210 :group 'org-time
3211 :group 'org-agenda-daily/weekly
3212 :type 'integer)
3214 (defcustom org-scheduled-delay-days 0
3215 "Number of days before a scheduled item becomes active.
3216 This variable governs the display in sparse trees and in the agenda.
3217 The default value (i.e. 0) means: don't delay scheduled item.
3218 When negative, it means use this number (the absolute value of it)
3219 even if a scheduled item has a different individual delay time
3220 specified.
3222 Custom commands can set this variable in the options section."
3223 :group 'org-time
3224 :group 'org-agenda-daily/weekly
3225 :version "24.4"
3226 :package-version '(Org . "8.0")
3227 :type 'integer)
3229 (defcustom org-read-date-prefer-future t
3230 "Non-nil means assume future for incomplete date input from user.
3231 This affects the following situations:
3232 1. The user gives a month but not a year.
3233 For example, if it is April and you enter \"feb 2\", this will be read
3234 as Feb 2, *next* year. \"May 5\", however, will be this year.
3235 2. The user gives a day, but no month.
3236 For example, if today is the 15th, and you enter \"3\", Org will read
3237 this as the third of *next* month. However, if you enter \"17\",
3238 it will be considered as *this* month.
3240 If you set this variable to the symbol `time', then also the following
3241 will work:
3243 3. If the user gives a time.
3244 If the time is before now, it will be interpreted as tomorrow.
3246 Currently none of this works for ISO week specifications.
3248 When this option is nil, the current day, month and year will always be
3249 used as defaults.
3251 See also `org-agenda-jump-prefer-future'."
3252 :group 'org-time
3253 :type '(choice
3254 (const :tag "Never" nil)
3255 (const :tag "Check month and day" t)
3256 (const :tag "Check month, day, and time" time)))
3258 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3259 "Should the agenda jump command prefer the future for incomplete dates?
3260 The default is to do the same as configured in `org-read-date-prefer-future'.
3261 But you can also set a deviating value here.
3262 This may t or nil, or the symbol `org-read-date-prefer-future'."
3263 :group 'org-agenda
3264 :group 'org-time
3265 :version "24.1"
3266 :type '(choice
3267 (const :tag "Use org-read-date-prefer-future"
3268 org-read-date-prefer-future)
3269 (const :tag "Never" nil)
3270 (const :tag "Always" t)))
3272 (defcustom org-read-date-force-compatible-dates t
3273 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3275 Depending on the system Emacs is running on, certain dates cannot
3276 be represented with the type used internally to represent time.
3277 Dates between 1970-1-1 and 2038-1-1 can always be represented
3278 correctly. Some systems allow for earlier dates, some for later,
3279 some for both. One way to find out it to insert any date into an
3280 Org buffer, putting the cursor on the year and hitting S-up and
3281 S-down to test the range.
3283 When this variable is set to t, the date/time prompt will not let
3284 you specify dates outside the 1970-2037 range, so it is certain that
3285 these dates will work in whatever version of Emacs you are
3286 running, and also that you can move a file from one Emacs implementation
3287 to another. WHenever Org is forcing the year for you, it will display
3288 a message and beep.
3290 When this variable is nil, Org will check if the date is
3291 representable in the specific Emacs implementation you are using.
3292 If not, it will force a year, usually the current year, and beep
3293 to remind you. Currently this setting is not recommended because
3294 the likelihood that you will open your Org files in an Emacs that
3295 has limited date range is not negligible.
3297 A workaround for this problem is to use diary sexp dates for time
3298 stamps outside of this range."
3299 :group 'org-time
3300 :version "24.1"
3301 :type 'boolean)
3303 (defcustom org-read-date-display-live t
3304 "Non-nil means display current interpretation of date prompt live.
3305 This display will be in an overlay, in the minibuffer."
3306 :group 'org-time
3307 :type 'boolean)
3309 (defcustom org-read-date-popup-calendar t
3310 "Non-nil means pop up a calendar when prompting for a date.
3311 In the calendar, the date can be selected with mouse-1. However, the
3312 minibuffer will also be active, and you can simply enter the date as well.
3313 When nil, only the minibuffer will be available."
3314 :group 'org-time
3315 :type 'boolean)
3316 (defvaralias 'org-popup-calendar-for-date-prompt
3317 'org-read-date-popup-calendar)
3319 (defcustom org-extend-today-until 0
3320 "The hour when your day really ends. Must be an integer.
3321 This has influence for the following applications:
3322 - When switching the agenda to \"today\". It it is still earlier than
3323 the time given here, the day recognized as TODAY is actually yesterday.
3324 - When a date is read from the user and it is still before the time given
3325 here, the current date and time will be assumed to be yesterday, 23:59.
3326 Also, timestamps inserted in capture templates follow this rule.
3328 IMPORTANT: This is a feature whose implementation is and likely will
3329 remain incomplete. Really, it is only here because past midnight seems to
3330 be the favorite working time of John Wiegley :-)"
3331 :group 'org-time
3332 :type 'integer)
3334 (defcustom org-use-effective-time nil
3335 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3336 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3337 \"effective time\" of any timestamps between midnight and 8am will be
3338 23:59 of the previous day."
3339 :group 'org-time
3340 :version "24.1"
3341 :type 'boolean)
3343 (defcustom org-use-last-clock-out-time-as-effective-time nil
3344 "When non-nil, use the last clock out time for `org-todo'.
3345 Note that this option has precedence over the combined use of
3346 `org-use-effective-time' and `org-extend-today-until'."
3347 :group 'org-time
3348 :version "24.4"
3349 :package-version '(Org . "8.0")
3350 :type 'boolean)
3352 (defcustom org-edit-timestamp-down-means-later nil
3353 "Non-nil means S-down will increase the time in a time stamp.
3354 When nil, S-up will increase."
3355 :group 'org-time
3356 :type 'boolean)
3358 (defcustom org-calendar-follow-timestamp-change t
3359 "Non-nil means make the calendar window follow timestamp changes.
3360 When a timestamp is modified and the calendar window is visible, it will be
3361 moved to the new date."
3362 :group 'org-time
3363 :type 'boolean)
3365 (defgroup org-tags nil
3366 "Options concerning tags in Org mode."
3367 :tag "Org Tags"
3368 :group 'org)
3370 (defcustom org-tag-alist nil
3371 "Default tags available in Org files.
3373 The value of this variable is an alist. Associations either:
3375 (TAG)
3376 (TAG . SELECT)
3377 (SPECIAL)
3379 where TAG is a tag as a string, SELECT is character, used to
3380 select that tag through the fast tag selection interface, and
3381 SPECIAL is one of the following keywords: `:startgroup',
3382 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3383 `:newline'. These keywords are used to define a hierarchy of
3384 tags. See manual for details.
3386 When this variable is nil, Org mode bases tag input on what is
3387 already in the buffer. The value can be overridden locally by
3388 using a TAGS keyword, e.g.,
3390 #+TAGS: tag1 tag2
3392 See also `org-tag-persistent-alist' to sidestep this behavior."
3393 :group 'org-tags
3394 :type '(repeat
3395 (choice
3396 (cons :tag "Tag with key"
3397 (string :tag "Tag name")
3398 (character :tag "Access char"))
3399 (list :tag "Tag" (string :tag "Tag name"))
3400 (const :tag "Start radio group" (:startgroup))
3401 (const :tag "Start tag group, non distinct" (:startgrouptag))
3402 (const :tag "Group tags delimiter" (:grouptags))
3403 (const :tag "End radio group" (:endgroup))
3404 (const :tag "End tag group, non distinct" (:endgrouptag))
3405 (const :tag "New line" (:newline)))))
3407 (defcustom org-tag-persistent-alist nil
3408 "Tags always available in Org files.
3410 The value of this variable is an alist. Associations either:
3412 (TAG)
3413 (TAG . SELECT)
3414 (SPECIAL)
3416 where TAG is a tag as a string, SELECT is a character, used to
3417 select that tag through the fast tag selection interface, and
3418 SPECIAL is one of the following keywords: `:startgroup',
3419 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3420 `:newline'. These keywords are used to define a hierarchy of
3421 tags. See manual for details.
3423 Unlike to `org-tag-alist', tags defined in this variable do not
3424 depend on a local TAGS keyword. Instead, to disable these tags
3425 on a per-file basis, insert anywhere in the file:
3427 #+STARTUP: noptag"
3428 :group 'org-tags
3429 :type '(repeat
3430 (choice
3431 (cons :tag "Tag with key"
3432 (string :tag "Tag name")
3433 (character :tag "Access char"))
3434 (list :tag "Tag" (string :tag "Tag name"))
3435 (const :tag "Start radio group" (:startgroup))
3436 (const :tag "Start tag group, non distinct" (:startgrouptag))
3437 (const :tag "Group tags delimiter" (:grouptags))
3438 (const :tag "End radio group" (:endgroup))
3439 (const :tag "End tag group, non distinct" (:endgrouptag))
3440 (const :tag "New line" (:newline)))))
3442 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3443 "If non-nil, always offer completion for all tags of all agenda files.
3444 Instead of customizing this variable directly, you might want to
3445 set it locally for capture buffers, because there no list of
3446 tags in that file can be created dynamically (there are none).
3448 (add-hook \\='org-capture-mode-hook
3449 (lambda ()
3450 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3451 :group 'org-tags
3452 :version "24.1"
3453 :type 'boolean)
3455 (defvar org-file-tags nil
3456 "List of tags that can be inherited by all entries in the file.
3457 The tags will be inherited if the variable `org-use-tag-inheritance'
3458 says they should be.
3459 This variable is populated from #+FILETAGS lines.")
3461 (defcustom org-use-fast-tag-selection 'auto
3462 "Non-nil means use fast tag selection scheme.
3463 This is a special interface to select and deselect tags with single keys.
3464 When nil, fast selection is never used.
3465 When the symbol `auto', fast selection is used if and only if selection
3466 characters for tags have been configured, either through the variable
3467 `org-tag-alist' or through a #+TAGS line in the buffer.
3468 When t, fast selection is always used and selection keys are assigned
3469 automatically if necessary."
3470 :group 'org-tags
3471 :type '(choice
3472 (const :tag "Always" t)
3473 (const :tag "Never" nil)
3474 (const :tag "When selection characters are configured" auto)))
3476 (defcustom org-fast-tag-selection-single-key nil
3477 "Non-nil means fast tag selection exits after first change.
3478 When nil, you have to press RET to exit it.
3479 During fast tag selection, you can toggle this flag with `C-c'.
3480 This variable can also have the value `expert'. In this case, the window
3481 displaying the tags menu is not even shown, until you press C-c again."
3482 :group 'org-tags
3483 :type '(choice
3484 (const :tag "No" nil)
3485 (const :tag "Yes" t)
3486 (const :tag "Expert" expert)))
3488 (defvar org-fast-tag-selection-include-todo nil
3489 "Non-nil means fast tags selection interface will also offer TODO states.
3490 This is an undocumented feature, you should not rely on it.")
3492 (defcustom org-tags-column -77
3493 "The column to which tags should be indented in a headline.
3494 If this number is positive, it specifies the column. If it is negative,
3495 it means that the tags should be flushright to that column. For example,
3496 -80 works well for a normal 80 character screen.
3497 When 0, place tags directly after headline text, with only one space in
3498 between."
3499 :group 'org-tags
3500 :type 'integer)
3502 (defcustom org-auto-align-tags t
3503 "Non-nil keeps tags aligned when modifying headlines.
3504 Some operations (i.e. demoting) change the length of a headline and
3505 therefore shift the tags around. With this option turned on, after
3506 each such operation the tags are again aligned to `org-tags-column'."
3507 :group 'org-tags
3508 :type 'boolean)
3510 (defcustom org-use-tag-inheritance t
3511 "Non-nil means tags in levels apply also for sublevels.
3512 When nil, only the tags directly given in a specific line apply there.
3513 This may also be a list of tags that should be inherited, or a regexp that
3514 matches tags that should be inherited. Additional control is possible
3515 with the variable `org-tags-exclude-from-inheritance' which gives an
3516 explicit list of tags to be excluded from inheritance, even if the value of
3517 `org-use-tag-inheritance' would select it for inheritance.
3519 If this option is t, a match early-on in a tree can lead to a large
3520 number of matches in the subtree when constructing the agenda or creating
3521 a sparse tree. If you only want to see the first match in a tree during
3522 a search, check out the variable `org-tags-match-list-sublevels'."
3523 :group 'org-tags
3524 :type '(choice
3525 (const :tag "Not" nil)
3526 (const :tag "Always" t)
3527 (repeat :tag "Specific tags" (string :tag "Tag"))
3528 (regexp :tag "Tags matched by regexp")))
3530 (defcustom org-tags-exclude-from-inheritance nil
3531 "List of tags that should never be inherited.
3532 This is a way to exclude a few tags from inheritance. For way to do
3533 the opposite, to actively allow inheritance for selected tags,
3534 see the variable `org-use-tag-inheritance'."
3535 :group 'org-tags
3536 :type '(repeat (string :tag "Tag")))
3538 (defun org-tag-inherit-p (tag)
3539 "Check if TAG is one that should be inherited."
3540 (cond
3541 ((member tag org-tags-exclude-from-inheritance) nil)
3542 ((eq org-use-tag-inheritance t) t)
3543 ((not org-use-tag-inheritance) nil)
3544 ((stringp org-use-tag-inheritance)
3545 (string-match org-use-tag-inheritance tag))
3546 ((listp org-use-tag-inheritance)
3547 (member tag org-use-tag-inheritance))
3548 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3550 (defcustom org-tags-match-list-sublevels t
3551 "Non-nil means list also sublevels of headlines matching a search.
3552 This variable applies to tags/property searches, and also to stuck
3553 projects because this search is based on a tags match as well.
3555 When set to the symbol `indented', sublevels are indented with
3556 leading dots.
3558 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3559 the sublevels of a headline matching a tag search often also match
3560 the same search. Listing all of them can create very long lists.
3561 Setting this variable to nil causes subtrees of a match to be skipped.
3563 This variable is semi-obsolete and probably should always be true. It
3564 is better to limit inheritance to certain tags using the variables
3565 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3566 :group 'org-tags
3567 :type '(choice
3568 (const :tag "No, don't list them" nil)
3569 (const :tag "Yes, do list them" t)
3570 (const :tag "List them, indented with leading dots" indented)))
3572 (defcustom org-tags-sort-function nil
3573 "When set, tags are sorted using this function as a comparator."
3574 :group 'org-tags
3575 :type '(choice
3576 (const :tag "No sorting" nil)
3577 (const :tag "Alphabetical" org-string-collate-lessp)
3578 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3579 (function :tag "Custom function" nil)))
3581 (defvar org-tags-history nil
3582 "History of minibuffer reads for tags.")
3583 (defvar org-last-tags-completion-table nil
3584 "The last used completion table for tags.")
3585 (defvar org-after-tags-change-hook nil
3586 "Hook that is run after the tags in a line have changed.")
3588 (defgroup org-properties nil
3589 "Options concerning properties in Org mode."
3590 :tag "Org Properties"
3591 :group 'org)
3593 (defcustom org-property-format "%-10s %s"
3594 "How property key/value pairs should be formatted by `indent-line'.
3595 When `indent-line' hits a property definition, it will format the line
3596 according to this format, mainly to make sure that the values are
3597 lined-up with respect to each other."
3598 :group 'org-properties
3599 :type 'string)
3601 (defcustom org-properties-postprocess-alist nil
3602 "Alist of properties and functions to adjust inserted values.
3603 Elements of this alist must be of the form
3605 ([string] [function])
3607 where [string] must be a property name and [function] must be a
3608 lambda expression: this lambda expression must take one argument,
3609 the value to adjust, and return the new value as a string.
3611 For example, this element will allow the property \"Remaining\"
3612 to be updated wrt the relation between the \"Effort\" property
3613 and the clock summary:
3615 ((\"Remaining\" (lambda(value)
3616 (let ((clocksum (org-clock-sum-current-item))
3617 (effort (org-duration-to-minutes
3618 (org-entry-get (point) \"Effort\"))))
3619 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3620 :group 'org-properties
3621 :version "24.1"
3622 :type '(alist :key-type (string :tag "Property")
3623 :value-type (function :tag "Function")))
3625 (defcustom org-use-property-inheritance nil
3626 "Non-nil means properties apply also for sublevels.
3628 This setting is chiefly used during property searches. Turning it on can
3629 cause significant overhead when doing a search, which is why it is not
3630 on by default.
3632 When nil, only the properties directly given in the current entry count.
3633 When t, every property is inherited. The value may also be a list of
3634 properties that should have inheritance, or a regular expression matching
3635 properties that should be inherited.
3637 However, note that some special properties use inheritance under special
3638 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3639 and the properties ending in \"_ALL\" when they are used as descriptor
3640 for valid values of a property.
3642 Note for programmers:
3643 When querying an entry with `org-entry-get', you can control if inheritance
3644 should be used. By default, `org-entry-get' looks only at the local
3645 properties. You can request inheritance by setting the inherit argument
3646 to t (to force inheritance) or to `selective' (to respect the setting
3647 in this variable)."
3648 :group 'org-properties
3649 :type '(choice
3650 (const :tag "Not" nil)
3651 (const :tag "Always" t)
3652 (repeat :tag "Specific properties" (string :tag "Property"))
3653 (regexp :tag "Properties matched by regexp")))
3655 (defun org-property-inherit-p (property)
3656 "Return a non-nil value if PROPERTY should be inherited."
3657 (cond
3658 ((eq org-use-property-inheritance t) t)
3659 ((not org-use-property-inheritance) nil)
3660 ((stringp org-use-property-inheritance)
3661 (string-match org-use-property-inheritance property))
3662 ((listp org-use-property-inheritance)
3663 (member-ignore-case property org-use-property-inheritance))
3664 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3666 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3667 "The default column format, if no other format has been defined.
3668 This variable can be set on the per-file basis by inserting a line
3670 #+COLUMNS: %25ITEM ....."
3671 :group 'org-properties
3672 :type 'string)
3674 (defcustom org-columns-ellipses ".."
3675 "The ellipses to be used when a field in column view is truncated.
3676 When this is the empty string, as many characters as possible are shown,
3677 but then there will be no visual indication that the field has been truncated.
3678 When this is a string of length N, the last N characters of a truncated
3679 field are replaced by this string. If the column is narrower than the
3680 ellipses string, only part of the ellipses string will be shown."
3681 :group 'org-properties
3682 :type 'string)
3684 (defconst org-global-properties-fixed
3685 '(("VISIBILITY_ALL" . "folded children content all")
3686 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3687 "List of property/value pairs that can be inherited by any entry.
3689 These are fixed values, for the preset properties. The user variable
3690 that can be used to add to this list is `org-global-properties'.
3692 The entries in this list are cons cells where the car is a property
3693 name and cdr is a string with the value. If the value represents
3694 multiple items like an \"_ALL\" property, separate the items by
3695 spaces.")
3697 (defcustom org-global-properties nil
3698 "List of property/value pairs that can be inherited by any entry.
3700 This list will be combined with the constant `org-global-properties-fixed'.
3702 The entries in this list are cons cells where the car is a property
3703 name and cdr is a string with the value.
3705 You can set buffer-local values for the same purpose in the variable
3706 `org-file-properties' this by adding lines like
3708 #+PROPERTY: NAME VALUE"
3709 :group 'org-properties
3710 :type '(repeat
3711 (cons (string :tag "Property")
3712 (string :tag "Value"))))
3714 (defvar-local org-file-properties nil
3715 "List of property/value pairs that can be inherited by any entry.
3716 Valid for the current buffer.
3717 This variable is populated from #+PROPERTY lines.")
3719 (defgroup org-agenda nil
3720 "Options concerning agenda views in Org mode."
3721 :tag "Org Agenda"
3722 :group 'org)
3724 (defvar-local org-category nil
3725 "Variable used by Org files to set a category for agenda display.
3726 Such files should use a file variable to set it, for example
3728 # -*- mode: org; org-category: \"ELisp\"
3730 or contain a special line
3732 #+CATEGORY: ELisp
3734 If the file does not specify a category, then file's base name
3735 is used instead.")
3736 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3738 (defcustom org-agenda-files nil
3739 "The files to be used for agenda display.
3741 If an entry is a directory, all files in that directory that are matched
3742 by `org-agenda-file-regexp' will be part of the file list.
3744 If the value of the variable is not a list but a single file name, then
3745 the list of agenda files is actually stored and maintained in that file,
3746 one agenda file per line. In this file paths can be given relative to
3747 `org-directory'. Tilde expansion and environment variable substitution
3748 are also made.
3750 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3751 and removed with `\\[org-remove-file]'."
3752 :group 'org-agenda
3753 :type '(choice
3754 (repeat :tag "List of files and directories" file)
3755 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3757 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3758 "Regular expression to match files for `org-agenda-files'.
3759 If any element in the list in that variable contains a directory instead
3760 of a normal file, all files in that directory that are matched by this
3761 regular expression will be included."
3762 :group 'org-agenda
3763 :type 'regexp)
3765 (defcustom org-agenda-text-search-extra-files nil
3766 "List of extra files to be searched by text search commands.
3767 These files will be searched in addition to the agenda files by the
3768 commands `org-search-view' (`\\[org-agenda] s') \
3769 and `org-occur-in-agenda-files'.
3770 Note that these files will only be searched for text search commands,
3771 not for the other agenda views like todo lists, tag searches or the weekly
3772 agenda. This variable is intended to list notes and possibly archive files
3773 that should also be searched by these two commands.
3774 In fact, if the first element in the list is the symbol `agenda-archives',
3775 then all archive files of all agenda files will be added to the search
3776 scope."
3777 :group 'org-agenda
3778 :type '(set :greedy t
3779 (const :tag "Agenda Archives" agenda-archives)
3780 (repeat :inline t (file))))
3782 (defvaralias 'org-agenda-multi-occur-extra-files
3783 'org-agenda-text-search-extra-files)
3785 (defcustom org-agenda-skip-unavailable-files nil
3786 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3787 A nil value means to remove them, after a query, from the list."
3788 :group 'org-agenda
3789 :type 'boolean)
3791 (defcustom org-agenda-diary-file 'diary-file
3792 "File to which to add new entries with the `i' key in agenda and calendar.
3793 When this is the symbol `diary-file', the functionality in the Emacs
3794 calendar will be used to add entries to the `diary-file'. But when this
3795 points to a file, `org-agenda-diary-entry' will be used instead."
3796 :group 'org-agenda
3797 :type '(choice
3798 (const :tag "The standard Emacs diary file" diary-file)
3799 (file :tag "Special Org file diary entries")))
3801 (defgroup org-latex nil
3802 "Options for embedding LaTeX code into Org mode."
3803 :tag "Org LaTeX"
3804 :group 'org)
3806 (defcustom org-format-latex-options
3807 '(:foreground default :background default :scale 1.0
3808 :html-foreground "Black" :html-background "Transparent"
3809 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3810 "Options for creating images from LaTeX fragments.
3811 This is a property list with the following properties:
3812 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3813 `default' means use the foreground of the default face.
3814 `auto' means use the foreground from the text face.
3815 :background the background color, or \"Transparent\".
3816 `default' means use the background of the default face.
3817 `auto' means use the background from the text face.
3818 :scale a scaling factor for the size of the images, to get more pixels
3819 :html-foreground, :html-background, :html-scale
3820 the same numbers for HTML export.
3821 :matchers a list indicating which matchers should be used to
3822 find LaTeX fragments. Valid members of this list are:
3823 \"begin\" find environments
3824 \"$1\" find single characters surrounded by $.$
3825 \"$\" find math expressions surrounded by $...$
3826 \"$$\" find math expressions surrounded by $$....$$
3827 \"\\(\" find math expressions surrounded by \\(...\\)
3828 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3829 :group 'org-latex
3830 :type 'plist)
3832 (defcustom org-format-latex-signal-error t
3833 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3834 When nil, just push out a message."
3835 :group 'org-latex
3836 :version "24.1"
3837 :type 'boolean)
3839 (defcustom org-latex-to-mathml-jar-file nil
3840 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3841 Use this to specify additional executable file say a jar file.
3843 When using MathToWeb as the converter, specify the full-path to
3844 your mathtoweb.jar file."
3845 :group 'org-latex
3846 :version "24.1"
3847 :type '(choice
3848 (const :tag "None" nil)
3849 (file :tag "JAR file" :must-match t)))
3851 (defcustom org-latex-to-mathml-convert-command nil
3852 "Command to convert LaTeX fragments to MathML.
3853 Replace format-specifiers in the command as noted below and use
3854 `shell-command' to convert LaTeX to MathML.
3855 %j: Executable file in fully expanded form as specified by
3856 `org-latex-to-mathml-jar-file'.
3857 %I: Input LaTeX file in fully expanded form.
3858 %i: The latex fragment to be converted.
3859 %o: Output MathML file.
3861 This command is used by `org-create-math-formula'.
3863 When using MathToWeb as the converter, set this option to
3864 \"java -jar %j -unicode -force -df %o %I\".
3866 When using LaTeXML set this option to
3867 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3868 :group 'org-latex
3869 :version "24.1"
3870 :type '(choice
3871 (const :tag "None" nil)
3872 (string :tag "\nShell command")))
3874 (defcustom org-preview-latex-default-process 'dvipng
3875 "The default process to convert LaTeX fragments to image files.
3876 All available processes and theirs documents can be found in
3877 `org-preview-latex-process-alist', which see."
3878 :group 'org-latex
3879 :version "26.1"
3880 :package-version '(Org . "9.0")
3881 :type 'symbol)
3883 (defcustom org-preview-latex-process-alist
3884 '((dvipng
3885 :programs ("latex" "dvipng")
3886 :description "dvi > png"
3887 :message "you need to install the programs: latex and dvipng."
3888 :image-input-type "dvi"
3889 :image-output-type "png"
3890 :image-size-adjust (1.0 . 1.0)
3891 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3892 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3893 (dvisvgm
3894 :programs ("latex" "dvisvgm")
3895 :description "dvi > svg"
3896 :message "you need to install the programs: latex and dvisvgm."
3897 :use-xcolor t
3898 :image-input-type "dvi"
3899 :image-output-type "svg"
3900 :image-size-adjust (1.7 . 1.5)
3901 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3902 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3903 (imagemagick
3904 :programs ("latex" "convert")
3905 :description "pdf > png"
3906 :message "you need to install the programs: latex and imagemagick."
3907 :use-xcolor t
3908 :image-input-type "pdf"
3909 :image-output-type "png"
3910 :image-size-adjust (1.0 . 1.0)
3911 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3912 :image-converter
3913 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3914 "Definitions of external processes for LaTeX previewing.
3915 Org mode can use some external commands to generate TeX snippet's images for
3916 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3917 `org-create-formula-image' how to call them.
3919 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3920 PROPERTIES accepts the following attributes:
3922 :programs list of strings, required programs.
3923 :description string, describe the process.
3924 :message string, message it when required programs cannot be found.
3925 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3926 :image-output-type string, output file type of image converter (e.g., \"png\").
3927 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3928 deal with background and foreground color of image.
3929 Otherwise, dvipng style background and foreground color
3930 format are generated. You may then refer to them in
3931 command options with \"%F\" and \"%B\".
3932 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3933 image size showed in buffer and the cdr element is for
3934 HTML file. This option is only useful for process
3935 developers, users should use variable
3936 `org-format-latex-options' instead.
3937 :post-clean list of strings, files matched are to be cleaned up once
3938 the image is generated. When nil, the files with \".dvi\",
3939 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3940 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3941 be cleaned up.
3942 :latex-header list of strings, the LaTeX header of the snippet file.
3943 When nil, the fallback value is used instead, which is
3944 controlled by `org-format-latex-header',
3945 `org-latex-default-packages-alist' and
3946 `org-latex-packages-alist', which see.
3947 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3948 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3949 replaced with values defined below.
3950 :image-converter list of image converter commands strings. Each of them is
3951 given to the shell and supports any of the following
3952 place-holders defined below.
3954 Place-holders used by `:image-converter' and `:latex-compiler':
3956 %f input file name
3957 %b base name of input file
3958 %o base directory of input file
3959 %O absolute output file name
3961 Place-holders only used by `:image-converter':
3963 %F foreground of image
3964 %B background of image
3965 %D dpi, which is used to adjust image size by some processing commands.
3966 %S the image size scale ratio, which is used to adjust image size by some
3967 processing commands."
3968 :group 'org-latex
3969 :version "26.1"
3970 :package-version '(Org . "9.0")
3971 :type '(alist :tag "LaTeX to image backends"
3972 :value-type (plist)))
3974 (defcustom org-preview-latex-image-directory "ltximg/"
3975 "Path to store latex preview images.
3976 A relative path here creates many directories relative to the
3977 processed Org files paths. An absolute path puts all preview
3978 images at the same place."
3979 :group 'org-latex
3980 :version "26.1"
3981 :package-version '(Org . "9.0")
3982 :type 'string)
3984 (defun org-format-latex-mathml-available-p ()
3985 "Return t if `org-latex-to-mathml-convert-command' is usable."
3986 (save-match-data
3987 (when (and (boundp 'org-latex-to-mathml-convert-command)
3988 org-latex-to-mathml-convert-command)
3989 (let ((executable (car (split-string
3990 org-latex-to-mathml-convert-command))))
3991 (when (executable-find executable)
3992 (if (string-match
3993 "%j" org-latex-to-mathml-convert-command)
3994 (file-readable-p org-latex-to-mathml-jar-file)
3995 t))))))
3997 (defcustom org-format-latex-header "\\documentclass{article}
3998 \\usepackage[usenames]{color}
3999 \[PACKAGES]
4000 \[DEFAULT-PACKAGES]
4001 \\pagestyle{empty} % do not remove
4002 % The settings below are copied from fullpage.sty
4003 \\setlength{\\textwidth}{\\paperwidth}
4004 \\addtolength{\\textwidth}{-3cm}
4005 \\setlength{\\oddsidemargin}{1.5cm}
4006 \\addtolength{\\oddsidemargin}{-2.54cm}
4007 \\setlength{\\evensidemargin}{\\oddsidemargin}
4008 \\setlength{\\textheight}{\\paperheight}
4009 \\addtolength{\\textheight}{-\\headheight}
4010 \\addtolength{\\textheight}{-\\headsep}
4011 \\addtolength{\\textheight}{-\\footskip}
4012 \\addtolength{\\textheight}{-3cm}
4013 \\setlength{\\topmargin}{1.5cm}
4014 \\addtolength{\\topmargin}{-2.54cm}"
4015 "The document header used for processing LaTeX fragments.
4016 It is imperative that this header make sure that no page number
4017 appears on the page. The package defined in the variables
4018 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4019 will either replace the placeholder \"[PACKAGES]\" in this
4020 header, or they will be appended."
4021 :group 'org-latex
4022 :type 'string)
4024 (defun org-set-packages-alist (var val)
4025 "Set the packages alist and make sure it has 3 elements per entry."
4026 (set var (mapcar (lambda (x)
4027 (if (and (consp x) (= (length x) 2))
4028 (list (car x) (nth 1 x) t)
4030 val)))
4032 (defun org-get-packages-alist (var)
4033 "Get the packages alist and make sure it has 3 elements per entry."
4034 (mapcar (lambda (x)
4035 (if (and (consp x) (= (length x) 2))
4036 (list (car x) (nth 1 x) t)
4038 (default-value var)))
4040 (defcustom org-latex-default-packages-alist
4041 '(("AUTO" "inputenc" t ("pdflatex"))
4042 ("T1" "fontenc" t ("pdflatex"))
4043 ("" "graphicx" t)
4044 ("" "grffile" t)
4045 ("" "longtable" nil)
4046 ("" "wrapfig" nil)
4047 ("" "rotating" nil)
4048 ("normalem" "ulem" t)
4049 ("" "amsmath" t)
4050 ("" "textcomp" t)
4051 ("" "amssymb" t)
4052 ("" "capt-of" nil)
4053 ("" "hyperref" nil))
4054 "Alist of default packages to be inserted in the header.
4056 Change this only if one of the packages here causes an
4057 incompatibility with another package you are using.
4059 The packages in this list are needed by one part or another of
4060 Org mode to function properly:
4062 - inputenc, fontenc: for basic font and character selection
4063 - graphicx: for including images
4064 - grffile: allow periods and spaces in graphics file names
4065 - longtable: For multipage tables
4066 - wrapfig: for figure placement
4067 - rotating: for sideways figures and tables
4068 - ulem: for underline and strike-through
4069 - amsmath: for subscript and superscript and math environments
4070 - textcomp, amssymb: for various symbols used
4071 for interpreting the entities in `org-entities'. You can skip
4072 some of these packages if you don't use any of their symbols.
4073 - capt-of: for captions outside of floats
4074 - hyperref: for cross references
4076 Therefore you should not modify this variable unless you know
4077 what you are doing. The one reason to change it anyway is that
4078 you might be loading some other package that conflicts with one
4079 of the default packages. Each element is either a cell or
4080 a string.
4082 A cell is of the format
4084 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4086 If SNIPPET-FLAG is non-nil, the package also needs to be included
4087 when compiling LaTeX snippets into images for inclusion into
4088 non-LaTeX output. COMPILERS is a list of compilers that should
4089 include the package, see `org-latex-compiler'. If the document
4090 compiler is not in the list, and the list is non-nil, the package
4091 will not be inserted in the final document.
4093 A string will be inserted as-is in the header of the document."
4094 :group 'org-latex
4095 :group 'org-export-latex
4096 :set 'org-set-packages-alist
4097 :get 'org-get-packages-alist
4098 :version "26.1"
4099 :package-version '(Org . "8.3")
4100 :type '(repeat
4101 (choice
4102 (list :tag "options/package pair"
4103 (string :tag "options")
4104 (string :tag "package")
4105 (boolean :tag "Snippet")
4106 (choice
4107 (const :tag "For all compilers" nil)
4108 (repeat :tag "Allowed compiler" string)))
4109 (string :tag "A line of LaTeX"))))
4111 (defcustom org-latex-packages-alist nil
4112 "Alist of packages to be inserted in every LaTeX header.
4114 These will be inserted after `org-latex-default-packages-alist'.
4115 Each element is either a cell or a string.
4117 A cell is of the format:
4119 (\"options\" \"package\" SNIPPET-FLAG)
4121 SNIPPET-FLAG, when non-nil, indicates that this package is also
4122 needed when turning LaTeX snippets into images for inclusion into
4123 non-LaTeX output.
4125 A string will be inserted as-is in the header of the document.
4127 Make sure that you only list packages here which:
4129 - you want in every file;
4130 - do not conflict with the setup in `org-format-latex-header';
4131 - do not conflict with the default packages in
4132 `org-latex-default-packages-alist'."
4133 :group 'org-latex
4134 :group 'org-export-latex
4135 :set 'org-set-packages-alist
4136 :get 'org-get-packages-alist
4137 :type '(repeat
4138 (choice
4139 (list :tag "options/package pair"
4140 (string :tag "options")
4141 (string :tag "package")
4142 (boolean :tag "Snippet"))
4143 (string :tag "A line of LaTeX"))))
4145 (defgroup org-appearance nil
4146 "Settings for Org mode appearance."
4147 :tag "Org Appearance"
4148 :group 'org)
4150 (defcustom org-level-color-stars-only nil
4151 "Non-nil means fontify only the stars in each headline.
4152 When nil, the entire headline is fontified.
4153 Changing it requires restart of `font-lock-mode' to become effective
4154 also in regions already fontified."
4155 :group 'org-appearance
4156 :type 'boolean)
4158 (defcustom org-hide-leading-stars nil
4159 "Non-nil means hide the first N-1 stars in a headline.
4160 This works by using the face `org-hide' for these stars. This
4161 face is white for a light background, and black for a dark
4162 background. You may have to customize the face `org-hide' to
4163 make this work.
4164 Changing it requires restart of `font-lock-mode' to become effective
4165 also in regions already fontified.
4166 You may also set this on a per-file basis by adding one of the following
4167 lines to the buffer:
4169 #+STARTUP: hidestars
4170 #+STARTUP: showstars"
4171 :group 'org-appearance
4172 :type 'boolean)
4174 (defcustom org-hidden-keywords nil
4175 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4176 For example, a value \\='(title) for this list makes the document's title
4177 appear in the buffer without the initial \"#+TITLE:\" part."
4178 :group 'org-appearance
4179 :version "24.1"
4180 :type '(set (const :tag "#+AUTHOR" author)
4181 (const :tag "#+DATE" date)
4182 (const :tag "#+EMAIL" email)
4183 (const :tag "#+TITLE" title)))
4185 (defcustom org-custom-properties nil
4186 "List of properties (as strings) with a special meaning.
4187 The default use of these custom properties is to let the user
4188 hide them with `org-toggle-custom-properties-visibility'."
4189 :group 'org-properties
4190 :group 'org-appearance
4191 :version "24.3"
4192 :type '(repeat (string :tag "Property Name")))
4194 (defcustom org-fontify-done-headline nil
4195 "Non-nil means change the face of a headline if it is marked DONE.
4196 Normally, only the TODO/DONE keyword indicates the state of a headline.
4197 When this is non-nil, the headline after the keyword is set to the
4198 `org-headline-done' as an additional indication."
4199 :group 'org-appearance
4200 :type 'boolean)
4202 (defcustom org-fontify-emphasized-text t
4203 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4204 Changing this variable requires a restart of Emacs to take effect."
4205 :group 'org-appearance
4206 :type 'boolean)
4208 (defcustom org-fontify-whole-heading-line nil
4209 "Non-nil means fontify the whole line for headings.
4210 This is useful when setting a background color for the
4211 org-level-* faces."
4212 :group 'org-appearance
4213 :type 'boolean)
4215 (defcustom org-highlight-latex-and-related nil
4216 "Non-nil means highlight LaTeX related syntax in the buffer.
4217 When non nil, the value should be a list containing any of the
4218 following symbols:
4219 `latex' Highlight LaTeX snippets and environments.
4220 `script' Highlight subscript and superscript.
4221 `entities' Highlight entities."
4222 :group 'org-appearance
4223 :version "24.4"
4224 :package-version '(Org . "8.0")
4225 :type '(choice
4226 (const :tag "No highlighting" nil)
4227 (set :greedy t :tag "Highlight"
4228 (const :tag "LaTeX snippets and environments" latex)
4229 (const :tag "Subscript and superscript" script)
4230 (const :tag "Entities" entities))))
4232 (defcustom org-hide-emphasis-markers nil
4233 "Non-nil mean font-lock should hide the emphasis marker characters."
4234 :group 'org-appearance
4235 :type 'boolean)
4237 (defcustom org-hide-macro-markers nil
4238 "Non-nil mean font-lock should hide the brackets marking macro calls."
4239 :group 'org-appearance
4240 :type 'boolean)
4242 (defcustom org-pretty-entities nil
4243 "Non-nil means show entities as UTF8 characters.
4244 When nil, the \\name form remains in the buffer."
4245 :group 'org-appearance
4246 :version "24.1"
4247 :type 'boolean)
4249 (defcustom org-pretty-entities-include-sub-superscripts t
4250 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4251 :group 'org-appearance
4252 :version "24.1"
4253 :type 'boolean)
4255 (defvar org-emph-re nil
4256 "Regular expression for matching emphasis.
4257 After a match, the match groups contain these elements:
4258 0 The match of the full regular expression, including the characters
4259 before and after the proper match
4260 1 The character before the proper match, or empty at beginning of line
4261 2 The proper match, including the leading and trailing markers
4262 3 The leading marker like * or /, indicating the type of highlighting
4263 4 The text between the emphasis markers, not including the markers
4264 5 The character after the match, empty at the end of a line")
4266 (defvar org-verbatim-re nil
4267 "Regular expression for matching verbatim text.")
4269 (defvar org-emphasis-regexp-components) ; defined just below
4270 (defvar org-emphasis-alist) ; defined just below
4271 (defun org-set-emph-re (var val)
4272 "Set variable and compute the emphasis regular expression."
4273 (set var val)
4274 (when (and (boundp 'org-emphasis-alist)
4275 (boundp 'org-emphasis-regexp-components)
4276 org-emphasis-alist org-emphasis-regexp-components)
4277 (pcase-let*
4278 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4279 (body (if (<= nl 0) body
4280 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4281 (template
4282 (format (concat "\\([%s]\\|^\\)" ;before markers
4283 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4284 "\\([%s]\\|$\\)") ;after markers
4285 pre border border body border post)))
4286 (setq org-emph-re (format template "*/_+"))
4287 (setq org-verbatim-re (format template "=~")))))
4289 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4290 ;; set this option proved cumbersome. See this message/thread:
4291 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4292 (defvar org-emphasis-regexp-components
4293 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4294 "Components used to build the regular expression for emphasis.
4295 This is a list with five entries. Terminology: In an emphasis string
4296 like \" *strong word* \", we call the initial space PREMATCH, the final
4297 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4298 and \"trong wor\" is the body. The different components in this variable
4299 specify what is allowed/forbidden in each part:
4301 pre Chars allowed as prematch. Beginning of line will be allowed too.
4302 post Chars allowed as postmatch. End of line will be allowed too.
4303 border The chars *forbidden* as border characters.
4304 body-regexp A regexp like \".\" to match a body character. Don't use
4305 non-shy groups here, and don't allow newline here.
4306 newline The maximum number of newlines allowed in an emphasis exp.
4308 You need to reload Org or to restart Emacs after setting this.")
4310 (defcustom org-emphasis-alist
4311 '(("*" bold)
4312 ("/" italic)
4313 ("_" underline)
4314 ("=" org-verbatim verbatim)
4315 ("~" org-code verbatim)
4316 ("+" (:strike-through t)))
4317 "Alist of characters and faces to emphasize text.
4318 Text starting and ending with a special character will be emphasized,
4319 for example *bold*, _underlined_ and /italic/. This variable sets the
4320 marker characters and the face to be used by font-lock for highlighting
4321 in Org buffers.
4323 You need to reload Org or to restart Emacs after customizing this."
4324 :group 'org-appearance
4325 :set 'org-set-emph-re
4326 :version "24.4"
4327 :package-version '(Org . "8.0")
4328 :type '(repeat
4329 (list
4330 (string :tag "Marker character")
4331 (choice
4332 (face :tag "Font-lock-face")
4333 (plist :tag "Face property list"))
4334 (option (const verbatim)))))
4336 (defvar org-protecting-blocks '("src" "example" "export")
4337 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4338 This is needed for font-lock setup.")
4340 ;;; Functions and variables from their packages
4341 ;; Declared here to avoid compiler warnings
4342 (defvar mark-active)
4344 ;; Various packages
4345 (declare-function calc-eval "calc" (str &optional separator &rest args))
4346 (declare-function calendar-forward-day "cal-move" (arg))
4347 (declare-function calendar-goto-date "cal-move" (date))
4348 (declare-function calendar-goto-today "cal-move" ())
4349 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4350 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4351 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4352 (declare-function cdlatex-tab "ext:cdlatex" ())
4353 (declare-function dired-get-filename
4354 "dired"
4355 (&optional localp no-error-if-not-filep))
4356 (declare-function iswitchb-read-buffer
4357 "iswitchb"
4358 (prompt &optional
4359 default require-match _predicate start matches-set))
4360 (declare-function org-agenda-change-all-lines
4361 "org-agenda"
4362 (newhead hdmarker &optional fixface just-this))
4363 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4364 "org-agenda"
4365 (&optional end))
4366 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4367 (declare-function org-agenda-format-item
4368 "org-agenda"
4369 (extra txt &optional level category tags dotime
4370 remove-re habitp))
4371 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4372 (declare-function org-agenda-save-markers-for-cut-and-paste
4373 "org-agenda"
4374 (beg end))
4375 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4376 (declare-function org-agenda-skip "org-agenda" ())
4377 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4378 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4379 (declare-function org-indent-mode "org-indent" (&optional arg))
4380 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4381 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4382 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4383 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4384 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4385 (declare-function parse-time-string "parse-time" (string))
4387 (defvar align-mode-rules-list)
4388 (defvar calc-embedded-close-formula)
4389 (defvar calc-embedded-open-formula)
4390 (defvar calc-embedded-open-mode)
4391 (defvar font-lock-unfontify-region-function)
4392 (defvar iswitchb-temp-buflist)
4393 (defvar org-agenda-tags-todo-honor-ignore-options)
4394 (defvar remember-data-file)
4395 (defvar texmathp-why)
4397 ;;;###autoload
4398 (defun turn-on-orgtbl ()
4399 "Unconditionally turn on `orgtbl-mode'."
4400 (require 'org-table)
4401 (orgtbl-mode 1))
4403 (defun org-at-table-p (&optional table-type)
4404 "Non-nil if the cursor is inside an Org table.
4405 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4406 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4407 (or (not (derived-mode-p 'org-mode))
4408 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4409 (and e (or table-type
4410 (eq 'org (org-element-property :type e))))))))
4412 (defun org-at-table.el-p ()
4413 "Non-nil when point is at a table.el table."
4414 (and (org-match-line "[ \t]*[|+]")
4415 (let ((element (org-element-at-point)))
4416 (and (eq (org-element-type element) 'table)
4417 (eq (org-element-property :type element) 'table.el)))))
4419 (defun org-at-table-hline-p ()
4420 "Non-nil when point is inside a hline in a table.
4421 Assume point is already in a table."
4422 (org-match-line org-table-hline-regexp))
4424 (defun org-table-map-tables (function &optional quietly)
4425 "Apply FUNCTION to the start of all tables in the buffer."
4426 (org-with-wide-buffer
4427 (goto-char (point-min))
4428 (while (re-search-forward org-table-any-line-regexp nil t)
4429 (unless quietly
4430 (message "Mapping tables: %d%%"
4431 (floor (* 100.0 (point)) (buffer-size))))
4432 (beginning-of-line 1)
4433 (when (and (looking-at org-table-line-regexp)
4434 ;; Exclude tables in src/example/verbatim/clocktable blocks
4435 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4436 (save-excursion (funcall function))
4437 (or (looking-at org-table-line-regexp)
4438 (forward-char 1)))
4439 (re-search-forward org-table-any-border-regexp nil 1)))
4440 (unless quietly (message "Mapping tables: done")))
4442 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4443 (declare-function org-clock-update-mode-line "org-clock" ())
4444 (declare-function org-resolve-clocks "org-clock"
4445 (&optional also-non-dangling-p prompt last-valid))
4447 (defun org-at-TBLFM-p (&optional pos)
4448 "Non-nil when point (or POS) is in #+TBLFM line."
4449 (save-excursion
4450 (goto-char (or pos (point)))
4451 (beginning-of-line)
4452 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4453 (eq (org-element-type (org-element-at-point)) 'table))))
4455 (defvar org-clock-start-time)
4456 (defvar org-clock-marker (make-marker)
4457 "Marker recording the last clock-in.")
4458 (defvar org-clock-hd-marker (make-marker)
4459 "Marker recording the last clock-in, but the headline position.")
4460 (defvar org-clock-heading ""
4461 "The heading of the current clock entry.")
4462 (defun org-clock-is-active ()
4463 "Return the buffer where the clock is currently running.
4464 Return nil if no clock is running."
4465 (marker-buffer org-clock-marker))
4467 (defun org-check-running-clock ()
4468 "Check if the current buffer contains the running clock.
4469 If yes, offer to stop it and to save the buffer with the changes."
4470 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4471 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4472 (buffer-name))))
4473 (org-clock-out)
4474 (when (y-or-n-p "Save changed buffer?")
4475 (save-buffer))))
4477 (defun org-clocktable-try-shift (dir n)
4478 "Check if this line starts a clock table, if yes, shift the time block."
4479 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4480 (org-clocktable-shift dir n)))
4482 ;;;###autoload
4483 (defun org-clock-persistence-insinuate ()
4484 "Set up hooks for clock persistence."
4485 (require 'org-clock)
4486 (add-hook 'org-mode-hook 'org-clock-load)
4487 (add-hook 'kill-emacs-hook 'org-clock-save))
4489 (defgroup org-archive nil
4490 "Options concerning archiving in Org mode."
4491 :tag "Org Archive"
4492 :group 'org-structure)
4494 (defcustom org-archive-location "%s_archive::"
4495 "The location where subtrees should be archived.
4497 The value of this variable is a string, consisting of two parts,
4498 separated by a double-colon. The first part is a filename and
4499 the second part is a headline.
4501 When the filename is omitted, archiving happens in the same file.
4502 %s in the filename will be replaced by the current file
4503 name (without the directory part). Archiving to a different file
4504 is useful to keep archived entries from contributing to the
4505 Org Agenda.
4507 The archived entries will be filed as subtrees of the specified
4508 headline. When the headline is omitted, the subtrees are simply
4509 filed away at the end of the file, as top-level entries. Also in
4510 the heading you can use %s to represent the file name, this can be
4511 useful when using the same archive for a number of different files.
4513 Here are a few examples:
4514 \"%s_archive::\"
4515 If the current file is Projects.org, archive in file
4516 Projects.org_archive, as top-level trees. This is the default.
4518 \"::* Archived Tasks\"
4519 Archive in the current file, under the top-level headline
4520 \"* Archived Tasks\".
4522 \"~/org/archive.org::\"
4523 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4525 \"~/org/archive.org::* From %s\"
4526 Archive in file ~/org/archive.org (absolute path), under headlines
4527 \"From FILENAME\" where file name is the current file name.
4529 \"~/org/datetree.org::datetree/* Finished Tasks\"
4530 The \"datetree/\" string is special, signifying to archive
4531 items to the datetree. Items are placed in either the CLOSED
4532 date of the item, or the current date if there is no CLOSED date.
4533 The heading will be a subentry to the current date. There doesn't
4534 need to be a heading, but there always needs to be a slash after
4535 datetree. For example, to store archived items directly in the
4536 datetree, use \"~/org/datetree.org::datetree/\".
4538 \"basement::** Finished Tasks\"
4539 Archive in file ./basement (relative path), as level 3 trees
4540 below the level 2 heading \"** Finished Tasks\".
4542 You may set this option on a per-file basis by adding to the buffer a
4543 line like
4545 #+ARCHIVE: basement::** Finished Tasks
4547 You may also define it locally for a subtree by setting an ARCHIVE property
4548 in the entry. If such a property is found in an entry, or anywhere up
4549 the hierarchy, it will be used."
4550 :group 'org-archive
4551 :type 'string)
4553 (defcustom org-agenda-skip-archived-trees t
4554 "Non-nil means the agenda will skip any items located in archived trees.
4555 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4556 variable is no longer recommended, you should leave it at the value t.
4557 Instead, use the key `v' to cycle the archives-mode in the agenda."
4558 :group 'org-archive
4559 :group 'org-agenda-skip
4560 :type 'boolean)
4562 (defcustom org-columns-skip-archived-trees t
4563 "Non-nil means ignore archived trees when creating column view."
4564 :group 'org-archive
4565 :group 'org-properties
4566 :type 'boolean)
4568 (defcustom org-cycle-open-archived-trees nil
4569 "Non-nil means `org-cycle' will open archived trees.
4570 An archived tree is a tree marked with the tag ARCHIVE.
4571 When nil, archived trees will stay folded. You can still open them with
4572 normal outline commands like `show-all', but not with the cycling commands."
4573 :group 'org-archive
4574 :group 'org-cycle
4575 :type 'boolean)
4577 (defcustom org-sparse-tree-open-archived-trees nil
4578 "Non-nil means sparse tree construction shows matches in archived trees.
4579 When nil, matches in these trees are highlighted, but the trees are kept in
4580 collapsed state."
4581 :group 'org-archive
4582 :group 'org-sparse-trees
4583 :type 'boolean)
4585 (defcustom org-sparse-tree-default-date-type nil
4586 "The default date type when building a sparse tree.
4587 When this is nil, a date is a scheduled or a deadline timestamp.
4588 Otherwise, these types are allowed:
4590 all: all timestamps
4591 active: only active timestamps (<...>)
4592 inactive: only inactive timestamps ([...])
4593 scheduled: only scheduled timestamps
4594 deadline: only deadline timestamps"
4595 :type '(choice (const :tag "Scheduled or deadline" nil)
4596 (const :tag "All timestamps" all)
4597 (const :tag "Only active timestamps" active)
4598 (const :tag "Only inactive timestamps" inactive)
4599 (const :tag "Only scheduled timestamps" scheduled)
4600 (const :tag "Only deadline timestamps" deadline)
4601 (const :tag "Only closed timestamps" closed))
4602 :version "26.1"
4603 :package-version '(Org . "8.3")
4604 :group 'org-sparse-trees)
4606 (defun org-cycle-hide-archived-subtrees (state)
4607 "Re-hide all archived subtrees after a visibility state change.
4608 STATE should be one of the symbols listed in the docstring of
4609 `org-cycle-hook'."
4610 (when (and (not org-cycle-open-archived-trees)
4611 (not (memq state '(overview folded))))
4612 (save-excursion
4613 (let* ((globalp (memq state '(contents all)))
4614 (beg (if globalp (point-min) (point)))
4615 (end (if globalp (point-max) (org-end-of-subtree t))))
4616 (org-hide-archived-subtrees beg end)
4617 (goto-char beg)
4618 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4619 (message "%s" (substitute-command-keys
4620 "Subtree is archived and stays closed. Use \
4621 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4623 (defun org-force-cycle-archived ()
4624 "Cycle subtree even if it is archived."
4625 (interactive)
4626 (setq this-command 'org-cycle)
4627 (let ((org-cycle-open-archived-trees t))
4628 (call-interactively 'org-cycle)))
4630 (defun org-hide-archived-subtrees (beg end)
4631 "Re-hide all archived subtrees after a visibility state change."
4632 (org-with-wide-buffer
4633 (let ((case-fold-search nil)
4634 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4635 (goto-char beg)
4636 ;; Include headline point is currently on.
4637 (beginning-of-line)
4638 (while (and (< (point) end) (re-search-forward re end t))
4639 (when (member org-archive-tag (org-get-tags nil t))
4640 (org-flag-subtree t)
4641 (org-end-of-subtree t))))))
4643 (defun org-flag-subtree (flag)
4644 (save-excursion
4645 (org-back-to-heading t)
4646 (org-flag-region (line-end-position)
4647 (progn (org-end-of-subtree t) (point))
4648 flag
4649 'outline)))
4651 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4653 ;; Declare Column View Code
4655 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4656 (declare-function org-columns-compute "org-colview" (property))
4658 ;; Declare ID code
4660 (declare-function org-id-store-link "org-id")
4661 (declare-function org-id-locations-load "org-id")
4662 (declare-function org-id-locations-save "org-id")
4663 (defvar org-id-track-globally)
4665 ;;; Variables for pre-computed regular expressions, all buffer local
4667 (defvar-local org-todo-regexp nil
4668 "Matches any of the TODO state keywords.
4669 Since TODO keywords are case-sensitive, `case-fold-search' is
4670 expected to be bound to nil when matching against this regexp.")
4672 (defvar-local org-not-done-regexp nil
4673 "Matches any of the TODO state keywords except the last one.
4674 Since TODO keywords are case-sensitive, `case-fold-search' is
4675 expected to be bound to nil when matching against this regexp.")
4677 (defvar-local org-not-done-heading-regexp nil
4678 "Matches a TODO headline that is not done.
4679 Since TODO keywords are case-sensitive, `case-fold-search' is
4680 expected to be bound to nil when matching against this regexp.")
4682 (defvar-local org-todo-line-regexp nil
4683 "Matches a headline and puts TODO state into group 2 if present.
4684 Since TODO keywords are case-sensitive, `case-fold-search' is
4685 expected to be bound to nil when matching against this regexp.")
4687 (defvar-local org-complex-heading-regexp nil
4688 "Matches a headline and puts everything into groups:
4690 group 1: Stars
4691 group 2: The TODO keyword, maybe
4692 group 3: Priority cookie
4693 group 4: True headline
4694 group 5: Tags
4696 Since TODO keywords are case-sensitive, `case-fold-search' is
4697 expected to be bound to nil when matching against this regexp.")
4699 (defvar-local org-complex-heading-regexp-format nil
4700 "Printf format to make regexp to match an exact headline.
4701 This regexp will match the headline of any node which has the
4702 exact headline text that is put into the format, but may have any
4703 TODO state, priority and tags.")
4705 (defvar-local org-todo-line-tags-regexp nil
4706 "Matches a headline and puts TODO state into group 2 if present.
4707 Also put tags into group 4 if tags are present.")
4709 (defconst org-plain-time-of-day-regexp
4710 (concat
4711 "\\(\\<[012]?[0-9]"
4712 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4713 "\\(--?"
4714 "\\(\\<[012]?[0-9]"
4715 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4716 "\\)?")
4717 "Regular expression to match a plain time or time range.
4718 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4719 groups carry important information:
4720 0 the full match
4721 1 the first time, range or not
4722 8 the second time, if it is a range.")
4724 (defconst org-plain-time-extension-regexp
4725 (concat
4726 "\\(\\<[012]?[0-9]"
4727 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4728 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4729 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4730 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4731 groups carry important information:
4732 0 the full match
4733 7 hours of duration
4734 9 minutes of duration")
4736 (defconst org-stamp-time-of-day-regexp
4737 (concat
4738 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4739 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4740 "\\(--?"
4741 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4742 "Regular expression to match a timestamp time or time range.
4743 After a match, the following groups carry important information:
4744 0 the full match
4745 1 date plus weekday, for back referencing to make sure both times are on the same day
4746 2 the first time, range or not
4747 4 the second time, if it is a range.")
4749 (defconst org-startup-options
4750 '(("fold" org-startup-folded t)
4751 ("overview" org-startup-folded t)
4752 ("nofold" org-startup-folded nil)
4753 ("showall" org-startup-folded nil)
4754 ("showeverything" org-startup-folded showeverything)
4755 ("content" org-startup-folded content)
4756 ("indent" org-startup-indented t)
4757 ("noindent" org-startup-indented nil)
4758 ("hidestars" org-hide-leading-stars t)
4759 ("showstars" org-hide-leading-stars nil)
4760 ("odd" org-odd-levels-only t)
4761 ("oddeven" org-odd-levels-only nil)
4762 ("align" org-startup-align-all-tables t)
4763 ("noalign" org-startup-align-all-tables nil)
4764 ("shrink" org-startup-shrink-all-tables t)
4765 ("inlineimages" org-startup-with-inline-images t)
4766 ("noinlineimages" org-startup-with-inline-images nil)
4767 ("latexpreview" org-startup-with-latex-preview t)
4768 ("nolatexpreview" org-startup-with-latex-preview nil)
4769 ("customtime" org-display-custom-times t)
4770 ("logdone" org-log-done time)
4771 ("lognotedone" org-log-done note)
4772 ("nologdone" org-log-done nil)
4773 ("lognoteclock-out" org-log-note-clock-out t)
4774 ("nolognoteclock-out" org-log-note-clock-out nil)
4775 ("logrepeat" org-log-repeat state)
4776 ("lognoterepeat" org-log-repeat note)
4777 ("logdrawer" org-log-into-drawer t)
4778 ("nologdrawer" org-log-into-drawer nil)
4779 ("logstatesreversed" org-log-states-order-reversed t)
4780 ("nologstatesreversed" org-log-states-order-reversed nil)
4781 ("nologrepeat" org-log-repeat nil)
4782 ("logreschedule" org-log-reschedule time)
4783 ("lognotereschedule" org-log-reschedule note)
4784 ("nologreschedule" org-log-reschedule nil)
4785 ("logredeadline" org-log-redeadline time)
4786 ("lognoteredeadline" org-log-redeadline note)
4787 ("nologredeadline" org-log-redeadline nil)
4788 ("logrefile" org-log-refile time)
4789 ("lognoterefile" org-log-refile note)
4790 ("nologrefile" org-log-refile nil)
4791 ("fninline" org-footnote-define-inline t)
4792 ("nofninline" org-footnote-define-inline nil)
4793 ("fnlocal" org-footnote-section nil)
4794 ("fnauto" org-footnote-auto-label t)
4795 ("fnprompt" org-footnote-auto-label nil)
4796 ("fnconfirm" org-footnote-auto-label confirm)
4797 ("fnplain" org-footnote-auto-label plain)
4798 ("fnadjust" org-footnote-auto-adjust t)
4799 ("nofnadjust" org-footnote-auto-adjust nil)
4800 ("constcgs" constants-unit-system cgs)
4801 ("constSI" constants-unit-system SI)
4802 ("noptag" org-tag-persistent-alist nil)
4803 ("hideblocks" org-hide-block-startup t)
4804 ("nohideblocks" org-hide-block-startup nil)
4805 ("beamer" org-startup-with-beamer-mode t)
4806 ("entitiespretty" org-pretty-entities t)
4807 ("entitiesplain" org-pretty-entities nil))
4808 "Variable associated with STARTUP options for Org.
4809 Each element is a list of three items: the startup options (as written
4810 in the #+STARTUP line), the corresponding variable, and the value to set
4811 this variable to if the option is found. An optional forth element PUSH
4812 means to push this value onto the list in the variable.")
4814 (defcustom org-group-tags t
4815 "When non-nil (the default), use group tags.
4816 This can be turned on/off through `org-toggle-tags-groups'."
4817 :group 'org-tags
4818 :group 'org-startup
4819 :type 'boolean)
4821 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4823 (defun org-toggle-tags-groups ()
4824 "Toggle support for group tags.
4825 Support for group tags is controlled by the option
4826 `org-group-tags', which is non-nil by default."
4827 (interactive)
4828 (setq org-group-tags (not org-group-tags))
4829 (cond ((and (derived-mode-p 'org-agenda-mode)
4830 org-group-tags)
4831 (org-agenda-redo))
4832 ((derived-mode-p 'org-mode)
4833 (let ((org-inhibit-startup t)) (org-mode))))
4834 (message "Groups tags support has been turned %s"
4835 (if org-group-tags "on" "off")))
4837 (defun org-tag-add-to-alist (alist1 alist2)
4838 "Append ALIST1 elements to ALIST2 if they are not there yet."
4839 (cond
4840 ((null alist2) alist1)
4841 ((null alist1) alist2)
4842 (t (let ((alist2-cars (mapcar (lambda (x) (car-safe x)) alist2))
4843 to-add)
4844 (dolist (i alist1)
4845 (unless (member (car-safe i) alist2-cars)
4846 (push i to-add)))
4847 (append to-add alist2)))))
4849 (defun org-set-regexps-and-options (&optional tags-only)
4850 "Precompute regular expressions used in the current buffer.
4851 When optional argument TAGS-ONLY is non-nil, only compute tags
4852 related expressions."
4853 (when (derived-mode-p 'org-mode)
4854 (let ((alist (org--setup-collect-keywords
4855 (org-make-options-regexp
4856 (append '("FILETAGS" "TAGS" "SETUPFILE")
4857 (and (not tags-only)
4858 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4859 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4860 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4861 ;; Startup options. Get this early since it does change
4862 ;; behavior for other options (e.g., tags).
4863 (let ((startup (cdr (assq 'startup alist))))
4864 (dolist (option startup)
4865 (let ((entry (assoc-string option org-startup-options t)))
4866 (when entry
4867 (let ((var (nth 1 entry))
4868 (val (nth 2 entry)))
4869 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4870 (unless (listp (symbol-value var))
4871 (set (make-local-variable var) nil))
4872 (add-to-list var val)))))))
4873 (setq-local org-file-tags
4874 (mapcar #'org-add-prop-inherited
4875 (cdr (assq 'filetags alist))))
4876 (setq org-current-tag-alist
4877 (org-tag-add-to-alist
4878 org-tag-persistent-alist
4879 (let ((tags (cdr (assq 'tags alist))))
4880 (if tags (org-tag-string-to-alist tags)
4881 org-tag-alist))))
4882 (setq org-tag-groups-alist
4883 (org-tag-alist-to-groups org-current-tag-alist))
4884 (unless tags-only
4885 ;; File properties.
4886 (setq-local org-file-properties (cdr (assq 'property alist)))
4887 ;; Archive location.
4888 (let ((archive (cdr (assq 'archive alist))))
4889 (when archive (setq-local org-archive-location archive)))
4890 ;; Category.
4891 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4892 (when cat
4893 (setq-local org-category (intern cat))
4894 (setq-local org-file-properties
4895 (org--update-property-plist
4896 "CATEGORY" cat org-file-properties))))
4897 ;; Columns.
4898 (let ((column (cdr (assq 'columns alist))))
4899 (when column (setq-local org-columns-default-format column)))
4900 ;; Constants.
4901 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4902 ;; Link abbreviations.
4903 (let ((links (cdr (assq 'link alist))))
4904 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4905 ;; Priorities.
4906 (let ((priorities (cdr (assq 'priorities alist))))
4907 (when priorities
4908 (setq-local org-highest-priority (nth 0 priorities))
4909 (setq-local org-lowest-priority (nth 1 priorities))
4910 (setq-local org-default-priority (nth 2 priorities))))
4911 ;; Scripts.
4912 (let ((scripts (assq 'scripts alist)))
4913 (when scripts
4914 (setq-local org-use-sub-superscripts (cdr scripts))))
4915 ;; TODO keywords.
4916 (setq-local org-todo-kwd-alist nil)
4917 (setq-local org-todo-key-alist nil)
4918 (setq-local org-todo-key-trigger nil)
4919 (setq-local org-todo-keywords-1 nil)
4920 (setq-local org-done-keywords nil)
4921 (setq-local org-todo-heads nil)
4922 (setq-local org-todo-sets nil)
4923 (setq-local org-todo-log-states nil)
4924 (let ((todo-sequences
4925 (or (nreverse (cdr (assq 'todo alist)))
4926 (let ((d (default-value 'org-todo-keywords)))
4927 (if (not (stringp (car d))) d
4928 ;; XXX: Backward compatibility code.
4929 (list (cons org-todo-interpretation d)))))))
4930 (dolist (sequence todo-sequences)
4931 (let* ((sequence (or (run-hook-with-args-until-success
4932 'org-todo-setup-filter-hook sequence)
4933 sequence))
4934 (sequence-type (car sequence))
4935 (keywords (cdr sequence))
4936 (sep (member "|" keywords))
4937 names alist)
4938 (dolist (k (remove "|" keywords))
4939 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4941 (error "Invalid TODO keyword %s" k))
4942 (let ((name (match-string 1 k))
4943 (key (match-string 2 k))
4944 (log (org-extract-log-state-settings k)))
4945 (push name names)
4946 (push (cons name (and key (string-to-char key))) alist)
4947 (when log (push log org-todo-log-states))))
4948 (let* ((names (nreverse names))
4949 (done (if sep (org-remove-keyword-keys (cdr sep))
4950 (last names)))
4951 (head (car names))
4952 (tail (list sequence-type head (car done) (org-last done))))
4953 (add-to-list 'org-todo-heads head 'append)
4954 (push names org-todo-sets)
4955 (setq org-done-keywords (append org-done-keywords done nil))
4956 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4957 (setq org-todo-key-alist
4958 (append org-todo-key-alist
4959 (and alist
4960 (append '((:startgroup))
4961 (nreverse alist)
4962 '((:endgroup))))))
4963 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4964 (setq org-todo-sets (nreverse org-todo-sets)
4965 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4966 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4967 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4968 ;; Compute the regular expressions and other local variables.
4969 ;; Using `org-outline-regexp-bol' would complicate them much,
4970 ;; because of the fixed white space at the end of that string.
4971 (unless org-done-keywords
4972 (setq org-done-keywords
4973 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4974 (setq org-not-done-keywords
4975 (org-delete-all org-done-keywords
4976 (copy-sequence org-todo-keywords-1))
4977 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4978 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4979 org-not-done-heading-regexp
4980 (format org-heading-keyword-regexp-format org-not-done-regexp)
4981 org-todo-line-regexp
4982 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4983 org-complex-heading-regexp
4984 (concat "^\\(\\*+\\)"
4985 "\\(?: +" org-todo-regexp "\\)?"
4986 "\\(?: +\\(\\[#.\\]\\)\\)?"
4987 "\\(?: +\\(.*?\\)\\)??"
4988 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4989 "[ \t]*$")
4990 org-complex-heading-regexp-format
4991 (concat "^\\(\\*+\\)"
4992 "\\(?: +" org-todo-regexp "\\)?"
4993 "\\(?: +\\(\\[#.\\]\\)\\)?"
4994 "\\(?: +"
4995 ;; Stats cookies can be stuck to body.
4996 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4997 "\\(%s\\)"
4998 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4999 "\\)"
5000 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5001 "[ \t]*$")
5002 org-todo-line-tags-regexp
5003 (concat "^\\(\\*+\\)"
5004 "\\(?: +" org-todo-regexp "\\)?"
5005 "\\(?: +\\(.*?\\)\\)??"
5006 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5007 "[ \t]*$"))
5008 (org-compute-latex-and-related-regexp)))))
5010 (defun org--setup-collect-keywords (regexp &optional files alist)
5011 "Return setup keywords values as an alist.
5013 REGEXP matches a subset of setup keywords. FILES is a list of
5014 file names already visited. It is used to avoid circular setup
5015 files. ALIST, when non-nil, is the alist computed so far.
5017 Return value contains the following keys: `archive', `category',
5018 `columns', `constants', `filetags', `link', `priorities',
5019 `property', `scripts', `startup', `tags' and `todo'."
5020 (org-with-wide-buffer
5021 (goto-char (point-min))
5022 (let ((case-fold-search t))
5023 (while (re-search-forward regexp nil t)
5024 (let ((element (org-element-at-point)))
5025 (when (eq (org-element-type element) 'keyword)
5026 (let ((key (org-element-property :key element))
5027 (value (org-element-property :value element)))
5028 (cond
5029 ((equal key "ARCHIVE")
5030 (when (org-string-nw-p value)
5031 (push (cons 'archive value) alist)))
5032 ((equal key "CATEGORY") (push (cons 'category value) alist))
5033 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5034 ((equal key "CONSTANTS")
5035 (let* ((constants (assq 'constants alist))
5036 (store (cdr constants)))
5037 (dolist (pair (split-string value))
5038 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5039 pair)
5040 (let* ((name (match-string 1 pair))
5041 (value (match-string 2 pair))
5042 (old (assoc name store)))
5043 (if old (setcdr old value)
5044 (push (cons name value) store)))))
5045 (if constants (setcdr constants store)
5046 (push (cons 'constants store) alist))))
5047 ((equal key "FILETAGS")
5048 (when (org-string-nw-p value)
5049 (let ((old (assq 'filetags alist))
5050 (new (apply #'nconc
5051 (mapcar (lambda (x) (org-split-string x ":"))
5052 (split-string value)))))
5053 (if old (setcdr old (append new (cdr old)))
5054 (push (cons 'filetags new) alist)))))
5055 ((equal key "LINK")
5056 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5057 (let ((links (assq 'link alist))
5058 (pair (cons (match-string-no-properties 1 value)
5059 (match-string-no-properties 2 value))))
5060 (if links (push pair (cdr links))
5061 (push (list 'link pair) alist)))))
5062 ((equal key "OPTIONS")
5063 (when (and (org-string-nw-p value)
5064 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5065 (push (cons 'scripts (read (match-string 1 value))) alist)))
5066 ((equal key "PRIORITIES")
5067 (push (cons 'priorities
5068 (let ((prio (split-string value)))
5069 (if (< (length prio) 3) '(?A ?C ?B)
5070 (mapcar #'string-to-char prio))))
5071 alist))
5072 ((equal key "PROPERTY")
5073 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5074 (let* ((property (assq 'property alist))
5075 (value (org--update-property-plist
5076 (match-string-no-properties 1 value)
5077 (match-string-no-properties 2 value)
5078 (cdr property))))
5079 (if property (setcdr property value)
5080 (push (cons 'property value) alist)))))
5081 ((equal key "STARTUP")
5082 (let ((startup (assq 'startup alist)))
5083 (if startup
5084 (setcdr startup
5085 (append (cdr startup) (split-string value)))
5086 (push (cons 'startup (split-string value)) alist))))
5087 ((equal key "TAGS")
5088 (let ((tag-cell (assq 'tags alist)))
5089 (if tag-cell
5090 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5091 (push (cons 'tags value) alist))))
5092 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5093 (let ((todo (assq 'todo alist))
5094 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5095 (split-string value))))
5096 (if todo (push value (cdr todo))
5097 (push (list 'todo value) alist))))
5098 ((equal key "SETUPFILE")
5099 (unless buffer-read-only ; Do not check in Gnus messages.
5100 (let ((f (and (org-string-nw-p value)
5101 (expand-file-name
5102 (org-unbracket-string "\"" "\"" value)))))
5103 (when (and f (file-readable-p f) (not (member f files)))
5104 (with-temp-buffer
5105 (setq default-directory (file-name-directory f))
5106 (insert-file-contents f)
5107 (setq alist
5108 ;; Fake Org mode to benefit from cache
5109 ;; without recurring needlessly.
5110 (let ((major-mode 'org-mode))
5111 (org--setup-collect-keywords
5112 regexp (cons f files) alist)))))))))))))))
5113 alist)
5115 (defun org-tag-string-to-alist (s)
5116 "Return tag alist associated to string S.
5117 S is a value for TAGS keyword or produced with
5118 `org-tag-alist-to-string'. Return value is an alist suitable for
5119 `org-tag-alist' or `org-tag-persistent-alist'."
5120 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5121 (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
5122 "\\(?:(\\(.\\))\\)?\\'"))
5123 alist group-flag)
5124 (dolist (tokens lines (cdr (nreverse alist)))
5125 (push '(:newline) alist)
5126 (while tokens
5127 (let ((token (pop tokens)))
5128 (pcase token
5129 ("{"
5130 (push '(:startgroup) alist)
5131 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5132 ("}"
5133 (push '(:endgroup) alist)
5134 (setq group-flag nil))
5135 ("["
5136 (push '(:startgrouptag) alist)
5137 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5138 ("]"
5139 (push '(:endgrouptag) alist)
5140 (setq group-flag nil))
5141 (":"
5142 (push '(:grouptags) alist))
5143 ((guard (string-match tag-re token))
5144 (let ((tag (match-string 1 token))
5145 (key (and (match-beginning 2)
5146 (string-to-char (match-string 2 token)))))
5147 ;; Push all tags in groups, no matter if they already
5148 ;; appear somewhere else in the list.
5149 (when (or group-flag (not (assoc tag alist)))
5150 (push (cons tag key) alist))))))))))
5152 (defun org-tag-alist-to-string (alist &optional skip-key)
5153 "Return tag string associated to ALIST.
5155 ALIST is an alist, as defined in `org-tag-alist' or
5156 `org-tag-persistent-alist', or produced with
5157 `org-tag-string-to-alist'.
5159 Return value is a string suitable as a value for \"TAGS\"
5160 keyword.
5162 When optional argument SKIP-KEY is non-nil, skip selection keys
5163 next to tags."
5164 (mapconcat (lambda (token)
5165 (pcase token
5166 (`(:startgroup) "{")
5167 (`(:endgroup) "}")
5168 (`(:startgrouptag) "[")
5169 (`(:endgrouptag) "]")
5170 (`(:grouptags) ":")
5171 (`(:newline) "\\n")
5172 ((and
5173 (guard (not skip-key))
5174 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5175 (format "%s(%c)" tag key))
5176 (`(,(and tag (pred stringp)) . ,_) tag)
5177 (_ (user-error "Invalid tag token: %S" token))))
5178 alist
5179 " "))
5181 (defun org-tag-alist-to-groups (alist)
5182 "Return group alist from tag ALIST.
5183 ALIST is an alist, as defined in `org-tag-alist' or
5184 `org-tag-persistent-alist', or produced with
5185 `org-tag-string-to-alist'. Return value is an alist following
5186 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5187 a string, summarizing TAGS, as a list of strings."
5188 (let (groups group-status current-group)
5189 (dolist (token alist (nreverse groups))
5190 (pcase token
5191 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5192 (`(,(or :endgroup :endgrouptag))
5193 (when (eq group-status 'append)
5194 (push (nreverse current-group) groups))
5195 (setq group-status nil current-group nil))
5196 (`(:grouptags) (setq group-status 'append))
5197 ((and `(,tag . ,_) (guard group-status))
5198 (if (eq group-status 'append) (push tag current-group)
5199 (setq current-group (list tag))))
5200 (_ nil)))))
5202 (defvar org--file-cache (make-hash-table :test #'equal)
5203 "Hash table to store contents of files referenced via a URL.
5204 This is the cache of file URLs read using `org-file-contents'.")
5206 (defun org-reset-file-cache ()
5207 "Reset the cache of files downloaded by `org-file-contents'."
5208 (clrhash org--file-cache))
5210 (defun org-file-url-p (file)
5211 "Non-nil if FILE is a URL."
5212 (require 'ffap)
5213 (string-match-p ffap-url-regexp file))
5215 (defun org-file-contents (file &optional noerror nocache)
5216 "Return the contents of FILE, as a string.
5218 FILE can be a file name or URL.
5220 If FILE is a URL, download the contents. If the URL contents are
5221 already cached in the `org--file-cache' hash table, the download step
5222 is skipped.
5224 If NOERROR is non-nil, ignore the error when unable to read the FILE
5225 from file or URL.
5227 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5228 is available. This option applies only if FILE is a URL."
5229 (let* ((is-url (org-file-url-p file))
5230 (cache (and is-url
5231 (not nocache)
5232 (gethash file org--file-cache))))
5233 (cond
5234 (cache)
5235 (is-url
5236 (with-current-buffer (url-retrieve-synchronously file)
5237 (goto-char (point-min))
5238 ;; Move point to after the url-retrieve header.
5239 (search-forward "\n\n" nil :move)
5240 ;; Search for the success code only in the url-retrieve header.
5241 (if (save-excursion
5242 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5243 ;; Update the cache `org--file-cache' and return contents.
5244 (puthash file
5245 (buffer-substring-no-properties (point) (point-max))
5246 org--file-cache)
5247 (funcall (if noerror #'message #'user-error)
5248 "Unable to fetch file from %S"
5249 file))))
5251 (with-temp-buffer
5252 (condition-case nil
5253 (progn
5254 (insert-file-contents file)
5255 (buffer-string))
5256 (file-error
5257 (funcall (if noerror #'message #'user-error)
5258 "Unable to read file %S"
5259 file))))))))
5261 (defun org-extract-log-state-settings (x)
5262 "Extract the log state setting from a TODO keyword string.
5263 This will extract info from a string like \"WAIT(w@/!)\"."
5264 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5265 (let ((kw (match-string 1 x))
5266 (log1 (and (match-end 3) (match-string 3 x)))
5267 (log2 (and (match-end 4) (match-string 4 x))))
5268 (and (or log1 log2)
5269 (list kw
5270 (and log1 (if (equal log1 "!") 'time 'note))
5271 (and log2 (if (equal log2 "!") 'time 'note)))))))
5273 (defun org-remove-keyword-keys (list)
5274 "Remove a pair of parenthesis at the end of each string in LIST."
5275 (mapcar (lambda (x)
5276 (if (string-match "(.*)$" x)
5277 (substring x 0 (match-beginning 0))
5279 list))
5281 (defun org-assign-fast-keys (alist)
5282 "Assign fast keys to a keyword-key alist.
5283 Respect keys that are already there."
5284 (let (new e (alt ?0))
5285 (while (setq e (pop alist))
5286 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5287 (cdr e)) ;; Key already assigned.
5288 (push e new)
5289 (let ((clist (string-to-list (downcase (car e))))
5290 (used (append new alist)))
5291 (when (= (car clist) ?@)
5292 (pop clist))
5293 (while (and clist (rassoc (car clist) used))
5294 (pop clist))
5295 (unless clist
5296 (while (rassoc alt used)
5297 (cl-incf alt)))
5298 (push (cons (car e) (or (car clist) alt)) new))))
5299 (nreverse new)))
5301 ;;; Some variables used in various places
5303 (defvar org-window-configuration nil
5304 "Used in various places to store a window configuration.")
5305 (defvar org-selected-window nil
5306 "Used in various places to store a window configuration.")
5307 (defvar org-finish-function nil
5308 "Function to be called when `C-c C-c' is used.
5309 This is for getting out of special buffers like capture.")
5310 (defvar org-last-state)
5312 ;; Defined somewhere in this file, but used before definition.
5313 (defvar org-entities) ;; defined in org-entities.el
5314 (defvar org-struct-menu)
5315 (defvar org-org-menu)
5316 (defvar org-tbl-menu)
5318 ;;;; Define the Org mode
5320 ;; We use a before-change function to check if a table might need
5321 ;; an update.
5322 (defvar org-table-may-need-update t
5323 "Indicates that a table might need an update.
5324 This variable is set by `org-before-change-function'.
5325 `org-table-align' sets it back to nil.")
5326 (defun org-before-change-function (_beg _end)
5327 "Every change indicates that a table might need an update."
5328 (setq org-table-may-need-update t))
5329 (defvar org-mode-map)
5330 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5331 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5332 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5333 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5334 (defvar org-table-buffer-is-an nil)
5336 (defvar bidi-paragraph-direction)
5337 (defvar buffer-face-mode-face)
5339 (require 'outline)
5341 ;; Other stuff we need.
5342 (require 'time-date)
5343 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5344 (require 'easymenu)
5345 (autoload 'easy-menu-add "easymenu")
5346 (require 'overlay)
5348 ;; (require 'org-macs) moved higher up in the file before it is first used
5349 (require 'org-entities)
5350 ;; (require 'org-compat) moved higher up in the file before it is first used
5351 (require 'org-faces)
5352 (require 'org-list)
5353 (require 'org-pcomplete)
5354 (require 'org-src)
5355 (require 'org-footnote)
5356 (require 'org-macro)
5358 ;; babel
5359 (require 'ob)
5361 ;;;###autoload
5362 (define-derived-mode org-mode outline-mode "Org"
5363 "Outline-based notes management and organizer, alias
5364 \"Carsten's outline-mode for keeping track of everything.\"
5366 Org mode develops organizational tasks around a NOTES file which
5367 contains information about projects as plain text. Org mode is
5368 implemented on top of Outline mode, which is ideal to keep the content
5369 of large files well structured. It supports ToDo items, deadlines and
5370 time stamps, which magically appear in the diary listing of the Emacs
5371 calendar. Tables are easily created with a built-in table editor.
5372 Plain text URL-like links connect to websites, emails (VM), Usenet
5373 messages (Gnus), BBDB entries, and any files related to the project.
5374 For printing and sharing of notes, an Org file (or a part of it)
5375 can be exported as a structured ASCII or HTML file.
5377 The following commands are available:
5379 \\{org-mode-map}"
5381 ;; Get rid of Outline menus, they are not needed
5382 ;; Need to do this here because define-derived-mode sets up
5383 ;; the keymap so late. Still, it is a waste to call this each time
5384 ;; we switch another buffer into Org mode.
5385 (define-key org-mode-map [menu-bar headings] 'undefined)
5386 (define-key org-mode-map [menu-bar hide] 'undefined)
5387 (define-key org-mode-map [menu-bar show] 'undefined)
5389 (org-load-modules-maybe)
5390 (org-install-agenda-files-menu)
5391 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5392 (add-to-invisibility-spec '(org-hide-block . t))
5393 (add-to-invisibility-spec '(org-hide-drawer . t))
5394 (setq-local outline-regexp org-outline-regexp)
5395 (setq-local outline-level 'org-outline-level)
5396 (setq bidi-paragraph-direction 'left-to-right)
5397 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5398 (unless org-display-table
5399 (setq org-display-table (make-display-table)))
5400 (set-display-table-slot
5401 org-display-table 4
5402 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5403 org-ellipsis)))
5404 (setq buffer-display-table org-display-table))
5405 (org-set-regexps-and-options)
5406 (org-set-font-lock-defaults)
5407 (when (and org-tag-faces (not org-tags-special-faces-re))
5408 ;; tag faces set outside customize.... force initialization.
5409 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5410 ;; Calc embedded
5411 (setq-local calc-embedded-open-mode "# ")
5412 ;; Modify a few syntax entries
5413 (modify-syntax-entry ?@ "w")
5414 (modify-syntax-entry ?\" "\"")
5415 (modify-syntax-entry ?\\ "_")
5416 (modify-syntax-entry ?~ "_")
5417 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5418 ;; Activate before-change-function
5419 (setq-local org-table-may-need-update t)
5420 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5421 ;; Check for running clock before killing a buffer
5422 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5423 ;; Initialize macros templates.
5424 (org-macro-initialize-templates)
5425 ;; Initialize radio targets.
5426 (org-update-radio-target-regexp)
5427 ;; Indentation.
5428 (setq-local indent-line-function 'org-indent-line)
5429 (setq-local indent-region-function 'org-indent-region)
5430 ;; Filling and auto-filling.
5431 (org-setup-filling)
5432 ;; Comments.
5433 (org-setup-comments-handling)
5434 ;; Initialize cache.
5435 (org-element-cache-reset)
5436 ;; Beginning/end of defun
5437 (setq-local beginning-of-defun-function 'org-backward-element)
5438 (setq-local end-of-defun-function
5439 (lambda ()
5440 (if (not (org-at-heading-p))
5441 (org-forward-element)
5442 (org-forward-element)
5443 (forward-char -1))))
5444 ;; Next error for sparse trees
5445 (setq-local next-error-function 'org-occur-next-match)
5446 ;; Make sure dependence stuff works reliably, even for users who set it
5447 ;; too late :-(
5448 (if org-enforce-todo-dependencies
5449 (add-hook 'org-blocker-hook
5450 'org-block-todo-from-children-or-siblings-or-parent)
5451 (remove-hook 'org-blocker-hook
5452 'org-block-todo-from-children-or-siblings-or-parent))
5453 (if org-enforce-todo-checkbox-dependencies
5454 (add-hook 'org-blocker-hook
5455 'org-block-todo-from-checkboxes)
5456 (remove-hook 'org-blocker-hook
5457 'org-block-todo-from-checkboxes))
5459 ;; Align options lines
5460 (setq-local
5461 align-mode-rules-list
5462 '((org-in-buffer-settings
5463 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5464 (modes . '(org-mode)))))
5466 ;; Imenu
5467 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5469 ;; Make isearch reveal context
5470 (setq-local outline-isearch-open-invisible-function
5471 (lambda (&rest _) (org-show-context 'isearch)))
5473 ;; Setup the pcomplete hooks
5474 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5475 (setq-local pcomplete-command-name-function 'org-command-at-point)
5476 (setq-local pcomplete-default-completion-function 'ignore)
5477 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5478 (setq-local pcomplete-termination-string "")
5479 (setq-local buffer-face-mode-face 'org-default)
5481 ;; If empty file that did not turn on Org mode automatically, make
5482 ;; it to.
5483 (when (and org-insert-mode-line-in-empty-file
5484 (called-interactively-p 'any)
5485 (= (point-min) (point-max)))
5486 (insert "# -*- mode: org -*-\n\n"))
5487 (unless org-inhibit-startup
5488 (org-unmodified
5489 (when org-startup-with-beamer-mode (org-beamer-mode))
5490 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5491 (org-table-map-tables
5492 (cond ((and org-startup-align-all-tables
5493 org-startup-shrink-all-tables)
5494 (lambda () (org-table-align) (org-table-shrink)))
5495 (org-startup-align-all-tables #'org-table-align)
5496 (t #'org-table-shrink))
5498 (when org-startup-with-inline-images (org-display-inline-images))
5499 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5500 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5501 (when org-startup-truncated (setq truncate-lines t))
5502 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5503 (org-refresh-effort-properties)))
5504 ;; Try to set `org-hide' face correctly.
5505 (let ((foreground (org-find-invisible-foreground)))
5506 (when foreground
5507 (set-face-foreground 'org-hide foreground))))
5509 ;; Update `customize-package-emacs-version-alist'
5510 (add-to-list 'customize-package-emacs-version-alist
5511 '(Org ("8.0" . "24.4")
5512 ("8.1" . "24.4")
5513 ("8.2" . "24.4")
5514 ("8.2.7" . "24.4")
5515 ("8.3" . "26.1")
5516 ("9.0" . "26.1")
5517 ("9.1" . "26.1")
5518 ("9.2" . "27.1")))
5520 (defvar org-mode-transpose-word-syntax-table
5521 (let ((st (make-syntax-table text-mode-syntax-table)))
5522 (dolist (c org-emphasis-alist st)
5523 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5525 (when (fboundp 'abbrev-table-put)
5526 (abbrev-table-put org-mode-abbrev-table
5527 :parents (list text-mode-abbrev-table)))
5529 (defun org-find-invisible-foreground ()
5530 (let ((candidates (remove
5531 "unspecified-bg"
5532 (nconc
5533 (list (face-background 'default)
5534 (face-background 'org-default))
5535 (mapcar
5536 (lambda (alist)
5537 (when (boundp alist)
5538 (cdr (assq 'background-color (symbol-value alist)))))
5539 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5540 (list (face-foreground 'org-hide))))))
5541 (car (remove nil candidates))))
5543 (defun org-current-time (&optional rounding-minutes past)
5544 "Current time, possibly rounded to ROUNDING-MINUTES.
5545 When ROUNDING-MINUTES is not an integer, fall back on the car of
5546 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5547 the rounding returns a past time."
5548 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5549 (car org-time-stamp-rounding-minutes)))
5550 (time (decode-time)) res)
5551 (if (< r 1)
5552 (current-time)
5553 (setq res
5554 (apply 'encode-time
5555 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5556 (nthcdr 2 time))))
5557 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5558 (seconds-to-time (- (float-time res) (* r 60)))
5559 res))))
5561 (defun org-today ()
5562 "Return today date, considering `org-extend-today-until'."
5563 (time-to-days
5564 (time-subtract (current-time)
5565 (list 0 (* 3600 org-extend-today-until) 0))))
5567 ;;;; Font-Lock stuff, including the activators
5569 (defvar org-mouse-map (make-sparse-keymap))
5570 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5571 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5572 (when org-mouse-1-follows-link
5573 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5574 (when org-tab-follows-link
5575 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5576 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5578 (require 'font-lock)
5580 (defconst org-non-link-chars "]\t\n\r<>")
5581 (defvar org-link-types-re nil
5582 "Matches a link that has a url-like prefix like \"http:\"")
5583 (defvar org-link-re-with-space nil
5584 "Matches a link with spaces, optional angular brackets around it.")
5585 (defvar org-link-re-with-space2 nil
5586 "Matches a link with spaces, optional angular brackets around it.")
5587 (defvar org-link-re-with-space3 nil
5588 "Matches a link with spaces, only for internal part in bracket links.")
5589 (defvar org-angle-link-re nil
5590 "Matches link with angular brackets, spaces are allowed.")
5591 (defvar org-plain-link-re nil
5592 "Matches plain link, without spaces.")
5593 (defvar org-bracket-link-regexp nil
5594 "Matches a link in double brackets.")
5595 (defvar org-bracket-link-analytic-regexp nil
5596 "Regular expression used to analyze links.
5597 Here is what the match groups contain after a match:
5598 1: http:
5599 2: http
5600 3: path
5601 4: [desc]
5602 5: desc")
5603 (defvar org-bracket-link-analytic-regexp++ nil
5604 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5605 (defvar org-any-link-re nil
5606 "Regular expression matching any link.")
5608 (defconst org-match-sexp-depth 3
5609 "Number of stacked braces for sub/superscript matching.")
5611 (defun org-create-multibrace-regexp (left right n)
5612 "Create a regular expression which will match a balanced sexp.
5613 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5614 as single character strings.
5615 The regexp returned will match the entire expression including the
5616 delimiters. It will also define a single group which contains the
5617 match except for the outermost delimiters. The maximum depth of
5618 stacked delimiters is N. Escaping delimiters is not possible."
5619 (let* ((nothing (concat "[^" left right "]*?"))
5620 (or "\\|")
5621 (re nothing)
5622 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5623 (while (> n 1)
5624 (setq n (1- n)
5625 re (concat re or next)
5626 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5627 (concat left "\\(" re "\\)" right)))
5629 (defconst org-match-substring-regexp
5630 (concat
5631 "\\(\\S-\\)\\([_^]\\)\\("
5632 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5633 "\\|"
5634 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5635 "\\|"
5636 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5637 "The regular expression matching a sub- or superscript.")
5639 (defconst org-match-substring-with-braces-regexp
5640 (concat
5641 "\\(\\S-\\)\\([_^]\\)"
5642 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5643 "The regular expression matching a sub- or superscript, forcing braces.")
5645 (defun org-make-link-regexps ()
5646 "Update the link regular expressions.
5647 This should be called after the variable `org-link-parameters' has changed."
5648 (let ((types-re (regexp-opt (org-link-types) t)))
5649 (setq org-link-types-re
5650 (concat "\\`" types-re ":")
5651 org-link-re-with-space
5652 (concat "<?" types-re ":"
5653 "\\([^" org-non-link-chars " ]"
5654 "[^" org-non-link-chars "]*"
5655 "[^" org-non-link-chars " ]\\)>?")
5656 org-link-re-with-space2
5657 (concat "<?" types-re ":"
5658 "\\([^" org-non-link-chars " ]"
5659 "[^\t\n\r]*"
5660 "[^" org-non-link-chars " ]\\)>?")
5661 org-link-re-with-space3
5662 (concat "<?" types-re ":"
5663 "\\([^" org-non-link-chars " ]"
5664 "[^\t\n\r]*\\)")
5665 org-angle-link-re
5666 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5667 types-re)
5668 org-plain-link-re
5669 (concat
5670 "\\<" types-re ":"
5671 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5672 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5673 org-bracket-link-regexp
5674 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5675 org-bracket-link-analytic-regexp
5676 (concat
5677 "\\[\\["
5678 "\\(" types-re ":\\)?"
5679 "\\([^]]+\\)"
5680 "\\]"
5681 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5682 "\\]")
5683 org-bracket-link-analytic-regexp++
5684 (concat
5685 "\\[\\["
5686 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5687 "\\([^]]+\\)"
5688 "\\]"
5689 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5690 "\\]")
5691 org-any-link-re
5692 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5693 org-angle-link-re "\\)\\|\\("
5694 org-plain-link-re "\\)"))))
5696 (org-make-link-regexps)
5698 (defvar org-emph-face nil)
5700 (defun org-do-emphasis-faces (limit)
5701 "Run through the buffer and emphasize strings."
5702 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5703 (car org-emphasis-regexp-components))))
5704 (catch :exit
5705 (while (re-search-forward quick-re limit t)
5706 (let* ((marker (match-string 2))
5707 (verbatim? (member marker '("~" "="))))
5708 (when (save-excursion
5709 (goto-char (match-beginning 0))
5710 (and
5711 ;; Do not match table hlines.
5712 (not (and (equal marker "+")
5713 (org-match-line
5714 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5715 ;; Do not match headline stars. Do not consider
5716 ;; stars of a headline as closing marker for bold
5717 ;; markup either.
5718 (not (and (equal marker "*")
5719 (save-excursion
5720 (forward-char)
5721 (skip-chars-backward "*")
5722 (looking-at-p org-outline-regexp-bol))))
5723 ;; Match full emphasis markup regexp.
5724 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5725 ;; Do not span over paragraph boundaries.
5726 (not (string-match-p org-element-paragraph-separate
5727 (match-string 2)))
5728 ;; Do not span over cells in table rows.
5729 (not (and (save-match-data (org-match-line "[ \t]*|"))
5730 (string-match-p "|" (match-string 4))))))
5731 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5732 (font-lock-prepend-text-property
5733 (match-beginning 2) (match-end 2) 'face face)
5734 (when verbatim?
5735 (org-remove-flyspell-overlays-in
5736 (match-beginning 0) (match-end 0)))
5737 (add-text-properties (match-beginning 2) (match-end 2)
5738 '(font-lock-multiline t org-emphasis t))
5739 (when org-hide-emphasis-markers
5740 (add-text-properties (match-end 4) (match-beginning 5)
5741 '(invisible org-link))
5742 (add-text-properties (match-beginning 3) (match-end 3)
5743 '(invisible org-link)))
5744 (throw :exit t))))))))
5746 (defun org-emphasize (&optional char)
5747 "Insert or change an emphasis, i.e. a font like bold or italic.
5748 If there is an active region, change that region to a new emphasis.
5749 If there is no region, just insert the marker characters and position
5750 the cursor between them.
5751 CHAR should be the marker character. If it is a space, it means to
5752 remove the emphasis of the selected region.
5753 If CHAR is not given (for example in an interactive call) it will be
5754 prompted for."
5755 (interactive)
5756 (let ((erc org-emphasis-regexp-components)
5757 (string "") beg end move s)
5758 (if (org-region-active-p)
5759 (setq beg (region-beginning)
5760 end (region-end)
5761 string (buffer-substring beg end))
5762 (setq move t))
5764 (unless char
5765 (message "Emphasis marker or tag: [%s]"
5766 (mapconcat #'car org-emphasis-alist ""))
5767 (setq char (read-char-exclusive)))
5768 (if (equal char ?\s)
5769 (setq s ""
5770 move nil)
5771 (unless (assoc (char-to-string char) org-emphasis-alist)
5772 (user-error "No such emphasis marker: \"%c\"" char))
5773 (setq s (char-to-string char)))
5774 (while (and (> (length string) 1)
5775 (equal (substring string 0 1) (substring string -1))
5776 (assoc (substring string 0 1) org-emphasis-alist))
5777 (setq string (substring string 1 -1)))
5778 (setq string (concat s string s))
5779 (when beg (delete-region beg end))
5780 (unless (or (bolp)
5781 (string-match (concat "[" (nth 0 erc) "\n]")
5782 (char-to-string (char-before (point)))))
5783 (insert " "))
5784 (unless (or (eobp)
5785 (string-match (concat "[" (nth 1 erc) "\n]")
5786 (char-to-string (char-after (point)))))
5787 (insert " ") (backward-char 1))
5788 (insert string)
5789 (and move (backward-char 1))))
5791 (defconst org-nonsticky-props
5792 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5794 (defsubst org-rear-nonsticky-at (pos)
5795 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5797 (defun org-activate-links (limit)
5798 "Add link properties to links.
5799 This includes angle, plain, and bracket links."
5800 (catch :exit
5801 (while (re-search-forward org-any-link-re limit t)
5802 (let* ((start (match-beginning 0))
5803 (end (match-end 0))
5804 (style (cond ((eq ?< (char-after start)) 'angle)
5805 ((eq ?\[ (char-after (1+ start))) 'bracket)
5806 (t 'plain))))
5807 (when (and (memq style org-highlight-links)
5808 ;; Do not confuse plain links with tags.
5809 (not (and (eq style 'plain)
5810 (let ((face (get-text-property
5811 (max (1- start) (point-min)) 'face)))
5812 (if (consp face) (memq 'org-tag face)
5813 (eq 'org-tag face))))))
5814 (let* ((link-object (save-excursion
5815 (goto-char start)
5816 (save-match-data (org-element-link-parser))))
5817 (link (org-element-property :raw-link link-object))
5818 (type (org-element-property :type link-object))
5819 (path (org-element-property :path link-object))
5820 (properties ;for link's visible part
5821 (list
5822 'face (pcase (org-link-get-parameter type :face)
5823 ((and (pred functionp) face) (funcall face path))
5824 ((and (pred facep) face) face)
5825 ((and (pred consp) face) face) ;anonymous
5826 (_ 'org-link))
5827 'mouse-face (or (org-link-get-parameter type :mouse-face)
5828 'highlight)
5829 'keymap (or (org-link-get-parameter type :keymap)
5830 org-mouse-map)
5831 'help-echo (pcase (org-link-get-parameter type :help-echo)
5832 ((and (pred stringp) echo) echo)
5833 ((and (pred functionp) echo) echo)
5834 (_ (concat "LINK: " link)))
5835 'htmlize-link (pcase (org-link-get-parameter type
5836 :htmlize-link)
5837 ((and (pred functionp) f) (funcall f))
5838 (_ `(:uri ,link)))
5839 'font-lock-multiline t)))
5840 (org-remove-flyspell-overlays-in start end)
5841 (org-rear-nonsticky-at end)
5842 (if (not (eq 'bracket style))
5843 (add-text-properties start end properties)
5844 ;; Handle invisible parts in bracket links.
5845 (remove-text-properties start end '(invisible nil))
5846 (let ((hidden
5847 (append `(invisible
5848 ,(or (org-link-get-parameter type :display)
5849 'org-link))
5850 properties))
5851 (visible-start (or (match-beginning 4) (match-beginning 2)))
5852 (visible-end (or (match-end 4) (match-end 2))))
5853 (add-text-properties start visible-start hidden)
5854 (add-text-properties visible-start visible-end properties)
5855 (add-text-properties visible-end end hidden)
5856 (org-rear-nonsticky-at visible-start)
5857 (org-rear-nonsticky-at visible-end)))
5858 (let ((f (org-link-get-parameter type :activate-func)))
5859 (when (functionp f)
5860 (funcall f start end path (eq style 'bracket))))
5861 (throw :exit t))))) ;signal success
5862 nil))
5864 (defun org-activate-code (limit)
5865 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5866 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5867 (remove-text-properties (match-beginning 0) (match-end 0)
5868 '(display t invisible t intangible t))
5871 (defcustom org-src-fontify-natively t
5872 "When non-nil, fontify code in code blocks.
5873 See also the `org-block' face."
5874 :type 'boolean
5875 :version "26.1"
5876 :package-version '(Org . "8.3")
5877 :group 'org-appearance
5878 :group 'org-babel)
5880 (defcustom org-allow-promoting-top-level-subtree nil
5881 "When non-nil, allow promoting a top level subtree.
5882 The leading star of the top level headline will be replaced
5883 by a #."
5884 :type 'boolean
5885 :version "24.1"
5886 :group 'org-appearance)
5888 (defun org-fontify-meta-lines-and-blocks (limit)
5889 (condition-case nil
5890 (org-fontify-meta-lines-and-blocks-1 limit)
5891 (error (message "Org mode fontification error in %S at %d"
5892 (current-buffer)
5893 (line-number-at-pos)))))
5895 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5896 "Fontify #+ lines and blocks."
5897 (let ((case-fold-search t))
5898 (when (re-search-forward
5899 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5900 limit t)
5901 (let ((beg (match-beginning 0))
5902 (block-start (match-end 0))
5903 (block-end nil)
5904 (lang (match-string 7))
5905 (beg1 (line-beginning-position 2))
5906 (dc1 (downcase (match-string 2)))
5907 (dc3 (downcase (match-string 3)))
5908 end end1 quoting block-type)
5909 (cond
5910 ((and (match-end 4) (equal dc3 "+begin"))
5911 ;; Truly a block
5912 (setq block-type (downcase (match-string 5))
5913 quoting (member block-type org-protecting-blocks))
5914 (when (re-search-forward
5915 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5916 nil t) ;; on purpose, we look further than LIMIT
5917 (setq end (min (point-max) (match-end 0))
5918 end1 (min (point-max) (1- (match-beginning 0))))
5919 (setq block-end (match-beginning 0))
5920 (when quoting
5921 (org-remove-flyspell-overlays-in beg1 end1)
5922 (remove-text-properties beg end
5923 '(display t invisible t intangible t)))
5924 (add-text-properties
5925 beg end '(font-lock-fontified t font-lock-multiline t))
5926 (add-text-properties beg beg1 '(face org-meta-line))
5927 (org-remove-flyspell-overlays-in beg beg1)
5928 (add-text-properties ; For end_src
5929 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5930 (org-remove-flyspell-overlays-in end1 end)
5931 (cond
5932 ((and lang (not (string= lang "")) org-src-fontify-natively)
5933 (org-src-font-lock-fontify-block lang block-start block-end)
5934 (add-text-properties beg1 block-end '(src-block t)))
5935 (quoting
5936 (add-text-properties beg1 (min (point-max) (1+ end1))
5937 (list 'face
5938 (list :inherit
5939 (let ((face-name
5940 (intern (format "org-block-%s" lang))))
5941 (append (and (facep face-name) (list face-name))
5942 '(org-block))))))) ; end of source block
5943 ((not org-fontify-quote-and-verse-blocks))
5944 ((string= block-type "quote")
5945 (add-face-text-property
5946 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5947 ((string= block-type "verse")
5948 (add-face-text-property
5949 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5950 (add-text-properties beg beg1 '(face org-block-begin-line))
5951 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5952 '(face org-block-end-line))
5954 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5955 (org-remove-flyspell-overlays-in
5956 (match-beginning 0)
5957 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5958 (add-text-properties
5959 beg (match-end 3)
5960 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5961 '(font-lock-fontified t invisible t)
5962 '(font-lock-fontified t face org-document-info-keyword)))
5963 (add-text-properties
5964 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5965 (if (string-equal dc1 "+title:")
5966 '(font-lock-fontified t face org-document-title)
5967 '(font-lock-fontified t face org-document-info))))
5968 ((string-prefix-p "+caption" dc1)
5969 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5970 (remove-text-properties (match-beginning 0) (match-end 0)
5971 '(display t invisible t intangible t))
5972 ;; Handle short captions.
5973 (save-excursion
5974 (beginning-of-line)
5975 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5976 (add-text-properties (line-beginning-position) (match-end 1)
5977 '(font-lock-fontified t face org-meta-line))
5978 (add-text-properties (match-end 0) (line-end-position)
5979 '(font-lock-fontified t face org-block))
5981 ((member dc3 '(" " ""))
5982 (org-remove-flyspell-overlays-in beg (match-end 0))
5983 (add-text-properties
5984 beg (match-end 0)
5985 '(font-lock-fontified t face font-lock-comment-face)))
5986 (t ;; just any other in-buffer setting, but not indented
5987 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5988 (remove-text-properties (match-beginning 0) (match-end 0)
5989 '(display t invisible t intangible t))
5990 (add-text-properties beg (match-end 0)
5991 '(font-lock-fontified t face org-meta-line))
5992 t))))))
5994 (defun org-fontify-drawers (limit)
5995 "Fontify drawers."
5996 (when (re-search-forward org-drawer-regexp limit t)
5997 (add-text-properties
5998 (match-beginning 0) (match-end 0)
5999 '(font-lock-fontified t face org-special-keyword))
6000 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6003 (defun org-fontify-macros (limit)
6004 "Fontify macros."
6005 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6006 (let ((begin (match-beginning 0))
6007 (opening-end (match-beginning 1)))
6008 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6009 (match-string 1))
6010 (let ((end (match-end 1))
6011 (closing-start (match-beginning 1)))
6012 (add-text-properties
6013 begin end
6014 '(font-lock-multiline t font-lock-fontified t face org-macro))
6015 (org-remove-flyspell-overlays-in begin end)
6016 (when org-hide-macro-markers
6017 (add-text-properties begin opening-end '(invisible t))
6018 (add-text-properties closing-start end '(invisible t)))
6019 t)))))
6021 (defun org-activate-footnote-links (limit)
6022 "Add text properties for footnotes."
6023 (let ((fn (org-footnote-next-reference-or-definition limit)))
6024 (when fn
6025 (let* ((beg (nth 1 fn))
6026 (end (nth 2 fn))
6027 (label (car fn))
6028 (referencep (/= (line-beginning-position) beg)))
6029 (when (and referencep (nth 3 fn))
6030 (save-excursion
6031 (goto-char beg)
6032 (search-forward (or label "fn:"))
6033 (org-remove-flyspell-overlays-in beg (match-end 0))))
6034 (add-text-properties beg end
6035 (list 'mouse-face 'highlight
6036 'keymap org-mouse-map
6037 'help-echo
6038 (if referencep "Footnote reference"
6039 "Footnote definition")
6040 'font-lock-fontified t
6041 'font-lock-multiline t
6042 'face 'org-footnote))))))
6044 (defun org-activate-dates (limit)
6045 "Add text properties for dates."
6046 (when (and (re-search-forward org-tsr-regexp-both limit t)
6047 (not (equal (char-before (match-beginning 0)) 91)))
6048 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6049 (add-text-properties (match-beginning 0) (match-end 0)
6050 (list 'mouse-face 'highlight
6051 'keymap org-mouse-map))
6052 (org-rear-nonsticky-at (match-end 0))
6053 (when org-display-custom-times
6054 ;; If it's a date range, activate custom time for second date.
6055 (when (match-end 3)
6056 (org-display-custom-time (match-beginning 3) (match-end 3)))
6057 (org-display-custom-time (match-beginning 1) (match-end 1)))
6060 (defvar-local org-target-link-regexp nil
6061 "Regular expression matching radio targets in plain text.")
6063 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6064 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6065 border border border))
6066 "Regular expression matching a link target.")
6068 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6069 "Regular expression matching a radio target.")
6071 (defconst org-any-target-regexp
6072 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6073 "Regular expression matching any target.")
6075 (defun org-activate-target-links (limit)
6076 "Add text properties for target matches."
6077 (when org-target-link-regexp
6078 (let ((case-fold-search t))
6079 (when (re-search-forward org-target-link-regexp limit t)
6080 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6081 (add-text-properties (match-beginning 1) (match-end 1)
6082 (list 'mouse-face 'highlight
6083 'keymap org-mouse-map
6084 'help-echo "Radio target link"
6085 'org-linked-text t))
6086 (org-rear-nonsticky-at (match-end 1))
6087 t))))
6089 (defun org-update-radio-target-regexp ()
6090 "Find all radio targets in this file and update the regular expression.
6091 Also refresh fontification if needed."
6092 (interactive)
6093 (let ((old-regexp org-target-link-regexp)
6094 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6095 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6096 (targets
6097 (org-with-wide-buffer
6098 (goto-char (point-min))
6099 (let (rtn)
6100 (while (re-search-forward org-radio-target-regexp nil t)
6101 ;; Make sure point is really within the object.
6102 (backward-char)
6103 (let ((obj (org-element-context)))
6104 (when (eq (org-element-type obj) 'radio-target)
6105 (cl-pushnew (org-element-property :value obj) rtn
6106 :test #'equal))))
6107 rtn))))
6108 (setq org-target-link-regexp
6109 (and targets
6110 (concat before-re
6111 (mapconcat
6112 (lambda (x)
6113 (replace-regexp-in-string
6114 " +" "\\s-+" (regexp-quote x) t t))
6115 targets
6116 "\\|")
6117 after-re)))
6118 (unless (equal old-regexp org-target-link-regexp)
6119 ;; Clean-up cache.
6120 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6121 ((not org-target-link-regexp) old-regexp)
6123 (concat before-re
6124 (mapconcat
6125 (lambda (re)
6126 (substring re (length before-re)
6127 (- (length after-re))))
6128 (list old-regexp org-target-link-regexp)
6129 "\\|")
6130 after-re)))))
6131 (org-with-wide-buffer
6132 (goto-char (point-min))
6133 (while (re-search-forward regexp nil t)
6134 (org-element-cache-refresh (match-beginning 1)))))
6135 ;; Re fontify buffer.
6136 (when (memq 'radio org-highlight-links)
6137 (org-restart-font-lock)))))
6139 (defvar org-latex-and-related-regexp nil
6140 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6142 (defun org-compute-latex-and-related-regexp ()
6143 "Compute regular expression for LaTeX, entities and sub/superscript.
6144 Result depends on variable `org-highlight-latex-and-related'."
6145 (setq-local
6146 org-latex-and-related-regexp
6147 (let* ((re-sub
6148 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6149 ((eq org-use-sub-superscripts '{})
6150 (list org-match-substring-with-braces-regexp))
6151 (org-use-sub-superscripts (list org-match-substring-regexp))))
6152 (re-latex
6153 (when (memq 'latex org-highlight-latex-and-related)
6154 (let ((matchers (plist-get org-format-latex-options :matchers)))
6155 (delq nil
6156 (mapcar (lambda (x)
6157 (and (member (car x) matchers) (nth 1 x)))
6158 org-latex-regexps)))))
6159 (re-entities
6160 (when (memq 'entities org-highlight-latex-and-related)
6161 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6162 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6164 (defun org-do-latex-and-related (limit)
6165 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6166 LIMIT bounds the search for syntax to highlight. Stop at first
6167 highlighted object, if any. Return t if some highlighting was
6168 done, nil otherwise."
6169 (when (org-string-nw-p org-latex-and-related-regexp)
6170 (catch 'found
6171 (while (re-search-forward org-latex-and-related-regexp limit t)
6172 (unless
6173 (cl-some
6174 (lambda (f)
6175 (memq f '(org-code org-verbatim underline org-special-keyword)))
6176 (save-excursion
6177 (goto-char (1+ (match-beginning 0)))
6178 (face-at-point nil t)))
6179 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6180 '(?_ ?^))
6182 0)))
6183 (font-lock-prepend-text-property
6184 (+ offset (match-beginning 0)) (match-end 0)
6185 'face 'org-latex-and-related)
6186 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6187 '(font-lock-multiline t)))
6188 (throw 'found t)))
6189 nil)))
6191 (defun org-restart-font-lock ()
6192 "Restart `font-lock-mode', to force refontification."
6193 (when (and (boundp 'font-lock-mode) font-lock-mode)
6194 (font-lock-mode -1)
6195 (font-lock-mode 1)))
6197 (defun org-activate-tags (limit)
6198 (when (re-search-forward org-tag-line-re limit t)
6199 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6200 (add-text-properties (match-beginning 1) (match-end 1)
6201 (list 'mouse-face 'highlight
6202 'keymap org-mouse-map))
6203 (org-rear-nonsticky-at (match-end 1))
6206 (defun org-outline-level ()
6207 "Compute the outline level of the heading at point.
6209 If this is called at a normal headline, the level is the number
6210 of stars. Use `org-reduced-level' to remove the effect of
6211 `org-odd-levels'. Unlike to `org-current-level', this function
6212 takes into consideration inlinetasks."
6213 (org-with-wide-buffer
6214 (end-of-line)
6215 (if (re-search-backward org-outline-regexp-bol nil t)
6216 (1- (- (match-end 0) (match-beginning 0)))
6217 0)))
6219 (defvar org-font-lock-keywords nil)
6221 (defsubst org-re-property (property &optional literal allow-null value)
6222 "Return a regexp matching a PROPERTY line.
6224 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6225 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6226 non-nil, match properties even without a value.
6228 Match group 3 is set to the value when it exists. If there is no
6229 value and ALLOW-NULL is non-nil, it is set to the empty string.
6231 With optional argument VALUE, match only property lines with
6232 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6233 unless LITERAL is non-nil."
6234 (concat
6235 "^\\(?4:[ \t]*\\)"
6236 (format "\\(?1::\\(?2:%s\\):\\)"
6237 (if literal property (regexp-quote property)))
6238 (cond (value
6239 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6240 (if literal value (regexp-quote value))))
6241 (allow-null
6242 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6244 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6246 (defconst org-property-re
6247 (org-re-property "\\S-+" 'literal t)
6248 "Regular expression matching a property line.
6249 There are four matching groups:
6250 1: :PROPKEY: including the leading and trailing colon,
6251 2: PROPKEY without the leading and trailing colon,
6252 3: PROPVAL without leading or trailing spaces,
6253 4: the indentation of the current line,
6254 5: trailing whitespace.")
6256 (defvar org-font-lock-hook nil
6257 "Functions to be called for special font lock stuff.")
6259 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6261 (defvar org-font-lock-set-keywords-hook nil
6262 "Functions that can manipulate `org-font-lock-extra-keywords'.
6263 This is called after `org-font-lock-extra-keywords' is defined, but before
6264 it is installed to be used by font lock. This can be useful if something
6265 needs to be inserted at a specific position in the font-lock sequence.")
6267 (defun org-font-lock-hook (limit)
6268 "Run `org-font-lock-hook' within LIMIT."
6269 (run-hook-with-args 'org-font-lock-hook limit))
6271 (defun org-set-font-lock-defaults ()
6272 "Set font lock defaults for the current buffer."
6273 (let* ((em org-fontify-emphasized-text)
6274 (lk org-highlight-links)
6275 (org-font-lock-extra-keywords
6276 (list
6277 ;; Call the hook
6278 '(org-font-lock-hook)
6279 ;; Headlines
6280 `(,(if org-fontify-whole-heading-line
6281 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6282 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6283 (1 (org-get-level-face 1))
6284 (2 (org-get-level-face 2))
6285 (3 (org-get-level-face 3)))
6286 ;; Table lines
6287 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6288 (1 'org-table t))
6289 ;; Table internals
6290 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6291 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6292 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6293 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6294 ;; Drawers
6295 '(org-fontify-drawers)
6296 ;; Properties
6297 (list org-property-re
6298 '(1 'org-special-keyword t)
6299 '(3 'org-property-value t))
6300 ;; Link related fontification.
6301 '(org-activate-links)
6302 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6303 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6304 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6305 (when (memq 'footnote lk) '(org-activate-footnote-links))
6306 ;; Targets.
6307 (list org-any-target-regexp '(0 'org-target t))
6308 ;; Diary sexps.
6309 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6310 ;; Macro
6311 '(org-fontify-macros)
6312 ;; TODO keyword
6313 (list (format org-heading-keyword-regexp-format
6314 org-todo-regexp)
6315 '(2 (org-get-todo-face 2) t))
6316 ;; DONE
6317 (if org-fontify-done-headline
6318 (list (format org-heading-keyword-regexp-format
6319 (concat
6320 "\\(?:"
6321 (mapconcat 'regexp-quote org-done-keywords "\\|")
6322 "\\)"))
6323 '(2 'org-headline-done t))
6324 nil)
6325 ;; Priorities
6326 '(org-font-lock-add-priority-faces)
6327 ;; Tags
6328 '(org-font-lock-add-tag-faces)
6329 ;; Tags groups
6330 (when (and org-group-tags org-tag-groups-alist)
6331 (list (concat org-outline-regexp-bol ".+\\(:"
6332 (regexp-opt (mapcar 'car org-tag-groups-alist))
6333 ":\\).*$")
6334 '(1 'org-tag-group prepend)))
6335 ;; Special keywords
6336 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6337 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6338 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6339 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6340 ;; Emphasis
6341 (when em '(org-do-emphasis-faces))
6342 ;; Checkboxes
6343 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6344 1 'org-checkbox prepend)
6345 (when (cdr (assq 'checkbox org-list-automatic-rules))
6346 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6347 (0 (org-get-checkbox-statistics-face) t)))
6348 ;; Description list items
6349 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6350 1 'org-list-dt prepend)
6351 ;; ARCHIVEd headings
6352 (list (concat
6353 org-outline-regexp-bol
6354 "\\(.*:" org-archive-tag ":.*\\)")
6355 '(1 'org-archived prepend))
6356 ;; Specials
6357 '(org-do-latex-and-related)
6358 '(org-fontify-entities)
6359 '(org-raise-scripts)
6360 ;; Code
6361 '(org-activate-code (1 'org-code t))
6362 ;; COMMENT
6363 (list (format
6364 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6365 org-todo-regexp
6366 org-comment-string)
6367 '(9 'org-special-keyword t))
6368 ;; Blocks and meta lines
6369 '(org-fontify-meta-lines-and-blocks))))
6370 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6371 (run-hooks 'org-font-lock-set-keywords-hook)
6372 ;; Now set the full font-lock-keywords
6373 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6374 (setq-local font-lock-defaults
6375 '(org-font-lock-keywords t nil nil backward-paragraph))
6376 (kill-local-variable 'font-lock-keywords)
6377 nil))
6379 (defun org-toggle-pretty-entities ()
6380 "Toggle the composition display of entities as UTF8 characters."
6381 (interactive)
6382 (setq-local org-pretty-entities (not org-pretty-entities))
6383 (org-restart-font-lock)
6384 (if org-pretty-entities
6385 (message "Entities are now displayed as UTF8 characters")
6386 (save-restriction
6387 (widen)
6388 (decompose-region (point-min) (point-max))
6389 (message "Entities are now displayed as plain text"))))
6391 (defvar-local org-custom-properties-overlays nil
6392 "List of overlays used for custom properties.")
6394 (defun org-toggle-custom-properties-visibility ()
6395 "Display or hide properties in `org-custom-properties'."
6396 (interactive)
6397 (if org-custom-properties-overlays
6398 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6399 (setq org-custom-properties-overlays nil))
6400 (when org-custom-properties
6401 (org-with-wide-buffer
6402 (goto-char (point-min))
6403 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6404 (while (re-search-forward regexp nil t)
6405 (let ((end (cdr (save-match-data (org-get-property-block)))))
6406 (when (and end (< (point) end))
6407 ;; Hide first custom property in current drawer.
6408 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6409 (overlay-put o 'invisible t)
6410 (overlay-put o 'org-custom-property t)
6411 (push o org-custom-properties-overlays))
6412 ;; Hide additional custom properties in the same drawer.
6413 (while (re-search-forward regexp end t)
6414 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6415 (overlay-put o 'invisible t)
6416 (overlay-put o 'org-custom-property t)
6417 (push o org-custom-properties-overlays)))))
6418 ;; Each entry is limited to a single property drawer.
6419 (outline-next-heading)))))))
6421 (defun org-fontify-entities (limit)
6422 "Find an entity to fontify."
6423 (let (ee)
6424 (when org-pretty-entities
6425 (catch 'match
6426 ;; "\_ "-family is left out on purpose. Only the first one,
6427 ;; i.e., "\_ ", could be fontified anyway, and it would be
6428 ;; confusing when adding a second white space character.
6429 (while (re-search-forward
6430 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6431 limit t)
6432 (when (and (not (org-at-comment-p))
6433 (setq ee (org-entity-get (match-string 1)))
6434 (= (length (nth 6 ee)) 1))
6435 (let* ((end (if (equal (match-string 2) "{}")
6436 (match-end 2)
6437 (match-end 1))))
6438 (add-text-properties
6439 (match-beginning 0) end
6440 (list 'font-lock-fontified t))
6441 (compose-region (match-beginning 0) end
6442 (nth 6 ee) nil)
6443 (backward-char 1)
6444 (throw 'match t))))
6445 nil))))
6447 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6448 "Fontify string S like in Org mode."
6449 (with-temp-buffer
6450 (insert s)
6451 (let ((org-odd-levels-only odd-levels))
6452 (org-mode)
6453 (org-font-lock-ensure)
6454 (buffer-string))))
6456 (defvar org-m nil)
6457 (defvar org-l nil)
6458 (defvar org-f nil)
6459 (defun org-get-level-face (n)
6460 "Get the right face for match N in font-lock matching of headlines."
6461 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6462 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6463 (if org-cycle-level-faces
6464 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6465 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6466 (cond
6467 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6468 ((eq n 2) org-f)
6469 (t (unless org-level-color-stars-only org-f))))
6471 (defun org-face-from-face-or-color (context inherit face-or-color)
6472 "Create a face list that inherits INHERIT, but sets the foreground color.
6473 When FACE-OR-COLOR is not a string, just return it."
6474 (if (stringp face-or-color)
6475 (list :inherit inherit
6476 (cdr (assoc context org-faces-easy-properties))
6477 face-or-color)
6478 face-or-color))
6480 (defun org-get-todo-face (kwd)
6481 "Get the right face for a TODO keyword KWD.
6482 If KWD is a number, get the corresponding match group."
6483 (when (numberp kwd) (setq kwd (match-string kwd)))
6484 (or (org-face-from-face-or-color
6485 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6486 (and (member kwd org-done-keywords) 'org-done)
6487 'org-todo))
6489 (defun org-get-priority-face (priority)
6490 "Get the right face for PRIORITY.
6491 PRIORITY is a character."
6492 (or (org-face-from-face-or-color
6493 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6494 'org-priority))
6496 (defun org-get-tag-face (tag)
6497 "Get the right face for TAG.
6498 If TAG is a number, get the corresponding match group."
6499 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6500 (or (org-face-from-face-or-color
6501 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6502 'org-tag)))
6504 (defun org-font-lock-add-priority-faces (limit)
6505 "Add the special priority faces."
6506 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6507 (add-text-properties
6508 (match-beginning 1) (match-end 1)
6509 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6510 'font-lock-fontified t))))
6512 (defun org-font-lock-add-tag-faces (limit)
6513 "Add the special tag faces."
6514 (when (and org-tag-faces org-tags-special-faces-re)
6515 (while (re-search-forward org-tags-special-faces-re limit t)
6516 (add-text-properties (match-beginning 1) (match-end 1)
6517 (list 'face (org-get-tag-face 1)
6518 'font-lock-fontified t))
6519 (backward-char 1))))
6521 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6522 "Remove fontification and activation overlays from links."
6523 (font-lock-default-unfontify-region beg end)
6524 (let* ((buffer-undo-list t)
6525 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6526 (inhibit-modification-hooks t)
6527 deactivate-mark buffer-file-name buffer-file-truename)
6528 (decompose-region beg end)
6529 (remove-text-properties beg end
6530 '(mouse-face t keymap t org-linked-text t
6531 invisible t intangible t
6532 org-emphasis t))
6533 (org-remove-font-lock-display-properties beg end)))
6535 (defconst org-script-display '(((raise -0.3) (height 0.7))
6536 ((raise 0.3) (height 0.7))
6537 ((raise -0.5))
6538 ((raise 0.5)))
6539 "Display properties for showing superscripts and subscripts.")
6541 (defun org-remove-font-lock-display-properties (beg end)
6542 "Remove specific display properties that have been added by font lock.
6543 The will remove the raise properties that are used to show superscripts
6544 and subscripts."
6545 (let (next prop)
6546 (while (< beg end)
6547 (setq next (next-single-property-change beg 'display nil end)
6548 prop (get-text-property beg 'display))
6549 (when (member prop org-script-display)
6550 (put-text-property beg next 'display nil))
6551 (setq beg next))))
6553 (defun org-raise-scripts (limit)
6554 "Add raise properties to sub/superscripts."
6555 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6556 (re-search-forward
6557 (if (eq org-use-sub-superscripts t)
6558 org-match-substring-regexp
6559 org-match-substring-with-braces-regexp)
6560 limit t))
6561 (let* ((pos (point)) table-p comment-p
6562 (mpos (match-beginning 3))
6563 (emph-p (get-text-property mpos 'org-emphasis))
6564 (link-p (get-text-property mpos 'mouse-face))
6565 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6566 (goto-char (point-at-bol))
6567 (setq table-p (looking-at-p org-table-dataline-regexp)
6568 comment-p (looking-at-p "^[ \t]*#[ +]"))
6569 (goto-char pos)
6570 ;; Handle a_b^c
6571 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6572 (unless (or comment-p emph-p link-p keyw-p)
6573 (put-text-property (match-beginning 3) (match-end 0)
6574 'display
6575 (if (equal (char-after (match-beginning 2)) ?^)
6576 (nth (if table-p 3 1) org-script-display)
6577 (nth (if table-p 2 0) org-script-display)))
6578 (add-text-properties (match-beginning 2) (match-end 2)
6579 (list 'invisible t))
6580 (when (and (eq (char-after (match-beginning 3)) ?{)
6581 (eq (char-before (match-end 3)) ?}))
6582 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6583 (list 'invisible t))
6584 (add-text-properties (1- (match-end 3)) (match-end 3)
6585 (list 'invisible t))))
6586 t)))
6588 (defun org-remove-empty-overlays-at (pos)
6589 "Remove outline overlays that do not contain non-white stuff."
6590 (dolist (o (overlays-at pos))
6591 (and (eq 'outline (overlay-get o 'invisible))
6592 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6593 (overlay-end o))))
6594 (delete-overlay o))))
6596 (defun org-show-empty-lines-in-parent ()
6597 "Move to the parent and re-show empty lines before visible headlines."
6598 (save-excursion
6599 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6600 (org-cycle-show-empty-lines context))))
6602 (defun org-files-list ()
6603 "Return `org-agenda-files' list, plus all open Org files.
6604 This is useful for operations that need to scan all of a user's
6605 open and agenda-wise Org files."
6606 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6607 (dolist (buf (buffer-list))
6608 (with-current-buffer buf
6609 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6610 (cl-pushnew (expand-file-name (buffer-file-name)) files
6611 :test #'equal))))
6612 files))
6614 (defsubst org-entry-beginning-position ()
6615 "Return the beginning position of the current entry."
6616 (save-excursion (org-back-to-heading t) (point)))
6618 (defsubst org-entry-end-position ()
6619 "Return the end position of the current entry."
6620 (save-excursion (outline-next-heading) (point)))
6622 (defun org-subtree-end-visible-p ()
6623 "Is the end of the current subtree visible?"
6624 (pos-visible-in-window-p
6625 (save-excursion (org-end-of-subtree t) (point))))
6627 (defun org-first-headline-recenter ()
6628 "Move cursor to the first headline and recenter the headline."
6629 (let ((window (get-buffer-window)))
6630 (when window
6631 (goto-char (point-min))
6632 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6633 (set-window-start window (line-beginning-position))))))
6636 ;;; Visibility (headlines, blocks, drawers)
6638 ;;;; Headlines visibility
6640 (defun org-show-entry ()
6641 "Show the body directly following this heading.
6642 Show the heading too, if it is currently invisible."
6643 (interactive)
6644 (save-excursion
6645 (ignore-errors
6646 (org-back-to-heading t)
6647 (org-flag-region
6648 (line-end-position 0)
6649 (save-excursion
6650 (if (re-search-forward
6651 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6652 (match-beginning 1)
6653 (point-max)))
6655 'outline))))
6657 (defun org-show-children (&optional level)
6658 "Show all direct subheadings of this heading.
6659 Prefix arg LEVEL is how many levels below the current level
6660 should be shown. Default is enough to cause the following
6661 heading to appear."
6662 (interactive "p")
6663 (save-excursion
6664 (org-back-to-heading t)
6665 (let* ((current-level (funcall outline-level))
6666 (max-level (org-get-valid-level
6667 current-level
6668 (if level (prefix-numeric-value level) 1)))
6669 (end (save-excursion (org-end-of-subtree t t)))
6670 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6671 (past-first-child nil)
6672 ;; Make sure to skip inlinetasks.
6673 (re (format regexp-fmt
6674 current-level
6675 (cond
6676 ((not (featurep 'org-inlinetask)) "")
6677 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6679 (t (1- org-inlinetask-min-level))))))
6680 ;; Display parent heading.
6681 (org-flag-heading nil)
6682 (forward-line)
6683 ;; Display children. First child may be deeper than expected
6684 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6685 ;; MAX-LEVEL accordingly.
6686 (while (re-search-forward re end t)
6687 (unless past-first-child
6688 (setq re (format regexp-fmt
6689 current-level
6690 (max (funcall outline-level) max-level)))
6691 (setq past-first-child t))
6692 (org-flag-heading nil)))))
6694 (defun org-show-subtree ()
6695 "Show everything after this heading at deeper levels."
6696 (interactive)
6697 (org-flag-region
6698 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6700 ;;;; Blocks visibility
6702 (defun org-hide-block-toggle-maybe ()
6703 "Toggle visibility of block at point.
6704 Unlike to `org-hide-block-toggle', this function does not throw
6705 an error. Return a non-nil value when toggling is successful."
6706 (interactive)
6707 (ignore-errors (org-hide-block-toggle)))
6709 (defun org-hide-block-toggle (&optional force)
6710 "Toggle the visibility of the current block.
6711 When optional argument FORCE is `off', make block visible. If it
6712 is non-nil, hide it unconditionally. Throw an error when not at
6713 a block. Return a non-nil value when toggling is successful."
6714 (interactive)
6715 (let ((element (org-element-at-point)))
6716 (unless (memq (org-element-type element)
6717 '(center-block comment-block dynamic-block example-block
6718 export-block quote-block special-block
6719 src-block verse-block))
6720 (user-error "Not at a block"))
6721 (let* ((post (org-element-property :post-affiliated element))
6722 (start (save-excursion
6723 (goto-char post)
6724 (line-end-position)))
6725 (end (save-excursion
6726 (goto-char (org-element-property :end element))
6727 (skip-chars-backward " \t\n")
6728 (line-end-position))))
6729 ;; Do nothing when not before or at the block opening line or at
6730 ;; the block closing line.
6731 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6732 (cond ((eq force 'off)
6733 (org-flag-region start end nil 'org-hide-block))
6734 (force
6735 (org-flag-region start end t 'org-hide-block))
6736 ((eq (get-char-property start 'invisible) 'org-hide-block)
6737 (org-flag-region start end nil 'org-hide-block))
6739 (org-flag-region start end t 'org-hide-block)))
6740 ;; When the block is hidden away, make sure point is left in
6741 ;; a visible part of the buffer.
6742 (when (invisible-p (max (1- (point)) (point-min)))
6743 (goto-char post))
6744 ;; Signal success.
6745 t))))
6747 (defun org-hide-block-toggle-all ()
6748 "Toggle the visibility of all blocks in the current buffer."
6749 (org-block-map 'org-hide-block-toggle))
6751 (defun org-hide-block-all ()
6752 "Fold all blocks in the current buffer."
6753 (interactive)
6754 (org-show-all '(blocks))
6755 (org-block-map 'org-hide-block-toggle-maybe))
6757 ;;;; Drawers visibility
6759 (defun org-cycle-hide-drawers (state &optional exceptions)
6760 "Re-hide all drawers after a visibility state change.
6761 STATE should be one of the symbols listed in the docstring of
6762 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6763 a list of strings specifying which drawers should not be hidden."
6764 (when (and (derived-mode-p 'org-mode)
6765 (not (memq state '(overview folded contents))))
6766 (save-excursion
6767 (let* ((globalp (eq state 'all))
6768 (beg (if globalp (point-min) (point)))
6769 (end (if globalp (point-max)
6770 (if (eq state 'children)
6771 (save-excursion (outline-next-heading) (point))
6772 (org-end-of-subtree t)))))
6773 (goto-char beg)
6774 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6775 (unless (member-ignore-case (match-string 1) exceptions)
6776 (let ((drawer (org-element-at-point)))
6777 (when (memq (org-element-type drawer) '(drawer property-drawer))
6778 (org-flag-drawer t drawer)
6779 ;; Make sure to skip drawer entirely or we might flag
6780 ;; it another time when matching its ending line with
6781 ;; `org-drawer-regexp'.
6782 (goto-char (org-element-property :end drawer))))))))))
6784 (defun org-flag-drawer (flag &optional element)
6785 "When FLAG is non-nil, hide the drawer we are at.
6786 Otherwise make it visible. When optional argument ELEMENT is
6787 a parsed drawer, as returned by `org-element-at-point', hide or
6788 show that drawer instead."
6789 (let ((drawer (or element
6790 (and (save-excursion
6791 (beginning-of-line)
6792 (looking-at-p org-drawer-regexp))
6793 (org-element-at-point)))))
6794 (when (memq (org-element-type drawer) '(drawer property-drawer))
6795 (let ((post (org-element-property :post-affiliated drawer)))
6796 (org-flag-region
6797 (save-excursion (goto-char post) (line-end-position))
6798 (save-excursion (goto-char (org-element-property :end drawer))
6799 (skip-chars-backward " \t\n")
6800 (line-end-position))
6801 flag 'org-hide-drawer)
6802 ;; When the drawer is hidden away, make sure point lies in
6803 ;; a visible part of the buffer.
6804 (when (invisible-p (max (1- (point)) (point-min)))
6805 (goto-char post))))))
6807 ;;;; Visibility cycling
6809 (defvar-local org-cycle-global-status nil)
6810 (put 'org-cycle-global-status 'org-state t)
6811 (defvar-local org-cycle-subtree-status nil)
6812 (put 'org-cycle-subtree-status 'org-state t)
6814 (defun org-show-all (&optional types)
6815 "Show all contents in the visible part of the buffer.
6816 By default, the function expands headings, blocks and drawers.
6817 When optional argument TYPE is a list of symbols among `blocks',
6818 `drawers' and `headings', to only expand one specific type."
6819 (dolist (type (or types '(blocks drawers headings)))
6820 (org-flag-region (point-min) (point-max) nil
6821 (pcase type
6822 (`blocks 'org-hide-block)
6823 (`drawers 'org-hide-drawer)
6824 (`headings 'outline)
6825 (_ (error "Invalid type: %S" type))))))
6827 ;;;###autoload
6828 (defun org-cycle (&optional arg)
6829 "TAB-action and visibility cycling for Org mode.
6831 This is the command invoked in Org mode by the `TAB' key. Its main
6832 purpose is outline visibility cycling, but it also invokes other actions
6833 in special contexts.
6835 When this function is called with a `\\[universal-argument]' prefix, rotate \
6836 the entire
6837 buffer through 3 states (global cycling)
6838 1. OVERVIEW: Show only top-level headlines.
6839 2. CONTENTS: Show all headlines of all levels, but no body text.
6840 3. SHOW ALL: Show everything.
6842 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6843 switch to the startup visibility,
6844 determined by the variable `org-startup-folded', and by any VISIBILITY
6845 properties in the buffer.
6847 With a `\\[universal-argument] \\[universal-argument] \
6848 \\[universal-argument]' prefix argument, show the entire buffer, including
6849 any drawers.
6851 When inside a table, re-align the table and move to the next field.
6853 When point is at the beginning of a headline, rotate the subtree started
6854 by this line through 3 different states (local cycling)
6855 1. FOLDED: Only the main headline is shown.
6856 2. CHILDREN: The main headline and the direct children are shown.
6857 From this state, you can move to one of the children
6858 and zoom in further.
6859 3. SUBTREE: Show the entire subtree, including body text.
6860 If there is no subtree, switch directly from CHILDREN to FOLDED.
6862 When point is at the beginning of an empty headline and the variable
6863 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6864 of the headline by demoting and promoting it to likely levels. This
6865 speeds up creation document structure by pressing `TAB' once or several
6866 times right after creating a new headline.
6868 When there is a numeric prefix, go up to a heading with level ARG, do
6869 a `show-subtree' and return to the previous cursor position. If ARG
6870 is negative, go up that many levels.
6872 When point is not at the beginning of a headline, execute the global
6873 binding for `TAB', which is re-indenting the line. See the option
6874 `org-cycle-emulate-tab' for details.
6876 As a special case, if point is at the beginning of the buffer and there is
6877 no headline in line 1, this function will act as if called with prefix arg
6878 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6879 prefix arg, but only
6880 if the variable `org-cycle-global-at-bob' is t."
6881 (interactive "P")
6882 (org-load-modules-maybe)
6883 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6884 (and org-cycle-level-after-item/entry-creation
6885 (or (org-cycle-level)
6886 (org-cycle-item-indentation))))
6887 (let* ((limit-level
6888 (or org-cycle-max-level
6889 (and (boundp 'org-inlinetask-min-level)
6890 org-inlinetask-min-level
6891 (1- org-inlinetask-min-level))))
6892 (nstars (and limit-level
6893 (if org-odd-levels-only
6894 (and limit-level (1- (* limit-level 2)))
6895 limit-level)))
6896 (org-outline-regexp
6897 (if (not (derived-mode-p 'org-mode))
6898 outline-regexp
6899 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6900 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6901 (not (looking-at org-outline-regexp))))
6902 (org-cycle-hook
6903 (if bob-special
6904 (delq 'org-optimize-window-after-visibility-change
6905 (copy-sequence org-cycle-hook))
6906 org-cycle-hook))
6907 (pos (point)))
6909 (cond
6911 ((equal arg '(16))
6912 (setq last-command 'dummy)
6913 (org-set-startup-visibility)
6914 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6916 ((equal arg '(64))
6917 (org-show-all)
6918 (org-unlogged-message "Entire buffer visible, including drawers"))
6920 ((equal arg '(4)) (org-cycle-internal-global))
6922 ;; Try hiding block at point.
6923 ((org-hide-block-toggle-maybe))
6925 ;; Try cdlatex TAB completion
6926 ((org-try-cdlatex-tab))
6928 ;; Table: enter it or move to the next field.
6929 ((org-at-table-p 'any)
6930 (if (org-at-table.el-p)
6931 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6932 Use `\\[org-edit-special]' to edit table.el tables"))
6933 (if arg (org-table-edit-field t)
6934 (org-table-justify-field-maybe)
6935 (call-interactively 'org-table-next-field))))
6937 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6939 ;; Global cycling: delegate to `org-cycle-internal-global'.
6940 (bob-special (org-cycle-internal-global))
6942 ;; Drawers: delegate to `org-flag-drawer'.
6943 ((save-excursion
6944 (beginning-of-line 1)
6945 (looking-at org-drawer-regexp))
6946 (org-flag-drawer ; toggle block visibility
6947 (not (get-char-property (match-end 0) 'invisible))))
6949 ;; Show-subtree, ARG levels up from here.
6950 ((integerp arg)
6951 (save-excursion
6952 (org-back-to-heading)
6953 (outline-up-heading (if (< arg 0) (- arg)
6954 (- (funcall outline-level) arg)))
6955 (org-show-subtree)))
6957 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6958 ((and (featurep 'org-inlinetask)
6959 (org-inlinetask-at-task-p)
6960 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6961 (org-inlinetask-toggle-visibility))
6963 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6964 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6965 (save-excursion (move-beginning-of-line 1)
6966 (looking-at org-outline-regexp)))
6967 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6968 (org-cycle-internal-local))
6970 ;; From there: TAB emulation and template completion.
6971 (buffer-read-only (org-back-to-heading))
6973 ((run-hook-with-args-until-success
6974 'org-tab-after-check-for-cycling-hook))
6976 ((run-hook-with-args-until-success
6977 'org-tab-before-tab-emulation-hook))
6979 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6980 (or (not (bolp))
6981 (not (looking-at org-outline-regexp))))
6982 (call-interactively (global-key-binding "\t")))
6984 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6985 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6986 (or (and (eq org-cycle-emulate-tab 'white)
6987 (= (match-end 0) (point-at-eol)))
6988 (and (eq org-cycle-emulate-tab 'whitestart)
6989 (>= (match-end 0) pos))))
6991 (eq org-cycle-emulate-tab t))
6992 (call-interactively (global-key-binding "\t")))
6994 (t (save-excursion
6995 (org-back-to-heading)
6996 (org-cycle)))))))
6998 (defun org-cycle-internal-global ()
6999 "Do the global cycling action."
7000 ;; Hack to avoid display of messages for .org attachments in Gnus
7001 (let ((ga (string-match "\\*fontification" (buffer-name))))
7002 (cond
7003 ((and (eq last-command this-command)
7004 (eq org-cycle-global-status 'overview))
7005 ;; We just created the overview - now do table of contents
7006 ;; This can be slow in very large buffers, so indicate action
7007 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7008 (unless ga (org-unlogged-message "CONTENTS..."))
7009 (org-content)
7010 (unless ga (org-unlogged-message "CONTENTS...done"))
7011 (setq org-cycle-global-status 'contents)
7012 (run-hook-with-args 'org-cycle-hook 'contents))
7014 ((and (eq last-command this-command)
7015 (eq org-cycle-global-status 'contents))
7016 ;; We just showed the table of contents - now show everything
7017 (run-hook-with-args 'org-pre-cycle-hook 'all)
7018 (org-show-all '(headings blocks))
7019 (unless ga (org-unlogged-message "SHOW ALL"))
7020 (setq org-cycle-global-status 'all)
7021 (run-hook-with-args 'org-cycle-hook 'all))
7024 ;; Default action: go to overview
7025 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7026 (org-overview)
7027 (unless ga (org-unlogged-message "OVERVIEW"))
7028 (setq org-cycle-global-status 'overview)
7029 (run-hook-with-args 'org-cycle-hook 'overview)))))
7031 (defvar org-called-with-limited-levels nil
7032 "Non-nil when `org-with-limited-levels' is currently active.")
7034 (defun org-cycle-internal-local ()
7035 "Do the local cycling action."
7036 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7037 ;; First, determine end of headline (EOH), end of subtree or item
7038 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7039 (save-excursion
7040 (if (org-at-item-p)
7041 (progn
7042 (beginning-of-line)
7043 (setq struct (org-list-struct))
7044 (setq eoh (point-at-eol))
7045 (setq eos (org-list-get-item-end-before-blank (point) struct))
7046 (setq has-children (org-list-has-child-p (point) struct)))
7047 (org-back-to-heading)
7048 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7049 (setq eos (save-excursion (org-end-of-subtree t t)
7050 (when (bolp) (backward-char)) (point)))
7051 (setq has-children
7052 (or (save-excursion
7053 (let ((level (funcall outline-level)))
7054 (outline-next-heading)
7055 (and (org-at-heading-p t)
7056 (> (funcall outline-level) level))))
7057 (save-excursion
7058 (org-list-search-forward (org-item-beginning-re) eos t)))))
7059 ;; Determine end invisible part of buffer (EOL)
7060 (beginning-of-line 2)
7061 (while (and (not (eobp)) ;This is like `next-line'.
7062 (get-char-property (1- (point)) 'invisible))
7063 (goto-char (next-single-char-property-change (point) 'invisible))
7064 (and (eolp) (beginning-of-line 2)))
7065 (setq eol (point)))
7066 ;; Find out what to do next and set `this-command'
7067 (cond
7068 ((= eos eoh)
7069 ;; Nothing is hidden behind this heading
7070 (unless (org-before-first-heading-p)
7071 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7072 (org-unlogged-message "EMPTY ENTRY")
7073 (setq org-cycle-subtree-status nil)
7074 (save-excursion
7075 (goto-char eos)
7076 (outline-next-heading)
7077 (when (org-invisible-p) (org-flag-heading nil))))
7078 ((and (or (>= eol eos)
7079 (not (string-match "\\S-" (buffer-substring eol eos))))
7080 (or has-children
7081 (not (setq children-skipped
7082 org-cycle-skip-children-state-if-no-children))))
7083 ;; Entire subtree is hidden in one line: children view
7084 (unless (org-before-first-heading-p)
7085 (run-hook-with-args 'org-pre-cycle-hook 'children))
7086 (if (org-at-item-p)
7087 (org-list-set-item-visibility (point-at-bol) struct 'children)
7088 (org-show-entry)
7089 (org-with-limited-levels (org-show-children))
7090 (org-show-set-visibility 'canonical)
7091 ;; Fold every list in subtree to top-level items.
7092 (when (eq org-cycle-include-plain-lists 'integrate)
7093 (save-excursion
7094 (org-back-to-heading)
7095 (while (org-list-search-forward (org-item-beginning-re) eos t)
7096 (beginning-of-line 1)
7097 (let* ((struct (org-list-struct))
7098 (prevs (org-list-prevs-alist struct))
7099 (end (org-list-get-bottom-point struct)))
7100 (dolist (e (org-list-get-all-items (point) struct prevs))
7101 (org-list-set-item-visibility e struct 'folded))
7102 (goto-char (if (< end eos) end eos)))))))
7103 (org-unlogged-message "CHILDREN")
7104 (save-excursion
7105 (goto-char eos)
7106 (outline-next-heading)
7107 (when (org-invisible-p) (org-flag-heading nil)))
7108 (setq org-cycle-subtree-status 'children)
7109 (unless (org-before-first-heading-p)
7110 (run-hook-with-args 'org-cycle-hook 'children)))
7111 ((or children-skipped
7112 (and (eq last-command this-command)
7113 (eq org-cycle-subtree-status 'children)))
7114 ;; We just showed the children, or no children are there,
7115 ;; now show everything.
7116 (unless (org-before-first-heading-p)
7117 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7118 (org-flag-region eoh eos nil 'outline)
7119 (org-unlogged-message
7120 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7121 (setq org-cycle-subtree-status 'subtree)
7122 (unless (org-before-first-heading-p)
7123 (run-hook-with-args 'org-cycle-hook 'subtree)))
7125 ;; Default action: hide the subtree.
7126 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7127 (org-flag-region eoh eos t 'outline)
7128 (org-unlogged-message "FOLDED")
7129 (setq org-cycle-subtree-status 'folded)
7130 (unless (org-before-first-heading-p)
7131 (run-hook-with-args 'org-cycle-hook 'folded))))))
7133 ;;;###autoload
7134 (defun org-global-cycle (&optional arg)
7135 "Cycle the global visibility. For details see `org-cycle'.
7136 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7137 With a numeric prefix, show all headlines up to that level."
7138 (interactive "P")
7139 (let ((org-cycle-include-plain-lists
7140 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7141 (cond
7142 ((integerp arg)
7143 (org-show-all '(headings blocks))
7144 (outline-hide-sublevels arg)
7145 (setq org-cycle-global-status 'contents))
7146 ((equal arg '(4))
7147 (org-set-startup-visibility)
7148 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7150 (org-cycle '(4))))))
7152 (defun org-set-startup-visibility ()
7153 "Set the visibility required by startup options and properties."
7154 (cond
7155 ((eq org-startup-folded t)
7156 (org-overview))
7157 ((eq org-startup-folded 'content)
7158 (org-content))
7159 ((or (eq org-startup-folded 'showeverything)
7160 (eq org-startup-folded nil))
7161 (org-show-all)))
7162 (unless (eq org-startup-folded 'showeverything)
7163 (when org-hide-block-startup (org-hide-block-all))
7164 (org-set-visibility-according-to-property)
7165 (org-cycle-hide-archived-subtrees 'all)
7166 (org-cycle-hide-drawers 'all)
7167 (org-cycle-show-empty-lines t)))
7169 (defun org-set-visibility-according-to-property ()
7170 "Switch subtree visibilities according to :VISIBILITY: property."
7171 (interactive)
7172 (org-with-wide-buffer
7173 (goto-char (point-min))
7174 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7175 (if (not (org-at-property-p)) (outline-next-heading)
7176 (let ((state (match-string 3)))
7177 (save-excursion
7178 (org-back-to-heading t)
7179 (outline-hide-subtree)
7180 (org-reveal)
7181 (cond
7182 ((equal state "folded")
7183 (outline-hide-subtree))
7184 ((equal state "children")
7185 (org-show-hidden-entry)
7186 (org-show-children))
7187 ((equal state "content")
7188 (save-excursion
7189 (save-restriction
7190 (org-narrow-to-subtree)
7191 (org-content))))
7192 ((member state '("all" "showall"))
7193 (outline-show-subtree)))))))))
7195 (defun org-overview ()
7196 "Switch to overview mode, showing only top-level headlines.
7197 This shows all headlines with a level equal or greater than the level
7198 of the first headline in the buffer. This is important, because if the
7199 first headline is not level one, then (hide-sublevels 1) gives confusing
7200 results."
7201 (interactive)
7202 (save-excursion
7203 (let ((level
7204 (save-excursion
7205 (goto-char (point-min))
7206 (when (re-search-forward org-outline-regexp-bol nil t)
7207 (goto-char (match-beginning 0))
7208 (funcall outline-level)))))
7209 (and level (outline-hide-sublevels level)))))
7211 (defun org-content (&optional arg)
7212 "Show all headlines in the buffer, like a table of contents.
7213 With numerical argument N, show content up to level N."
7214 (interactive "P")
7215 (org-overview)
7216 (save-excursion
7217 ;; Visit all headings and show their offspring
7218 (and (integerp arg) (org-overview))
7219 (goto-char (point-max))
7220 (catch 'exit
7221 (while (and (progn (condition-case nil
7222 (outline-previous-visible-heading 1)
7223 (error (goto-char (point-min))))
7225 (looking-at org-outline-regexp))
7226 (if (integerp arg)
7227 (org-show-children (1- arg))
7228 (outline-show-branches))
7229 (when (bobp) (throw 'exit nil))))))
7231 (defun org-optimize-window-after-visibility-change (state)
7232 "Adjust the window after a change in outline visibility.
7233 This function is the default value of the hook `org-cycle-hook'."
7234 (when (get-buffer-window (current-buffer))
7235 (cond
7236 ((eq state 'content) nil)
7237 ((eq state 'all) nil)
7238 ((eq state 'folded) nil)
7239 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7240 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7242 (defun org-clean-visibility-after-subtree-move ()
7243 "Fix visibility issues after moving a subtree."
7244 ;; First, find a reasonable region to look at:
7245 ;; Start two siblings above, end three below
7246 (let* ((beg (save-excursion
7247 (and (org-get-last-sibling)
7248 (org-get-last-sibling))
7249 (point)))
7250 (end (save-excursion
7251 (and (org-get-next-sibling)
7252 (org-get-next-sibling)
7253 (org-get-next-sibling))
7254 (if (org-at-heading-p)
7255 (point-at-eol)
7256 (point))))
7257 (level (looking-at "\\*+"))
7258 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7259 (save-excursion
7260 (save-restriction
7261 (narrow-to-region beg end)
7262 (when re
7263 ;; Properly fold already folded siblings
7264 (goto-char (point-min))
7265 (while (re-search-forward re nil t)
7266 (when (and (not (org-invisible-p))
7267 (org-invisible-p (line-end-position)))
7268 (outline-hide-entry))))
7269 (org-cycle-hide-drawers 'all)
7270 (org-cycle-show-empty-lines 'overview)))))
7272 (defun org-cycle-show-empty-lines (state)
7273 "Show empty lines above all visible headlines.
7274 The region to be covered depends on STATE when called through
7275 `org-cycle-hook'. Lisp program can use t for STATE to get the
7276 entire buffer covered. Note that an empty line is only shown if there
7277 are at least `org-cycle-separator-lines' empty lines before the headline."
7278 (when (/= org-cycle-separator-lines 0)
7279 (save-excursion
7280 (let* ((n (abs org-cycle-separator-lines))
7281 (re (cond
7282 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7283 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7284 (t (let ((ns (number-to-string (- n 2))))
7285 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7286 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7287 beg end)
7288 (cond
7289 ((memq state '(overview contents t))
7290 (setq beg (point-min) end (point-max)))
7291 ((memq state '(children folded))
7292 (setq beg (point)
7293 end (progn (org-end-of-subtree t t)
7294 (line-beginning-position 2)))))
7295 (when beg
7296 (goto-char beg)
7297 (while (re-search-forward re end t)
7298 (unless (get-char-property (match-end 1) 'invisible)
7299 (let ((e (match-end 1))
7300 (b (if (>= org-cycle-separator-lines 0)
7301 (match-beginning 1)
7302 (save-excursion
7303 (goto-char (match-beginning 0))
7304 (skip-chars-backward " \t\n")
7305 (line-end-position)))))
7306 (org-flag-region b e nil 'outline))))))))
7307 ;; Never hide empty lines at the end of the file.
7308 (save-excursion
7309 (goto-char (point-max))
7310 (outline-previous-heading)
7311 (outline-end-of-heading)
7312 (when (and (looking-at "[ \t\n]+")
7313 (= (match-end 0) (point-max)))
7314 (org-flag-region (point) (match-end 0) nil 'outline))))
7316 ;;;; Reveal point location
7318 (defun org-show-context (&optional key)
7319 "Make sure point and context are visible.
7320 Optional argument KEY, when non-nil, is a symbol. See
7321 `org-show-context-detail' for allowed values and how much is to
7322 be shown."
7323 (org-show-set-visibility
7324 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7325 ((cdr (assq key org-show-context-detail)))
7326 (t (cdr (assq 'default org-show-context-detail))))))
7328 (defun org-show-set-visibility (detail)
7329 "Set visibility around point according to DETAIL.
7330 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7331 `tree', `canonical' or t. See `org-show-context-detail' for more
7332 information."
7333 ;; Show current heading and possibly its entry, following headline
7334 ;; or all children.
7335 (if (and (org-at-heading-p) (not (eq detail 'local)))
7336 (org-flag-heading nil)
7337 (org-show-entry)
7338 ;; If point is hidden within a drawer or a block, make sure to
7339 ;; expose it.
7340 (dolist (o (overlays-at (point)))
7341 (when (memq (overlay-get o 'invisible)
7342 '(org-hide-block org-hide-drawer outline))
7343 (delete-overlay o)))
7344 (unless (org-before-first-heading-p)
7345 (org-with-limited-levels
7346 (cl-case detail
7347 ((tree canonical t) (org-show-children))
7348 ((nil minimal ancestors))
7349 (t (save-excursion
7350 (outline-next-heading)
7351 (org-flag-heading nil)))))))
7352 ;; Show all siblings.
7353 (when (eq detail 'lineage) (org-show-siblings))
7354 ;; Show ancestors, possibly with their children.
7355 (when (memq detail '(ancestors lineage tree canonical t))
7356 (save-excursion
7357 (while (org-up-heading-safe)
7358 (org-flag-heading nil)
7359 (when (memq detail '(canonical t)) (org-show-entry))
7360 (when (memq detail '(tree canonical t)) (org-show-children))))))
7362 (defvar org-reveal-start-hook nil
7363 "Hook run before revealing a location.")
7365 (defun org-reveal (&optional siblings)
7366 "Show current entry, hierarchy above it, and the following headline.
7368 This can be used to show a consistent set of context around
7369 locations exposed with `org-show-context'.
7371 With optional argument SIBLINGS, on each level of the hierarchy all
7372 siblings are shown. This repairs the tree structure to what it would
7373 look like when opened with hierarchical calls to `org-cycle'.
7375 With a \\[universal-argument] \\[universal-argument] prefix, \
7376 go to the parent and show the entire tree."
7377 (interactive "P")
7378 (run-hooks 'org-reveal-start-hook)
7379 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7380 ((equal siblings '(16))
7381 (save-excursion
7382 (when (org-up-heading-safe)
7383 (org-show-subtree)
7384 (run-hook-with-args 'org-cycle-hook 'subtree))))
7385 (t (org-show-set-visibility 'lineage))))
7388 ;;; Indirect buffer display of subtrees
7390 (defvar org-indirect-dedicated-frame nil
7391 "This is the frame being used for indirect tree display.")
7392 (defvar org-last-indirect-buffer nil)
7394 (defun org-tree-to-indirect-buffer (&optional arg)
7395 "Create indirect buffer and narrow it to current subtree.
7397 With a numerical prefix ARG, go up to this level and then take that tree.
7398 If ARG is negative, go up that many levels.
7400 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7401 indirect buffer previously made with this command, to avoid proliferation of
7402 indirect buffers. However, when you call the command with a \
7403 `\\[universal-argument]' prefix, or
7404 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7405 so that you can work with several indirect buffers at the same time. If
7406 `org-indirect-buffer-display' is `dedicated-frame', the \
7407 `\\[universal-argument]' prefix also
7408 requests that a new frame be made for the new buffer, so that the dedicated
7409 frame is not changed."
7410 (interactive "P")
7411 (let ((cbuf (current-buffer))
7412 (cwin (selected-window))
7413 (pos (point))
7414 beg end level heading ibuf)
7415 (save-excursion
7416 (org-back-to-heading t)
7417 (when (numberp arg)
7418 (setq level (org-outline-level))
7419 (when (< arg 0) (setq arg (+ level arg)))
7420 (while (> (setq level (org-outline-level)) arg)
7421 (org-up-heading-safe)))
7422 (setq beg (point)
7423 heading (org-get-heading 'no-tags))
7424 (org-end-of-subtree t t)
7425 (when (org-at-heading-p) (backward-char 1))
7426 (setq end (point)))
7427 (when (and (buffer-live-p org-last-indirect-buffer)
7428 (not (eq org-indirect-buffer-display 'new-frame))
7429 (not arg))
7430 (kill-buffer org-last-indirect-buffer))
7431 (setq ibuf (org-get-indirect-buffer cbuf heading)
7432 org-last-indirect-buffer ibuf)
7433 (cond
7434 ((or (eq org-indirect-buffer-display 'new-frame)
7435 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7436 (select-frame (make-frame))
7437 (delete-other-windows)
7438 (pop-to-buffer-same-window ibuf)
7439 (org-set-frame-title heading))
7440 ((eq org-indirect-buffer-display 'dedicated-frame)
7441 (raise-frame
7442 (select-frame (or (and org-indirect-dedicated-frame
7443 (frame-live-p org-indirect-dedicated-frame)
7444 org-indirect-dedicated-frame)
7445 (setq org-indirect-dedicated-frame (make-frame)))))
7446 (delete-other-windows)
7447 (pop-to-buffer-same-window ibuf)
7448 (org-set-frame-title (concat "Indirect: " heading)))
7449 ((eq org-indirect-buffer-display 'current-window)
7450 (pop-to-buffer-same-window ibuf))
7451 ((eq org-indirect-buffer-display 'other-window)
7452 (pop-to-buffer ibuf))
7453 (t (error "Invalid value")))
7454 (narrow-to-region beg end)
7455 (org-show-all '(headings blocks))
7456 (goto-char pos)
7457 (run-hook-with-args 'org-cycle-hook 'all)
7458 (and (window-live-p cwin) (select-window cwin))))
7460 (defun org-get-indirect-buffer (&optional buffer heading)
7461 (setq buffer (or buffer (current-buffer)))
7462 (let ((n 1) (base (buffer-name buffer)) bname)
7463 (while (buffer-live-p
7464 (get-buffer
7465 (setq bname
7466 (concat base "-"
7467 (if heading (concat heading "-" (number-to-string n))
7468 (number-to-string n))))))
7469 (setq n (1+ n)))
7470 (condition-case nil
7471 (make-indirect-buffer buffer bname 'clone)
7472 (error (make-indirect-buffer buffer bname)))))
7474 (defun org-set-frame-title (title)
7475 "Set the title of the current frame to the string TITLE."
7476 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7478 ;;;; Structure editing
7480 ;;; Inserting headlines
7482 (defun org--line-empty-p (n)
7483 "Is the Nth next line empty?
7485 Counts the current line as N = 1 and the previous line as N = 0;
7486 see `beginning-of-line'."
7487 (save-excursion
7488 (and (not (bobp))
7489 (or (beginning-of-line n) t)
7490 (save-match-data
7491 (looking-at "[ \t]*$")))))
7493 (defun org-previous-line-empty-p ()
7494 "Is the previous line a blank line?
7495 When NEXT is non-nil, check the next line instead."
7496 (org--line-empty-p 0))
7498 (defun org-next-line-empty-p ()
7499 "Is the previous line a blank line?
7500 When NEXT is non-nil, check the next line instead."
7501 (org--line-empty-p 2))
7503 (defun org--blank-before-heading-p (&optional parent)
7504 "Non-nil when an empty line should precede a new heading here.
7505 When optional argument PARENT is non-nil, consider parent
7506 headline instead of current one."
7507 (pcase (assq 'heading org-blank-before-new-entry)
7508 (`(heading . auto)
7509 (save-excursion
7510 (org-with-limited-levels
7511 (unless (and (org-before-first-heading-p)
7512 (not (outline-next-heading)))
7513 (org-back-to-heading t)
7514 (when parent (org-up-heading-safe))
7515 (cond ((not (bobp))
7516 (org-previous-line-empty-p))
7517 ((outline-next-heading)
7518 (org-previous-line-empty-p))
7519 ;; Ignore trailing spaces on last buffer line.
7520 ((progn (skip-chars-backward " \t") (bolp))
7521 (org-previous-line-empty-p))
7522 (t nil))))))
7523 (`(heading . ,value) value)
7524 (_ nil)))
7526 (defun org-insert-heading (&optional arg invisible-ok top)
7527 "Insert a new heading or an item with the same depth at point.
7529 If point is at the beginning of a heading, insert a new heading
7530 or a new headline above the current one. When at the beginning
7531 of a regular line of text, turn it into a heading.
7533 If point is in the middle of a line, split it and create a new
7534 headline with the text in the current line after point (see
7535 `org-M-RET-may-split-line' on how to modify this behavior). As
7536 a special case, on a headline, splitting can only happen on the
7537 title itself. E.g., this excludes breaking stars or tags.
7539 With a `\\[universal-argument]' prefix, set \
7540 `org-insert-heading-respect-content' to
7541 a non-nil value for the duration of the command. This forces the
7542 insertion of a heading after the current subtree, independently
7543 on the location of point.
7545 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7546 insert the heading at the end of the tree
7547 above the current heading. For example, if point is within a
7548 2nd-level heading, then it will insert a 2nd-level heading at
7549 the end of the 1st-level parent subtree.
7551 When INVISIBLE-OK is set, stop at invisible headlines when going
7552 back. This is important for non-interactive uses of the
7553 command.
7555 When optional argument TOP is non-nil, insert a level 1 heading,
7556 unconditionally."
7557 (interactive "P")
7558 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7559 (level (org-current-level))
7560 (stars (make-string (if (and level (not top)) level 1) ?*)))
7561 (cond
7562 ((or org-insert-heading-respect-content
7563 (member arg '((4) (16)))
7564 (and (not invisible-ok)
7565 (invisible-p (max (1- (point)) (point-min)))))
7566 ;; Position point at the location of insertion.
7567 (if (not level) ;before first headline
7568 (org-with-limited-levels (outline-next-heading))
7569 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7570 ;; is nil.
7571 (org-with-limited-levels (org-back-to-heading invisible-ok))
7572 (cond ((equal arg '(16))
7573 (org-up-heading-safe)
7574 (org-end-of-subtree t t))
7576 (org-end-of-subtree t t))))
7577 (unless (bolp) (insert "\n")) ;ensure final newline
7578 (unless (and blank? (org-previous-line-empty-p))
7579 (org-N-empty-lines-before-current (if blank? 1 0)))
7580 (insert stars " \n")
7581 (forward-char -1))
7582 ;; At a headline...
7583 ((org-at-heading-p)
7584 (cond ((bolp)
7585 (when blank? (save-excursion (insert "\n")))
7586 (save-excursion (insert stars " \n"))
7587 (unless (and blank? (org-previous-line-empty-p))
7588 (org-N-empty-lines-before-current (if blank? 1 0)))
7589 (end-of-line))
7590 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7591 (org-match-line org-complex-heading-regexp)
7592 (org-pos-in-match-range (point) 4))
7593 ;; Grab the text that should moved to the new headline.
7594 ;; Preserve tags.
7595 (let ((split (delete-and-extract-region (point) (match-end 4))))
7596 (if (looking-at "[ \t]*$") (replace-match "")
7597 (org-align-tags))
7598 (end-of-line)
7599 (when blank? (insert "\n"))
7600 (insert "\n" stars " ")
7601 (when (org-string-nw-p split) (insert split))
7602 (when (eobp) (save-excursion (insert "\n")))))
7604 (end-of-line)
7605 (when blank? (insert "\n"))
7606 (insert "\n" stars " ")
7607 (when (eobp) (save-excursion (insert "\n"))))))
7608 ;; On regular text, turn line into a headline or split, if
7609 ;; appropriate.
7610 ((bolp)
7611 (insert stars " ")
7612 (unless (and blank? (org-previous-line-empty-p))
7613 (org-N-empty-lines-before-current (if blank? 1 0))))
7615 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7616 (end-of-line))
7617 (insert "\n" stars " ")
7618 (unless (and blank? (org-previous-line-empty-p))
7619 (org-N-empty-lines-before-current (if blank? 1 0))))))
7620 (run-hooks 'org-insert-heading-hook))
7622 (defun org-N-empty-lines-before-current (n)
7623 "Make the number of empty lines before current exactly N.
7624 So this will delete or add empty lines."
7625 (let ((column (current-column)))
7626 (beginning-of-line)
7627 (unless (bobp)
7628 (let ((start (save-excursion
7629 (skip-chars-backward " \r\t\n")
7630 (line-end-position))))
7631 (delete-region start (line-end-position 0))))
7632 (insert (make-string n ?\n))
7633 (move-to-column column)))
7635 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7636 "Return the heading of the current entry, without the stars.
7637 When NO-TAGS is non-nil, don't include tags.
7638 When NO-TODO is non-nil, don't include TODO keywords.
7639 When NO-PRIORITY is non-nil, don't include priority cookie.
7640 When NO-COMMENT is non-nil, don't include COMMENT string."
7641 (save-excursion
7642 (org-back-to-heading t)
7643 (let ((case-fold-search nil))
7644 (looking-at org-complex-heading-regexp)
7645 (let ((todo (and (not no-todo) (match-string 2)))
7646 (priority (and (not no-priority) (match-string 3)))
7647 (headline (pcase (match-string 4)
7648 (`nil "")
7649 ((and (guard no-comment) h)
7650 (replace-regexp-in-string
7651 (eval-when-compile
7652 (format "\\`%s[ \t]+" org-comment-string))
7653 "" h))
7654 (h h)))
7655 (tags (and (not no-tags) (match-string 5))))
7656 (mapconcat #'identity
7657 (delq nil (list todo priority headline tags))
7658 " ")))))
7660 (defun org-heading-components ()
7661 "Return the components of the current heading.
7662 This is a list with the following elements:
7663 - the level as an integer
7664 - the reduced level, different if `org-odd-levels-only' is set.
7665 - the TODO keyword, or nil
7666 - the priority character, like ?A, or nil if no priority is given
7667 - the headline text itself, or the tags string if no headline text
7668 - the tags string, or nil."
7669 (save-excursion
7670 (org-back-to-heading t)
7671 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7672 (list (length (match-string 1))
7673 (org-reduced-level (length (match-string 1)))
7674 (match-string-no-properties 2)
7675 (and (match-end 3) (aref (match-string 3) 2))
7676 (match-string-no-properties 4)
7677 (match-string-no-properties 5)))))
7679 (defun org-get-entry ()
7680 "Get the entry text, after heading, entire subtree."
7681 (save-excursion
7682 (org-back-to-heading t)
7683 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7685 (defun org-edit-headline (&optional heading)
7686 "Edit the current headline.
7687 Set it to HEADING when provided."
7688 (interactive)
7689 (org-with-wide-buffer
7690 (org-back-to-heading t)
7691 (let ((case-fold-search nil))
7692 (when (looking-at org-complex-heading-regexp)
7693 (let* ((old (match-string-no-properties 4))
7694 (new (save-match-data
7695 (org-trim (or heading (read-string "Edit: " old))))))
7696 (unless (equal old new)
7697 (if old (replace-match new t t nil 4)
7698 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7699 (insert " " new))
7700 (org-align-tags)
7701 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7703 (defun org-insert-heading-after-current ()
7704 "Insert a new heading with same level as current, after current subtree."
7705 (interactive)
7706 (org-back-to-heading)
7707 (org-insert-heading)
7708 (org-move-subtree-down)
7709 (end-of-line 1))
7711 (defun org-insert-heading-respect-content (&optional invisible-ok)
7712 "Insert heading with `org-insert-heading-respect-content' set to t."
7713 (interactive)
7714 (org-insert-heading '(4) invisible-ok))
7716 (defun org-insert-todo-heading-respect-content (&optional force-state)
7717 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7718 (interactive)
7719 (org-insert-todo-heading force-state '(4)))
7721 (defun org-insert-todo-heading (arg &optional force-heading)
7722 "Insert a new heading with the same level and TODO state as current heading.
7724 If the heading has no TODO state, or if the state is DONE, use
7725 the first state (TODO by default). Also with one prefix arg,
7726 force first state. With two prefix args, force inserting at the
7727 end of the parent subtree.
7729 When called at a plain list item, insert a new item with an
7730 unchecked check box."
7731 (interactive "P")
7732 (when (or force-heading (not (org-insert-item 'checkbox)))
7733 (org-insert-heading (or (and (equal arg '(16)) '(16))
7734 force-heading))
7735 (save-excursion
7736 (org-forward-heading-same-level -1)
7737 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7738 (let* ((new-mark-x
7739 (if (or (equal arg '(4))
7740 (not (match-beginning 2))
7741 (member (match-string 2) org-done-keywords))
7742 (car org-todo-keywords-1)
7743 (match-string 2)))
7744 (new-mark
7746 (run-hook-with-args-until-success
7747 'org-todo-get-default-hook new-mark-x nil)
7748 new-mark-x)))
7749 (beginning-of-line 1)
7750 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7751 (if org-treat-insert-todo-heading-as-state-change
7752 (org-todo new-mark)
7753 (insert new-mark " "))))
7754 (when org-provide-todo-statistics
7755 (org-update-parent-todo-statistics))))
7757 (defun org-insert-subheading (arg)
7758 "Insert a new subheading and demote it.
7759 Works for outline headings and for plain lists alike."
7760 (interactive "P")
7761 (org-insert-heading arg)
7762 (cond
7763 ((org-at-heading-p) (org-do-demote))
7764 ((org-at-item-p) (org-indent-item))))
7766 (defun org-insert-todo-subheading (arg)
7767 "Insert a new subheading with TODO keyword or checkbox and demote it.
7768 Works for outline headings and for plain lists alike."
7769 (interactive "P")
7770 (org-insert-todo-heading arg)
7771 (cond
7772 ((org-at-heading-p) (org-do-demote))
7773 ((org-at-item-p) (org-indent-item))))
7775 ;;; Promotion and Demotion
7777 (defvar org-after-demote-entry-hook nil
7778 "Hook run after an entry has been demoted.
7779 The cursor will be at the beginning of the entry.
7780 When a subtree is being demoted, the hook will be called for each node.")
7782 (defvar org-after-promote-entry-hook nil
7783 "Hook run after an entry has been promoted.
7784 The cursor will be at the beginning of the entry.
7785 When a subtree is being promoted, the hook will be called for each node.")
7787 (defun org-promote-subtree ()
7788 "Promote the entire subtree.
7789 See also `org-promote'."
7790 (interactive)
7791 (save-excursion
7792 (org-with-limited-levels (org-map-tree 'org-promote)))
7793 (org-fix-position-after-promote))
7795 (defun org-demote-subtree ()
7796 "Demote the entire subtree.
7797 See `org-demote' and `org-promote'."
7798 (interactive)
7799 (save-excursion
7800 (org-with-limited-levels (org-map-tree 'org-demote)))
7801 (org-fix-position-after-promote))
7803 (defun org-do-promote ()
7804 "Promote the current heading higher up the tree.
7805 If the region is active in `transient-mark-mode', promote all
7806 headings in the region."
7807 (interactive)
7808 (save-excursion
7809 (if (org-region-active-p)
7810 (org-map-region 'org-promote (region-beginning) (region-end))
7811 (org-promote)))
7812 (org-fix-position-after-promote))
7814 (defun org-do-demote ()
7815 "Demote the current heading lower down the tree.
7816 If the region is active in `transient-mark-mode', demote all
7817 headings in the region."
7818 (interactive)
7819 (save-excursion
7820 (if (org-region-active-p)
7821 (org-map-region 'org-demote (region-beginning) (region-end))
7822 (org-demote)))
7823 (org-fix-position-after-promote))
7825 (defun org-fix-position-after-promote ()
7826 "Fix cursor position and indentation after demoting/promoting."
7827 (let ((pos (point)))
7828 (when (save-excursion
7829 (beginning-of-line)
7830 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7831 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7832 (cond ((eobp) (insert " "))
7833 ((eolp) (insert " "))
7834 ((equal (char-after) ?\s) (forward-char 1))))))
7836 (defun org-current-level ()
7837 "Return the level of the current entry, or nil if before the first headline.
7838 The level is the number of stars at the beginning of the
7839 headline. Use `org-reduced-level' to remove the effect of
7840 `org-odd-levels'. Unlike to `org-outline-level', this function
7841 ignores inlinetasks."
7842 (let ((level (org-with-limited-levels (org-outline-level))))
7843 (and (> level 0) level)))
7845 (defun org-get-previous-line-level ()
7846 "Return the outline depth of the last headline before the current line.
7847 Returns 0 for the first headline in the buffer, and nil if before the
7848 first headline."
7849 (and (org-current-level)
7850 (or (and (/= (line-beginning-position) (point-min))
7851 (save-excursion (beginning-of-line 0) (org-current-level)))
7852 0)))
7854 (defun org-reduced-level (l)
7855 "Compute the effective level of a heading.
7856 This takes into account the setting of `org-odd-levels-only'."
7857 (cond
7858 ((zerop l) 0)
7859 (org-odd-levels-only (1+ (floor (/ l 2))))
7860 (t l)))
7862 (defun org-level-increment ()
7863 "Return the number of stars that will be added or removed at a
7864 time to headlines when structure editing, based on the value of
7865 `org-odd-levels-only'."
7866 (if org-odd-levels-only 2 1))
7868 (defun org-get-valid-level (level &optional change)
7869 "Rectify a level change under the influence of `org-odd-levels-only'.
7870 LEVEL is a current level, CHANGE is by how much the level should
7871 be modified. Even if CHANGE is nil, LEVEL may be returned
7872 modified because even level numbers will become the next higher
7873 odd number. Returns values greater than 0."
7874 (if org-odd-levels-only
7875 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7876 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7877 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7878 (max 1 (+ level (or change 0)))))
7880 (defun org-promote ()
7881 "Promote the current heading higher up the tree."
7882 (org-with-wide-buffer
7883 (org-back-to-heading t)
7884 (let* ((after-change-functions (remq 'flyspell-after-change-function
7885 after-change-functions))
7886 (level (save-match-data (funcall outline-level)))
7887 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7888 (diff (abs (- level (length up-head) -1))))
7889 (cond
7890 ((and (= level 1) org-allow-promoting-top-level-subtree)
7891 (replace-match "# " nil t))
7892 ((= level 1)
7893 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7894 (t (replace-match up-head nil t)))
7895 (unless (= level 1)
7896 (when org-auto-align-tags (org-align-tags))
7897 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7898 (run-hooks 'org-after-promote-entry-hook))))
7900 (defun org-demote ()
7901 "Demote the current heading lower down the tree."
7902 (org-with-wide-buffer
7903 (org-back-to-heading t)
7904 (let* ((after-change-functions (remq 'flyspell-after-change-function
7905 after-change-functions))
7906 (level (save-match-data (funcall outline-level)))
7907 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7908 (diff (abs (- level (length down-head) -1))))
7909 (replace-match down-head nil t)
7910 (when org-auto-align-tags (org-align-tags))
7911 (when org-adapt-indentation (org-fixup-indentation diff))
7912 (run-hooks 'org-after-demote-entry-hook))))
7914 (defun org-cycle-level ()
7915 "Cycle the level of an empty headline through possible states.
7916 This goes first to child, then to parent, level, then up the hierarchy.
7917 After top level, it switches back to sibling level."
7918 (interactive)
7919 (let ((org-adapt-indentation nil))
7920 (when (org-point-at-end-of-empty-headline)
7921 (setq this-command 'org-cycle-level) ; Only needed for caching
7922 (let ((cur-level (org-current-level))
7923 (prev-level (org-get-previous-line-level)))
7924 (cond
7925 ;; If first headline in file, promote to top-level.
7926 ((= prev-level 0)
7927 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7928 do (org-do-promote)))
7929 ;; If same level as prev, demote one.
7930 ((= prev-level cur-level)
7931 (org-do-demote))
7932 ;; If parent is top-level, promote to top level if not already.
7933 ((= prev-level 1)
7934 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7935 do (org-do-promote)))
7936 ;; If top-level, return to prev-level.
7937 ((= cur-level 1)
7938 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7939 do (org-do-demote)))
7940 ;; If less than prev-level, promote one.
7941 ((< cur-level prev-level)
7942 (org-do-promote))
7943 ;; If deeper than prev-level, promote until higher than
7944 ;; prev-level.
7945 ((> cur-level prev-level)
7946 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7947 do (org-do-promote))))
7948 t))))
7950 (defun org-map-tree (fun)
7951 "Call FUN for every heading underneath the current one."
7952 (org-back-to-heading t)
7953 (let ((level (funcall outline-level)))
7954 (save-excursion
7955 (funcall fun)
7956 (while (and (progn
7957 (outline-next-heading)
7958 (> (funcall outline-level) level))
7959 (not (eobp)))
7960 (funcall fun)))))
7962 (defun org-map-region (fun beg end)
7963 "Call FUN for every heading between BEG and END."
7964 (let ((org-ignore-region t))
7965 (save-excursion
7966 (setq end (copy-marker end))
7967 (goto-char beg)
7968 (when (and (re-search-forward org-outline-regexp-bol nil t)
7969 (< (point) end))
7970 (funcall fun))
7971 (while (and (progn
7972 (outline-next-heading)
7973 (< (point) end))
7974 (not (eobp)))
7975 (funcall fun)))))
7977 (defun org-fixup-indentation (diff)
7978 "Change the indentation in the current entry by DIFF.
7980 DIFF is an integer. Indentation is done according to the
7981 following rules:
7983 - Planning information and property drawers are always indented
7984 according to the new level of the headline;
7986 - Footnote definitions and their contents are ignored;
7988 - Inlinetasks' boundaries are not shifted;
7990 - Empty lines are ignored;
7992 - Other lines' indentation are shifted by DIFF columns, unless
7993 it would introduce a structural change in the document, in
7994 which case no shifting is done at all.
7996 Assume point is at a heading or an inlinetask beginning."
7997 (org-with-wide-buffer
7998 (narrow-to-region (line-beginning-position)
7999 (save-excursion
8000 (if (org-with-limited-levels (org-at-heading-p))
8001 (org-with-limited-levels (outline-next-heading))
8002 (org-inlinetask-goto-end))
8003 (point)))
8004 (forward-line)
8005 ;; Indent properly planning info and property drawer.
8006 (when (looking-at-p org-planning-line-re)
8007 (org-indent-line)
8008 (forward-line))
8009 (when (looking-at org-property-drawer-re)
8010 (goto-char (match-end 0))
8011 (forward-line)
8012 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8013 (catch 'no-shift
8014 (when (zerop diff) (throw 'no-shift nil))
8015 ;; If DIFF is negative, first check if a shift is possible at all
8016 ;; (e.g., it doesn't break structure). This can only happen if
8017 ;; some contents are not properly indented.
8018 (let ((case-fold-search t))
8019 (when (< diff 0)
8020 (let ((diff (- diff))
8021 (forbidden-re (concat org-outline-regexp
8022 "\\|"
8023 (substring org-footnote-definition-re 1))))
8024 (save-excursion
8025 (while (not (eobp))
8026 (cond
8027 ((looking-at-p "[ \t]*$") (forward-line))
8028 ((and (looking-at-p org-footnote-definition-re)
8029 (let ((e (org-element-at-point)))
8030 (and (eq (org-element-type e) 'footnote-definition)
8031 (goto-char (org-element-property :end e))))))
8032 ((looking-at-p org-outline-regexp) (forward-line))
8033 ;; Give up if shifting would move before column 0 or
8034 ;; if it would introduce a headline or a footnote
8035 ;; definition.
8037 (skip-chars-forward " \t")
8038 (let ((ind (current-column)))
8039 (when (or (< ind diff)
8040 (and (= ind diff) (looking-at-p forbidden-re)))
8041 (throw 'no-shift nil)))
8042 ;; Ignore contents of example blocks and source
8043 ;; blocks if their indentation is meant to be
8044 ;; preserved. Jump to block's closing line.
8045 (beginning-of-line)
8046 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8047 (let ((e (org-element-at-point)))
8048 (and (memq (org-element-type e)
8049 '(example-block src-block))
8050 (or org-src-preserve-indentation
8051 (org-element-property :preserve-indent e))
8052 (goto-char (org-element-property :end e))
8053 (progn (skip-chars-backward " \r\t\n")
8054 (beginning-of-line)
8055 t))))
8056 (forward-line))))))))
8057 ;; Shift lines but footnote definitions, inlinetasks boundaries
8058 ;; by DIFF. Also skip contents of source or example blocks
8059 ;; when indentation is meant to be preserved.
8060 (while (not (eobp))
8061 (cond
8062 ((and (looking-at-p org-footnote-definition-re)
8063 (let ((e (org-element-at-point)))
8064 (and (eq (org-element-type e) 'footnote-definition)
8065 (goto-char (org-element-property :end e))))))
8066 ((looking-at-p org-outline-regexp) (forward-line))
8067 ((looking-at-p "[ \t]*$") (forward-line))
8069 (indent-line-to (+ (org-get-indentation) diff))
8070 (beginning-of-line)
8071 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8072 (let ((e (org-element-at-point)))
8073 (and (memq (org-element-type e)
8074 '(example-block src-block))
8075 (or org-src-preserve-indentation
8076 (org-element-property :preserve-indent e))
8077 (goto-char (org-element-property :end e))
8078 (progn (skip-chars-backward " \r\t\n")
8079 (beginning-of-line)
8080 t))))
8081 (forward-line)))))))))
8083 (defun org-convert-to-odd-levels ()
8084 "Convert an Org file with all levels allowed to one with odd levels.
8085 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8086 level 5 etc."
8087 (interactive)
8088 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8089 (let ((outline-level 'org-outline-level)
8090 (org-odd-levels-only nil) n)
8091 (save-excursion
8092 (goto-char (point-min))
8093 (while (re-search-forward "^\\*\\*+ " nil t)
8094 (setq n (- (length (match-string 0)) 2))
8095 (while (>= (setq n (1- n)) 0)
8096 (org-demote))
8097 (end-of-line 1))))))
8099 (defun org-convert-to-oddeven-levels ()
8100 "Convert an Org file with only odd levels to one with odd/even levels.
8101 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8102 file contains a section with an even level, conversion would
8103 destroy the structure of the file. An error is signaled in this
8104 case."
8105 (interactive)
8106 (goto-char (point-min))
8107 ;; First check if there are no even levels
8108 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8109 (org-show-set-visibility 'canonical)
8110 (error "Not all levels are odd in this file. Conversion not possible"))
8111 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8112 (let ((outline-regexp org-outline-regexp)
8113 (outline-level 'org-outline-level)
8114 (org-odd-levels-only nil) n)
8115 (save-excursion
8116 (goto-char (point-min))
8117 (while (re-search-forward "^\\*\\*+ " nil t)
8118 (setq n (/ (1- (length (match-string 0))) 2))
8119 (while (>= (setq n (1- n)) 0)
8120 (org-promote))
8121 (end-of-line 1))))))
8123 (defun org-tr-level (n)
8124 "Make N odd if required."
8125 (if org-odd-levels-only (1+ (/ n 2)) n))
8127 ;;; Vertical tree motion, cutting and pasting of subtrees
8129 (defun org-move-subtree-up (&optional arg)
8130 "Move the current subtree up past ARG headlines of the same level."
8131 (interactive "p")
8132 (org-move-subtree-down (- (prefix-numeric-value arg))))
8134 (defun org-move-subtree-down (&optional arg)
8135 "Move the current subtree down past ARG headlines of the same level."
8136 (interactive "p")
8137 (setq arg (prefix-numeric-value arg))
8138 (org-preserve-local-variables
8139 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8140 'org-get-last-sibling))
8141 (ins-point (make-marker))
8142 (cnt (abs arg))
8143 (col (current-column))
8144 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8145 ;; Select the tree
8146 (org-back-to-heading)
8147 (setq beg0 (point))
8148 (save-excursion
8149 (setq ne-beg (org-back-over-empty-lines))
8150 (setq beg (point)))
8151 (save-match-data
8152 (save-excursion (outline-end-of-heading)
8153 (setq folded (org-invisible-p)))
8154 (progn (org-end-of-subtree nil t)
8155 (unless (eobp) (backward-char))))
8156 (outline-next-heading)
8157 (setq ne-end (org-back-over-empty-lines))
8158 (setq end (point))
8159 (goto-char beg0)
8160 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8161 ;; include less whitespace
8162 (save-excursion
8163 (goto-char beg)
8164 (forward-line (- ne-beg ne-end))
8165 (setq beg (point))))
8166 ;; Find insertion point, with error handling
8167 (while (> cnt 0)
8168 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8169 (goto-char beg0)
8170 (user-error "Cannot move past superior level or buffer limit"))
8171 (setq cnt (1- cnt)))
8172 (when (> arg 0)
8173 ;; Moving forward - still need to move over subtree
8174 (org-end-of-subtree t t)
8175 (save-excursion
8176 (org-back-over-empty-lines)
8177 (or (bolp) (newline))))
8178 (setq ne-ins (org-back-over-empty-lines))
8179 (move-marker ins-point (point))
8180 (setq txt (buffer-substring beg end))
8181 (org-save-markers-in-region beg end)
8182 (delete-region beg end)
8183 (org-remove-empty-overlays-at beg)
8184 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8185 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8186 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8187 (let ((bbb (point)))
8188 (insert-before-markers txt)
8189 (org-reinstall-markers-in-region bbb)
8190 (move-marker ins-point bbb))
8191 (or (bolp) (insert "\n"))
8192 (setq ins-end (point))
8193 (goto-char ins-point)
8194 (org-skip-whitespace)
8195 (when (and (< arg 0)
8196 (org-first-sibling-p)
8197 (> ne-ins ne-beg))
8198 ;; Move whitespace back to beginning
8199 (save-excursion
8200 (goto-char ins-end)
8201 (let ((kill-whole-line t))
8202 (kill-line (- ne-ins ne-beg)) (point)))
8203 (insert (make-string (- ne-ins ne-beg) ?\n)))
8204 (move-marker ins-point nil)
8205 (if folded
8206 (outline-hide-subtree)
8207 (org-show-entry)
8208 (org-show-children))
8209 (org-clean-visibility-after-subtree-move)
8210 ;; move back to the initial column we were at
8211 (move-to-column col))))
8213 (defvar org-subtree-clip ""
8214 "Clipboard for cut and paste of subtrees.
8215 This is actually only a copy of the kill, because we use the normal kill
8216 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8218 (defvar org-subtree-clip-folded nil
8219 "Was the last copied subtree folded?
8220 This is used to fold the tree back after pasting.")
8222 (defun org-cut-subtree (&optional n)
8223 "Cut the current subtree into the clipboard.
8224 With prefix arg N, cut this many sequential subtrees.
8225 This is a short-hand for marking the subtree and then cutting it."
8226 (interactive "p")
8227 (org-copy-subtree n 'cut))
8229 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8230 "Copy the current subtree into the clipboard.
8231 With prefix arg N, copy this many sequential subtrees.
8232 This is a short-hand for marking the subtree and then copying it.
8233 If CUT is non-nil, actually cut the subtree.
8234 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8235 of some markers in the region, even if CUT is non-nil. This is
8236 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8237 (interactive "p")
8238 (org-preserve-local-variables
8239 (let (beg end folded (beg0 (point)))
8240 (if (called-interactively-p 'any)
8241 (org-back-to-heading nil) ; take what looks like a subtree
8242 (org-back-to-heading t)) ; take what is really there
8243 (setq beg (point))
8244 (skip-chars-forward " \t\r\n")
8245 (save-match-data
8246 (if nosubtrees
8247 (outline-next-heading)
8248 (save-excursion (outline-end-of-heading)
8249 (setq folded (org-invisible-p)))
8250 (ignore-errors (org-forward-heading-same-level (1- n) t))
8251 (org-end-of-subtree t t)))
8252 ;; Include the end of an inlinetask
8253 (when (and (featurep 'org-inlinetask)
8254 (looking-at-p (concat (org-inlinetask-outline-regexp)
8255 "END[ \t]*$")))
8256 (end-of-line))
8257 (setq end (point))
8258 (goto-char beg0)
8259 (when (> end beg)
8260 (setq org-subtree-clip-folded folded)
8261 (when (or cut force-store-markers)
8262 (org-save-markers-in-region beg end))
8263 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8264 (setq org-subtree-clip (current-kill 0))
8265 (message "%s: Subtree(s) with %d characters"
8266 (if cut "Cut" "Copied")
8267 (length org-subtree-clip))))))
8269 (defun org-paste-subtree (&optional level tree for-yank remove)
8270 "Paste the clipboard as a subtree, with modification of headline level.
8272 The entire subtree is promoted or demoted in order to match a new headline
8273 level.
8275 If the cursor is at the beginning of a headline, the same level as
8276 that headline is used to paste the tree.
8278 If not, the new level is derived from the *visible* headings
8279 before and after the insertion point, and taken to be the inferior headline
8280 level of the two. So if the previous visible heading is level 3 and the
8281 next is level 4 (or vice versa), level 4 will be used for insertion.
8282 This makes sure that the subtree remains an independent subtree and does
8283 not swallow low level entries.
8285 You can also force a different level, either by using a numeric prefix
8286 argument, or by inserting the heading marker by hand. For example, if the
8287 cursor is after \"*****\", then the tree will be shifted to level 5.
8289 If optional TREE is given, use this text instead of the kill ring.
8291 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8292 move back over whitespace before inserting, and move point to the end of
8293 the inserted text when done.
8295 When REMOVE is non-nil, remove the subtree from the clipboard."
8296 (interactive "P")
8297 (setq tree (or tree (and kill-ring (current-kill 0))))
8298 (unless (org-kill-is-subtree-p tree)
8299 (user-error
8300 (substitute-command-keys
8301 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8302 (org-with-limited-levels
8303 (let* ((visp (not (org-invisible-p)))
8304 (txt tree)
8305 (old-level (if (string-match org-outline-regexp-bol txt)
8306 (- (match-end 0) (match-beginning 0) 1)
8307 -1))
8308 (force-level
8309 (cond
8310 (level (prefix-numeric-value level))
8311 ;; When point is right after the stars in an otherwise
8312 ;; empty headline, use stars as the forced level.
8313 ((and (looking-at-p "[ \t]*$")
8314 (string-match-p "^\\*+ *"
8315 (buffer-substring (line-beginning-position)
8316 (point))))
8317 (org-outline-level))
8318 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8319 (previous-level
8320 (save-excursion
8321 (org-previous-visible-heading 1)
8322 (if (org-at-heading-p) (org-outline-level) 1)))
8323 (next-level
8324 (save-excursion
8325 (if (org-at-heading-p) (org-outline-level)
8326 (org-next-visible-heading 1)
8327 (if (org-at-heading-p) (org-outline-level) 1))))
8328 (new-level (or force-level (max previous-level next-level)))
8329 (shift (if (or (= old-level -1)
8330 (= new-level -1)
8331 (= old-level new-level))
8333 (- new-level old-level)))
8334 (delta (if (> shift 0) -1 1))
8335 (func (if (> shift 0) #'org-demote #'org-promote))
8336 (org-odd-levels-only nil)
8337 beg end newend)
8338 ;; Remove the forced level indicator.
8339 (when (and force-level (not level))
8340 (delete-region (line-beginning-position) (point)))
8341 ;; Paste before the next visible heading or at end of buffer,
8342 ;; unless point is at the beginning of a headline.
8343 (unless (and (bolp) (org-at-heading-p))
8344 (org-next-visible-heading 1)
8345 (unless (bolp) (insert "\n")))
8346 (setq beg (point))
8347 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8348 (insert-before-markers txt)
8349 (unless (string-suffix-p "\n" txt) (insert "\n"))
8350 (setq newend (point))
8351 (org-reinstall-markers-in-region beg)
8352 (setq end (point))
8353 (goto-char beg)
8354 (skip-chars-forward " \t\n\r")
8355 (setq beg (point))
8356 (when (and (org-invisible-p) visp)
8357 (save-excursion (outline-show-heading)))
8358 ;; Shift if necessary.
8359 (unless (= shift 0)
8360 (save-restriction
8361 (narrow-to-region beg end)
8362 (while (not (= shift 0))
8363 (org-map-region func (point-min) (point-max))
8364 (setq shift (+ delta shift)))
8365 (goto-char (point-min))
8366 (setq newend (point-max))))
8367 (when (or for-yank (called-interactively-p 'interactive))
8368 (message "Clipboard pasted as level %d subtree" new-level))
8369 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8370 kill-ring
8371 (equal org-subtree-clip (current-kill 0))
8372 org-subtree-clip-folded)
8373 ;; The tree was folded before it was killed/copied
8374 (outline-hide-subtree))
8375 (when for-yank (goto-char newend))
8376 (when remove (pop kill-ring)))))
8378 (defun org-kill-is-subtree-p (&optional txt)
8379 "Check if the current kill is an outline subtree, or a set of trees.
8380 Returns nil if kill does not start with a headline, or if the first
8381 headline level is not the largest headline level in the tree.
8382 So this will actually accept several entries of equal levels as well,
8383 which is OK for `org-paste-subtree'.
8384 If optional TXT is given, check this string instead of the current kill."
8385 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8386 (re (org-get-limited-outline-regexp))
8387 (^re (concat "^" re))
8388 (start-level (and kill
8389 (string-match
8390 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8391 kill)
8392 (- (match-end 2) (match-beginning 2) 1)))
8393 (start (1+ (or (match-beginning 2) -1))))
8394 (if (not start-level)
8395 (progn
8396 nil) ;; does not even start with a heading
8397 (catch 'exit
8398 (while (setq start (string-match ^re kill (1+ start)))
8399 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8400 (throw 'exit nil)))
8401 t))))
8403 (defvar org-markers-to-move nil
8404 "Markers that should be moved with a cut-and-paste operation.
8405 Those markers are stored together with their positions relative to
8406 the start of the region.")
8408 (defun org-save-markers-in-region (beg end)
8409 "Check markers in region.
8410 If these markers are between BEG and END, record their position relative
8411 to BEG, so that after moving the block of text, we can put the markers back
8412 into place.
8413 This function gets called just before an entry or tree gets cut from the
8414 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8415 called immediately, to move the markers with the entries."
8416 (setq org-markers-to-move nil)
8417 (when (featurep 'org-clock)
8418 (org-clock-save-markers-for-cut-and-paste beg end))
8419 (when (featurep 'org-agenda)
8420 (org-agenda-save-markers-for-cut-and-paste beg end)))
8422 (defun org-check-and-save-marker (marker beg end)
8423 "Check if MARKER is between BEG and END.
8424 If yes, remember the marker and the distance to BEG."
8425 (when (and (marker-buffer marker)
8426 (equal (marker-buffer marker) (current-buffer))
8427 (>= marker beg) (< marker end))
8428 (push (cons marker (- marker beg)) org-markers-to-move)))
8430 (defun org-reinstall-markers-in-region (beg)
8431 "Move all remembered markers to their position relative to BEG."
8432 (dolist (x org-markers-to-move)
8433 (move-marker (car x) (+ beg (cdr x))))
8434 (setq org-markers-to-move nil))
8436 (defun org-narrow-to-subtree ()
8437 "Narrow buffer to the current subtree."
8438 (interactive)
8439 (save-excursion
8440 (save-match-data
8441 (org-with-limited-levels
8442 (narrow-to-region
8443 (progn (org-back-to-heading t) (point))
8444 (progn (org-end-of-subtree t t)
8445 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8446 (point)))))))
8448 (defun org-narrow-to-block ()
8449 "Narrow buffer to the current block."
8450 (interactive)
8451 (let* ((case-fold-search t)
8452 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8453 "^[ \t]*#\\+end_.*")))
8454 (if blockp
8455 (narrow-to-region (car blockp) (cdr blockp))
8456 (user-error "Not in a block"))))
8458 (defun org-clone-subtree-with-time-shift (n &optional shift)
8459 "Clone the task (subtree) at point N times.
8460 The clones will be inserted as siblings.
8462 In interactive use, the user will be prompted for the number of
8463 clones to be produced. If the entry has a timestamp, the user
8464 will also be prompted for a time shift, which may be a repeater
8465 as used in time stamps, for example `+3d'. To disable this,
8466 you can call the function with a universal prefix argument.
8468 When a valid repeater is given and the entry contains any time
8469 stamps, the clones will become a sequence in time, with time
8470 stamps in the subtree shifted for each clone produced. If SHIFT
8471 is nil or the empty string, time stamps will be left alone. The
8472 ID property of the original subtree is removed.
8474 In each clone, all the CLOCK entries will be removed. This
8475 prevents Org from considering that the clocked times overlap.
8477 If the original subtree did contain time stamps with a repeater,
8478 the following will happen:
8479 - the repeater will be removed in each clone
8480 - an additional clone will be produced, with the current, unshifted
8481 date(s) in the entry.
8482 - the original entry will be placed *after* all the clones, with
8483 repeater intact.
8484 - the start days in the repeater in the original entry will be shifted
8485 to past the last clone.
8486 In this way you can spell out a number of instances of a repeating task,
8487 and still retain the repeater to cover future instances of the task.
8489 As described above, N+1 clones are produced when the original
8490 subtree has a repeater. Setting N to 0, then, can be used to
8491 remove the repeater from a subtree and create a shifted clone
8492 with the original repeater."
8493 (interactive "nNumber of clones to produce: ")
8494 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8495 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8496 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8497 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8498 (shift
8499 (or shift
8500 (if (and (not (equal current-prefix-arg '(4)))
8501 (save-excursion
8502 (goto-char beg)
8503 (re-search-forward org-ts-regexp-both end-of-tree t)))
8504 (read-from-minibuffer
8505 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8506 ""))) ;No time shift
8507 (doshift
8508 (and (org-string-nw-p shift)
8509 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8510 shift)
8511 (user-error "Invalid shift specification %s" shift)))))
8512 (goto-char end-of-tree)
8513 (unless (bolp) (insert "\n"))
8514 (let* ((end (point))
8515 (template (buffer-substring beg end))
8516 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8517 (shift-what (pcase (and doshift (match-string 2 shift))
8518 (`nil nil)
8519 ("d" 'day)
8520 ("w" (setq shift-n (* 7 shift-n)) 'day)
8521 ("m" 'month)
8522 ("y" 'year)
8523 (_ (error "Unsupported time unit"))))
8524 (nmin 1)
8525 (nmax n)
8526 (n-no-remove -1)
8527 (idprop (org-entry-get nil "ID")))
8528 (when (and doshift
8529 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8530 template))
8531 (delete-region beg end)
8532 (setq end beg)
8533 (setq nmin 0)
8534 (setq nmax (1+ nmax))
8535 (setq n-no-remove nmax))
8536 (goto-char end)
8537 (cl-loop for n from nmin to nmax do
8538 (insert
8539 ;; Prepare clone.
8540 (with-temp-buffer
8541 (insert template)
8542 (org-mode)
8543 (goto-char (point-min))
8544 (org-show-subtree)
8545 (and idprop (if org-clone-delete-id
8546 (org-entry-delete nil "ID")
8547 (org-id-get-create t)))
8548 (unless (= n 0)
8549 (while (re-search-forward org-clock-line-re nil t)
8550 (delete-region (line-beginning-position)
8551 (line-beginning-position 2)))
8552 (goto-char (point-min))
8553 (while (re-search-forward org-drawer-regexp nil t)
8554 (org-remove-empty-drawer-at (point))))
8555 (goto-char (point-min))
8556 (when doshift
8557 (while (re-search-forward org-ts-regexp-both nil t)
8558 (org-timestamp-change (* n shift-n) shift-what))
8559 (unless (= n n-no-remove)
8560 (goto-char (point-min))
8561 (while (re-search-forward org-ts-regexp nil t)
8562 (save-excursion
8563 (goto-char (match-beginning 0))
8564 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8565 (delete-region (match-beginning 1) (match-end 1)))))))
8566 (buffer-string)))))
8567 (goto-char beg)))
8569 ;;; Outline Sorting
8571 (defun org-sort (&optional with-case)
8572 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8573 Optional argument WITH-CASE means sort case-sensitively."
8574 (interactive "P")
8575 (org-call-with-arg
8576 (cond ((org-at-table-p) #'org-table-sort-lines)
8577 ((org-at-item-p) #'org-sort-list)
8578 (t #'org-sort-entries))
8579 with-case))
8581 (defun org-sort-remove-invisible (s)
8582 "Remove invisible part of links and emphasis markers from string S."
8583 (remove-text-properties 0 (length s) org-rm-props s)
8584 (replace-regexp-in-string
8585 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8586 (replace-regexp-in-string
8587 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8588 (org-link-display-format s)
8589 t t) t t))
8591 (defvar org-priority-regexp) ; defined later in the file
8593 (defvar org-after-sorting-entries-or-items-hook nil
8594 "Hook that is run after a bunch of entries or items have been sorted.
8595 When children are sorted, the cursor is in the parent line when this
8596 hook gets called. When a region or a plain list is sorted, the cursor
8597 will be in the first entry of the sorted region/list.")
8599 (defun org-sort-entries
8600 (&optional with-case sorting-type getkey-func compare-func property
8601 interactive?)
8602 "Sort entries on a certain level of an outline tree.
8603 If there is an active region, the entries in the region are sorted.
8604 Else, if the cursor is before the first entry, sort the top-level items.
8605 Else, the children of the entry at point are sorted.
8607 Sorting can be alphabetically, numerically, by date/time as given by
8608 a time stamp, by a property, by priority order, or by a custom function.
8610 The command prompts for the sorting type unless it has been given to the
8611 function through the SORTING-TYPE argument, which needs to be a character,
8612 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8613 the precise meaning of each character:
8615 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8616 c By creation time, which is assumed to be the first inactive time stamp
8617 at the beginning of a line.
8618 d By deadline date/time.
8619 k By clocking time.
8620 n Numerically, by converting the beginning of the entry/item to a number.
8621 o By order of TODO keywords.
8622 p By priority according to the cookie.
8623 r By the value of a property.
8624 s By scheduled date/time.
8625 t By date/time, either the first active time stamp in the entry, or, if
8626 none exist, by the first inactive one.
8628 Capital letters will reverse the sort order.
8630 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8631 called with point at the beginning of the record. It must return a
8632 value that is compatible with COMPARE-FUNC, the function used to
8633 compare entries.
8635 Comparing entries ignores case by default. However, with an optional argument
8636 WITH-CASE, the sorting considers case as well.
8638 Sorting is done against the visible part of the headlines, it ignores hidden
8639 links.
8641 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8643 A non-nil value for INTERACTIVE? is used to signal that this
8644 function is being called interactively."
8645 (interactive (list current-prefix-arg nil nil nil nil t))
8646 (let ((case-func (if with-case 'identity 'downcase))
8647 start beg end stars re re2
8648 txt what tmp)
8649 ;; Find beginning and end of region to sort
8650 (cond
8651 ((org-region-active-p)
8652 ;; we will sort the region
8653 (setq end (region-end)
8654 what "region")
8655 (goto-char (region-beginning))
8656 (unless (org-at-heading-p) (outline-next-heading))
8657 (setq start (point)))
8658 ((or (org-at-heading-p)
8659 (ignore-errors (progn (org-back-to-heading) t)))
8660 ;; we will sort the children of the current headline
8661 (org-back-to-heading)
8662 (setq start (point)
8663 end (progn (org-end-of-subtree t t)
8664 (or (bolp) (insert "\n"))
8665 (when (>= (org-back-over-empty-lines) 1)
8666 (forward-line 1))
8667 (point))
8668 what "children")
8669 (goto-char start)
8670 (outline-show-subtree)
8671 (outline-next-heading))
8673 ;; we will sort the top-level entries in this file
8674 (goto-char (point-min))
8675 (or (org-at-heading-p) (outline-next-heading))
8676 (setq start (point))
8677 (goto-char (point-max))
8678 (beginning-of-line 1)
8679 (when (looking-at ".*?\\S-")
8680 ;; File ends in a non-white line
8681 (end-of-line 1)
8682 (insert "\n"))
8683 (setq end (point-max))
8684 (setq what "top-level")
8685 (goto-char start)
8686 (org-show-all '(headings blocks))))
8688 (setq beg (point))
8689 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8691 (looking-at "\\(\\*+\\)")
8692 (setq stars (match-string 1)
8693 re (concat "^" (regexp-quote stars) " +")
8694 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8695 txt (buffer-substring beg end))
8696 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8697 (when (and (not (equal stars "*")) (string-match re2 txt))
8698 (user-error "Region to sort contains a level above the first entry"))
8700 (unless sorting-type
8701 (message
8702 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8703 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8704 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8705 what)
8706 (setq sorting-type (read-char-exclusive)))
8708 (unless getkey-func
8709 (and (= (downcase sorting-type) ?f)
8710 (setq getkey-func
8711 (or (and interactive?
8712 (org-read-function
8713 "Function for extracting keys: "))
8714 (error "Missing key extractor")))))
8716 (and (= (downcase sorting-type) ?r)
8717 (not property)
8718 (setq property
8719 (completing-read "Property: "
8720 (mapcar #'list (org-buffer-property-keys t))
8721 nil t)))
8723 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8724 (message "Sorting entries...")
8726 (save-restriction
8727 (narrow-to-region start end)
8728 (let ((restore-clock?
8729 ;; The clock marker is lost when using `sort-subr'; mark
8730 ;; the clock with temporary `:org-clock-marker-backup'
8731 ;; text property.
8732 (when (and (eq (org-clock-is-active) (current-buffer))
8733 (<= start (marker-position org-clock-marker))
8734 (>= end (marker-position org-clock-marker)))
8735 (org-with-silent-modifications
8736 (put-text-property (1- org-clock-marker) org-clock-marker
8737 :org-clock-marker-backup t))
8739 (dcst (downcase sorting-type))
8740 (case-fold-search nil)
8741 (now (current-time)))
8742 (org-preserve-local-variables
8743 (sort-subr
8744 (/= dcst sorting-type)
8745 ;; This function moves to the beginning character of the
8746 ;; "record" to be sorted.
8747 (lambda nil
8748 (if (re-search-forward re nil t)
8749 (goto-char (match-beginning 0))
8750 (goto-char (point-max))))
8751 ;; This function moves to the last character of the "record" being
8752 ;; sorted.
8753 (lambda nil
8754 (save-match-data
8755 (condition-case nil
8756 (outline-forward-same-level 1)
8757 (error
8758 (goto-char (point-max))))))
8759 ;; This function returns the value that gets sorted against.
8760 (lambda ()
8761 (cond
8762 ((= dcst ?n)
8763 (string-to-number
8764 (org-sort-remove-invisible (org-get-heading t t t t))))
8765 ((= dcst ?a)
8766 (funcall case-func
8767 (org-sort-remove-invisible (org-get-heading t t t t))))
8768 ((= dcst ?k)
8769 (or (get-text-property (point) :org-clock-minutes) 0))
8770 ((= dcst ?t)
8771 (let ((end (save-excursion (outline-next-heading) (point))))
8772 (if (or (re-search-forward org-ts-regexp end t)
8773 (re-search-forward org-ts-regexp-both end t))
8774 (org-time-string-to-seconds (match-string 0))
8775 (float-time now))))
8776 ((= dcst ?c)
8777 (let ((end (save-excursion (outline-next-heading) (point))))
8778 (if (re-search-forward
8779 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8780 end t)
8781 (org-time-string-to-seconds (match-string 0))
8782 (float-time now))))
8783 ((= dcst ?s)
8784 (let ((end (save-excursion (outline-next-heading) (point))))
8785 (if (re-search-forward org-scheduled-time-regexp end t)
8786 (org-time-string-to-seconds (match-string 1))
8787 (float-time now))))
8788 ((= dcst ?d)
8789 (let ((end (save-excursion (outline-next-heading) (point))))
8790 (if (re-search-forward org-deadline-time-regexp end t)
8791 (org-time-string-to-seconds (match-string 1))
8792 (float-time now))))
8793 ((= dcst ?p)
8794 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8795 (string-to-char (match-string 2))
8796 org-default-priority))
8797 ((= dcst ?r)
8798 (or (org-entry-get nil property) ""))
8799 ((= dcst ?o)
8800 (when (looking-at org-complex-heading-regexp)
8801 (let* ((m (match-string 2))
8802 (s (if (member m org-done-keywords) '- '+)))
8803 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8804 ((= dcst ?f)
8805 (if getkey-func
8806 (progn
8807 (setq tmp (funcall getkey-func))
8808 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8809 tmp)
8810 (error "Invalid key function `%s'" getkey-func)))
8811 (t (error "Invalid sorting type `%c'" sorting-type))))
8813 (cond
8814 ((= dcst ?a) 'org-string-collate-lessp)
8815 ((= dcst ?f)
8816 (or compare-func
8817 (and interactive?
8818 (org-read-function
8819 (concat "Function for comparing keys "
8820 "(empty for default `sort-subr' predicate): ")
8821 'allow-empty))))
8822 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8823 (when restore-clock?
8824 (move-marker org-clock-marker
8825 (1+ (next-single-property-change
8826 start :org-clock-marker-backup)))
8827 (remove-text-properties (1- org-clock-marker) org-clock-marker
8828 '(:org-clock-marker-backup t)))))
8829 (run-hooks 'org-after-sorting-entries-or-items-hook)
8830 (message "Sorting entries...done")))
8832 (defun org-contextualize-keys (alist contexts)
8833 "Return valid elements in ALIST depending on CONTEXTS.
8835 `org-agenda-custom-commands' or `org-capture-templates' are the
8836 values used for ALIST, and `org-agenda-custom-commands-contexts'
8837 or `org-capture-templates-contexts' are the associated contexts
8838 definitions."
8839 (let ((contexts
8840 ;; normalize contexts
8841 (mapcar
8842 (lambda(c) (cond ((listp (cadr c))
8843 (list (car c) (car c) (nth 1 c)))
8844 ((string= "" (cadr c))
8845 (list (car c) (car c) (nth 2 c)))
8846 (t c)))
8847 contexts))
8848 (a alist) r s)
8849 ;; loop over all commands or templates
8850 (dolist (c a)
8851 (let (vrules repl)
8852 (cond
8853 ((not (assoc (car c) contexts))
8854 (push c r))
8855 ((and (assoc (car c) contexts)
8856 (setq vrules (org-contextualize-validate-key
8857 (car c) contexts)))
8858 (mapc (lambda (vr)
8859 (unless (equal (car vr) (cadr vr))
8860 (setq repl vr)))
8861 vrules)
8862 (if (not repl) (push c r)
8863 (push (cadr repl) s)
8864 (push
8865 (cons (car c)
8866 (cdr (or (assoc (cadr repl) alist)
8867 (error "Undefined key `%s' as contextual replacement for `%s'"
8868 (cadr repl) (car c)))))
8869 r))))))
8870 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8871 (delq
8873 (delete-dups
8874 (mapcar (lambda (x)
8875 (let ((tpl (car x)))
8876 (unless (delq
8878 (mapcar (lambda (y)
8879 (equal y tpl))
8881 x)))
8882 (reverse r))))))
8884 (defun org-contextualize-validate-key (key contexts)
8885 "Check CONTEXTS for agenda or capture KEY."
8886 (let (res)
8887 (dolist (r contexts)
8888 (dolist (rr (car (last r)))
8889 (when
8890 (and (equal key (car r))
8891 (if (functionp rr) (funcall rr)
8892 (or (and (eq (car rr) 'in-file)
8893 (buffer-file-name)
8894 (string-match (cdr rr) (buffer-file-name)))
8895 (and (eq (car rr) 'in-mode)
8896 (string-match (cdr rr) (symbol-name major-mode)))
8897 (and (eq (car rr) 'in-buffer)
8898 (string-match (cdr rr) (buffer-name)))
8899 (when (and (eq (car rr) 'not-in-file)
8900 (buffer-file-name))
8901 (not (string-match (cdr rr) (buffer-file-name))))
8902 (when (eq (car rr) 'not-in-mode)
8903 (not (string-match (cdr rr) (symbol-name major-mode))))
8904 (when (eq (car rr) 'not-in-buffer)
8905 (not (string-match (cdr rr) (buffer-name)))))))
8906 (push r res))))
8907 (delete-dups (delq nil res))))
8909 ;; Defined to provide a value for defcustom, since there is no
8910 ;; string-collate-greaterp in Emacs.
8911 (defun org-string-collate-greaterp (s1 s2)
8912 "Return non-nil if S1 is greater than S2 in collation order."
8913 (not (org-string-collate-lessp s1 s2)))
8915 ;;;###autoload
8916 (defun org-run-like-in-org-mode (cmd)
8917 "Run a command, pretending that the current buffer is in Org mode.
8918 This will temporarily bind local variables that are typically bound in
8919 Org mode to the values they have in Org mode, and then interactively
8920 call CMD."
8921 (org-load-modules-maybe)
8922 (let (binds)
8923 (dolist (var (org-get-local-variables))
8924 (when (or (not (boundp (car var)))
8925 (eq (symbol-value (car var))
8926 (default-value (car var))))
8927 (push (list (car var) `(quote ,(cadr var))) binds)))
8928 (eval `(let ,binds
8929 (call-interactively (quote ,cmd))))))
8931 (defun org-get-category (&optional pos force-refresh)
8932 "Get the category applying to position POS."
8933 (save-match-data
8934 (when force-refresh (org-refresh-category-properties))
8935 (let ((pos (or pos (point))))
8936 (or (get-text-property pos 'org-category)
8937 (progn (org-refresh-category-properties)
8938 (get-text-property pos 'org-category))))))
8940 ;;; Refresh properties
8942 (defun org-refresh-properties (dprop tprop)
8943 "Refresh buffer text properties.
8944 DPROP is the drawer property and TPROP is either the
8945 corresponding text property to set, or an alist with each element
8946 being a text property (as a symbol) and a function to apply to
8947 the value of the drawer property."
8948 (let* ((case-fold-search t)
8949 (inhibit-read-only t)
8950 (inherit? (org-property-inherit-p dprop))
8951 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8952 (global (and inherit? (org--property-global-value dprop nil))))
8953 (org-with-silent-modifications
8954 (org-with-point-at 1
8955 ;; Set global values (e.g., values defined through
8956 ;; "#+PROPERTY:" keywords) to the whole buffer.
8957 (when global (put-text-property (point-min) (point-max) tprop global))
8958 ;; Set local values.
8959 (while (re-search-forward property-re nil t)
8960 (when (org-at-property-p)
8961 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8962 (outline-next-heading))))))
8964 (defun org-refresh-property (tprop p &optional inherit)
8965 "Refresh the buffer text property TPROP from the drawer property P.
8966 The refresh happens only for the current headline, or the whole
8967 sub-tree if optional argument INHERIT is non-nil."
8968 (unless (org-before-first-heading-p)
8969 (save-excursion
8970 (org-back-to-heading t)
8971 (let ((start (point))
8972 (end (save-excursion
8973 (if inherit (org-end-of-subtree t t)
8974 (or (outline-next-heading) (point-max))))))
8975 (if (symbolp tprop)
8976 ;; TPROP is a text property symbol.
8977 (put-text-property start end tprop p)
8978 ;; TPROP is an alist with (property . function) elements.
8979 (pcase-dolist (`(,prop . ,f) tprop)
8980 (put-text-property start end prop (funcall f p))))))))
8982 (defun org-refresh-category-properties ()
8983 "Refresh category text properties in the buffer."
8984 (let ((case-fold-search t)
8985 (inhibit-read-only t)
8986 (default-category
8987 (cond ((null org-category)
8988 (if buffer-file-name
8989 (file-name-sans-extension
8990 (file-name-nondirectory buffer-file-name))
8991 "???"))
8992 ((symbolp org-category) (symbol-name org-category))
8993 (t org-category))))
8994 (org-with-silent-modifications
8995 (org-with-wide-buffer
8996 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8997 ;; This is the default category for the buffer. If none is
8998 ;; found, fall-back to `org-category' or buffer file name.
8999 (put-text-property
9000 (point-min) (point-max)
9001 'org-category
9002 (catch 'buffer-category
9003 (goto-char (point-max))
9004 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9005 (let ((element (org-element-at-point)))
9006 (when (eq (org-element-type element) 'keyword)
9007 (throw 'buffer-category
9008 (org-element-property :value element)))))
9009 default-category))
9010 ;; Set sub-tree specific categories.
9011 (goto-char (point-min))
9012 (let ((regexp (org-re-property "CATEGORY")))
9013 (while (re-search-forward regexp nil t)
9014 (let ((value (match-string-no-properties 3)))
9015 (when (org-at-property-p)
9016 (put-text-property
9017 (save-excursion (org-back-to-heading t) (point))
9018 (save-excursion (org-end-of-subtree t t) (point))
9019 'org-category
9020 value)))))))))
9022 (defun org-refresh-stats-properties ()
9023 "Refresh stats text properties in the buffer."
9024 (org-with-silent-modifications
9025 (org-with-point-at 1
9026 (let ((regexp (concat org-outline-regexp-bol
9027 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9028 (while (re-search-forward regexp nil t)
9029 (let* ((numerator (string-to-number (match-string 1)))
9030 (denominator (and (match-end 2)
9031 (string-to-number (match-string 2))))
9032 (stats (cond ((not denominator) numerator) ;percent
9033 ((= denominator 0) 0)
9034 (t (/ (* numerator 100) denominator)))))
9035 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9036 'org-stats stats)))))))
9038 (defun org-refresh-effort-properties ()
9039 "Refresh effort properties"
9040 (org-refresh-properties
9041 org-effort-property
9042 '((effort . identity)
9043 (effort-minutes . org-duration-to-minutes))))
9045 ;;;; Link Stuff
9047 ;;; Link abbreviations
9049 (defun org-link-expand-abbrev (link)
9050 "Apply replacements as defined in `org-link-abbrev-alist'."
9051 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9052 (let* ((key (match-string 1 link))
9053 (as (or (assoc key org-link-abbrev-alist-local)
9054 (assoc key org-link-abbrev-alist)))
9055 (tag (and (match-end 2) (match-string 3 link)))
9056 rpl)
9057 (if (not as)
9058 link
9059 (setq rpl (cdr as))
9060 (cond
9061 ((symbolp rpl) (funcall rpl tag))
9062 ((string-match "%(\\([^)]+\\))" rpl)
9063 (replace-match
9064 (save-match-data
9065 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9066 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9067 ((string-match "%h" rpl)
9068 (replace-match (url-hexify-string (or tag "")) t t rpl))
9069 (t (concat rpl tag)))))
9070 link))
9072 ;;; Storing and inserting links
9074 (defvar org-insert-link-history nil
9075 "Minibuffer history for links inserted with `org-insert-link'.")
9077 (defvar org-stored-links nil
9078 "Contains the links stored with `org-store-link'.")
9080 (defvar org-store-link-plist nil
9081 "Plist with info about the most recently link created with `org-store-link'.")
9083 (defun org-store-link-functions ()
9084 "Return a list of functions that are called to create and store a link.
9085 The functions defined in the :store property of
9086 `org-link-parameters'.
9088 Each function will be called in turn until one returns a non-nil
9089 value. Each function should check if it is responsible for
9090 creating this link (for example by looking at the major mode).
9091 If not, it must exit and return nil. If yes, it should return
9092 a non-nil value after calling `org-store-link-props' with a list
9093 of properties and values. Special properties are:
9095 :type The link prefix, like \"http\". This must be given.
9096 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9097 This is obligatory as well.
9098 :description Optional default description for the second pair
9099 of brackets in an Org mode link. The user can still change
9100 this when inserting this link into an Org mode buffer.
9102 In addition to these, any additional properties can be specified
9103 and then used in capture templates."
9104 (cl-loop for link in org-link-parameters
9105 with store-func
9106 do (setq store-func (org-link-get-parameter (car link) :store))
9107 if store-func
9108 collect store-func))
9110 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9111 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9113 ;;;###autoload
9114 (defun org-store-link (arg &optional interactive?)
9115 "Store an org-link to the current location.
9116 \\<org-mode-map>
9117 This link is added to `org-stored-links' and can later be inserted
9118 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9120 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9121 A single
9122 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9123 `org-gnus-prefer-web-links' for links to Usenet articles.
9125 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9126 skipping storing functions that are not
9127 part of Org core.
9129 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9130 prefix ARG forces storing a link for each line in the
9131 active region.
9133 Assume the function is called interactively if INTERACTIVE? is
9134 non-nil."
9135 (interactive "P\np")
9136 (org-load-modules-maybe)
9137 (if (and (equal arg '(64)) (org-region-active-p))
9138 (save-excursion
9139 (let ((end (region-end)))
9140 (goto-char (region-beginning))
9141 (set-mark (point))
9142 (while (< (point-at-eol) end)
9143 (move-end-of-line 1) (activate-mark)
9144 (let (current-prefix-arg)
9145 (call-interactively 'org-store-link))
9146 (move-beginning-of-line 2)
9147 (set-mark (point)))))
9148 (setq org-store-link-plist nil)
9149 (let (link cpltxt desc description search txt custom-id agenda-link)
9150 (cond
9151 ;; Store a link using an external link type, if any function is
9152 ;; available. If more than one can generate a link from current
9153 ;; location, ask which one to use.
9154 ((and (not (equal arg '(16)))
9155 (let ((results-alist nil))
9156 (dolist (f (org-store-link-functions))
9157 (when (funcall f)
9158 ;; XXX: return value is not link's plist, so we
9159 ;; store the new value before it is modified. It
9160 ;; would be cleaner to ask store link functions to
9161 ;; return the plist instead.
9162 (push (cons f (copy-sequence org-store-link-plist))
9163 results-alist)))
9164 (pcase results-alist
9165 (`nil nil)
9166 (`((,_ . ,_)) t) ;single choice: nothing to do
9167 (`((,name . ,_) . ,_)
9168 ;; Reinstate link plist associated to the chosen
9169 ;; function.
9170 (apply #'org-store-link-props
9171 (cdr (assoc-string
9172 (completing-read
9173 "Which function for creating the link? "
9174 (mapcar #'car results-alist)
9175 nil t (symbol-name name))
9176 results-alist)))
9177 t))))
9178 (setq link (plist-get org-store-link-plist :link))
9179 (setq desc (or (plist-get org-store-link-plist :description)
9180 link)))
9182 ;; Store a link from a source code buffer.
9183 ((org-src-edit-buffer-p)
9184 (let ((coderef-format (org-src-coderef-format)))
9185 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9186 (setq link (format "(%s)" (match-string-no-properties 3))))
9187 (interactive?
9188 (let ((label (read-string "Code line label: ")))
9189 (end-of-line)
9190 (setq link (format coderef-format label))
9191 (let ((gc (- 79 (length link))))
9192 (if (< (current-column) gc)
9193 (org-move-to-column gc t)
9194 (insert " ")))
9195 (insert link)
9196 (setq link (concat "(" label ")"))
9197 (setq desc nil)))
9198 (t (setq link nil)))))
9200 ;; We are in the agenda, link to referenced location
9201 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9202 (let ((m (or (get-text-property (point) 'org-hd-marker)
9203 (get-text-property (point) 'org-marker))))
9204 (when m
9205 (org-with-point-at m
9206 (setq agenda-link (org-store-link nil interactive?))))))
9208 ((eq major-mode 'calendar-mode)
9209 (let ((cd (calendar-cursor-to-date)))
9210 (setq link
9211 (format-time-string
9212 (car org-time-stamp-formats)
9213 (apply 'encode-time
9214 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9215 nil nil nil))))
9216 (org-store-link-props :type "calendar" :date cd)))
9218 ((eq major-mode 'help-mode)
9219 (setq link (concat "help:" (save-excursion
9220 (goto-char (point-min))
9221 (looking-at "^[^ ]+")
9222 (match-string 0))))
9223 (org-store-link-props :type "help"))
9225 ((eq major-mode 'w3-mode)
9226 (setq cpltxt (if (and (buffer-name)
9227 (not (string-match "Untitled" (buffer-name))))
9228 (buffer-name)
9229 (url-view-url t))
9230 link (url-view-url t))
9231 (org-store-link-props :type "w3" :url (url-view-url t)))
9233 ((eq major-mode 'image-mode)
9234 (setq cpltxt (concat "file:"
9235 (abbreviate-file-name buffer-file-name))
9236 link cpltxt)
9237 (org-store-link-props :type "image" :file buffer-file-name))
9239 ;; In dired, store a link to the file of the current line
9240 ((derived-mode-p 'dired-mode)
9241 (let ((file (dired-get-filename nil t)))
9242 (setq file (if file
9243 (abbreviate-file-name
9244 (expand-file-name (dired-get-filename nil t)))
9245 ;; otherwise, no file so use current directory.
9246 default-directory))
9247 (setq cpltxt (concat "file:" file)
9248 link cpltxt)))
9250 ((setq search (run-hook-with-args-until-success
9251 'org-create-file-search-functions))
9252 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9253 "::" search))
9254 (setq cpltxt (or description link)))
9256 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9257 (org-with-limited-levels
9258 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9259 (cond
9260 ;; Store a link using the target at point
9261 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9262 (setq cpltxt
9263 (concat "file:"
9264 (abbreviate-file-name
9265 (buffer-file-name (buffer-base-buffer)))
9266 "::" (match-string 1))
9267 link cpltxt))
9268 ((and (featurep 'org-id)
9269 (or (eq org-id-link-to-org-use-id t)
9270 (and interactive?
9271 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9272 (and (eq org-id-link-to-org-use-id
9273 'create-if-interactive-and-no-custom-id)
9274 (not custom-id))))
9275 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9276 ;; Store a link using the ID at point
9277 (setq link (condition-case nil
9278 (prog1 (org-id-store-link)
9279 (setq desc (or (plist-get org-store-link-plist
9280 :description)
9281 "")))
9282 (error
9283 ;; Probably before first headline, link only to file
9284 (concat "file:"
9285 (abbreviate-file-name
9286 (buffer-file-name (buffer-base-buffer))))))))
9288 ;; Just link to current headline
9289 (setq cpltxt (concat "file:"
9290 (abbreviate-file-name
9291 (buffer-file-name (buffer-base-buffer)))))
9292 ;; Add a context search string
9293 (when (org-xor org-context-in-file-links
9294 (equal arg '(4)))
9295 (let* ((element (org-element-at-point))
9296 (name (org-element-property :name element)))
9297 (setq txt (cond
9298 ((org-at-heading-p) nil)
9299 (name)
9300 ((org-region-active-p)
9301 (buffer-substring (region-beginning) (region-end)))))
9302 (when (or (null txt) (string-match "\\S-" txt))
9303 (setq cpltxt
9304 (concat cpltxt "::"
9305 (condition-case nil
9306 (org-make-org-heading-search-string txt)
9307 (error "")))
9308 desc (or name
9309 (nth 4 (ignore-errors (org-heading-components)))
9310 "NONE")))))
9311 (when (string-match "::\\'" cpltxt)
9312 (setq cpltxt (substring cpltxt 0 -2)))
9313 (setq link cpltxt)))))
9315 ((buffer-file-name (buffer-base-buffer))
9316 ;; Just link to this file here.
9317 (setq cpltxt (concat "file:"
9318 (abbreviate-file-name
9319 (buffer-file-name (buffer-base-buffer)))))
9320 ;; Add a context string.
9321 (when (org-xor org-context-in-file-links
9322 (equal arg '(4)))
9323 (setq txt (if (org-region-active-p)
9324 (buffer-substring (region-beginning) (region-end))
9325 (buffer-substring (point-at-bol) (point-at-eol))))
9326 ;; Only use search option if there is some text.
9327 (when (string-match "\\S-" txt)
9328 (setq cpltxt
9329 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9330 desc "NONE")))
9331 (setq link cpltxt))
9333 (interactive?
9334 (user-error "No method for storing a link from this buffer"))
9336 (t (setq link nil)))
9338 ;; We're done setting link and desc, clean up
9339 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9340 (setq link (or link cpltxt)
9341 desc (or desc cpltxt))
9342 (cond ((not desc))
9343 ((equal desc "NONE") (setq desc nil))
9344 (t (setq desc
9345 (replace-regexp-in-string
9346 org-bracket-link-analytic-regexp
9347 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9348 desc))))
9349 ;; Return the link
9350 (if (not (and interactive? link))
9351 (or agenda-link (and link (org-make-link-string link desc)))
9352 (push (list link desc) org-stored-links)
9353 (message "Stored: %s" (or desc link))
9354 (when custom-id
9355 (setq link (concat "file:" (abbreviate-file-name
9356 (buffer-file-name)) "::#" custom-id))
9357 (push (list link desc) org-stored-links))
9358 (car org-stored-links)))))
9360 (defun org-store-link-props (&rest plist)
9361 "Store link properties.
9362 The properties are pre-processed by extracting names, addresses
9363 and dates."
9364 (let ((x (plist-get plist :from)))
9365 (when x
9366 (let ((adr (mail-extract-address-components x)))
9367 (setq plist (plist-put plist :fromname (car adr)))
9368 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9369 (let ((x (plist-get plist :to)))
9370 (when x
9371 (let ((adr (mail-extract-address-components x)))
9372 (setq plist (plist-put plist :toname (car adr)))
9373 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9374 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9375 (when x
9376 (setq plist (plist-put plist :date-timestamp
9377 (format-time-string
9378 (org-time-stamp-format t) x)))
9379 (setq plist (plist-put plist :date-timestamp-inactive
9380 (format-time-string
9381 (org-time-stamp-format t t) x)))))
9382 (let ((from (plist-get plist :from))
9383 (to (plist-get plist :to)))
9384 (when (and from to org-from-is-user-regexp)
9385 (setq plist
9386 (plist-put plist :fromto
9387 (if (string-match org-from-is-user-regexp from)
9388 (concat "to %t")
9389 (concat "from %f"))))))
9390 (setq org-store-link-plist plist))
9392 (defun org-add-link-props (&rest plist)
9393 "Add these properties to the link property list."
9394 (let (key value)
9395 (while plist
9396 (setq key (pop plist) value (pop plist))
9397 (setq org-store-link-plist
9398 (plist-put org-store-link-plist key value)))))
9400 (defun org-email-link-description (&optional fmt)
9401 "Return the description part of an email link.
9402 This takes information from `org-store-link-plist' and formats it
9403 according to FMT (default from `org-email-link-description-format')."
9404 (setq fmt (or fmt org-email-link-description-format))
9405 (let* ((p org-store-link-plist)
9406 (to (plist-get p :toaddress))
9407 (from (plist-get p :fromaddress))
9408 (table
9409 (list
9410 (cons "%c" (plist-get p :fromto))
9411 (cons "%F" (plist-get p :from))
9412 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9413 (cons "%T" (plist-get p :to))
9414 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9415 (cons "%s" (plist-get p :subject))
9416 (cons "%d" (plist-get p :date))
9417 (cons "%m" (plist-get p :message-id)))))
9418 (when (string-match "%c" fmt)
9419 ;; Check if the user wrote this message
9420 (if (and org-from-is-user-regexp from to
9421 (save-match-data (string-match org-from-is-user-regexp from)))
9422 (setq fmt (replace-match "to %t" t t fmt))
9423 (setq fmt (replace-match "from %f" t t fmt))))
9424 (org-replace-escapes fmt table)))
9426 (defun org-make-org-heading-search-string (&optional string)
9427 "Make search string for the current headline or STRING."
9428 (let ((s (or string
9429 (and (derived-mode-p 'org-mode)
9430 (save-excursion
9431 (org-back-to-heading t)
9432 (org-element-property :raw-value (org-element-at-point))))))
9433 (lines org-context-in-file-links))
9434 (unless string (setq s (concat "*" s))) ;Add * for headlines
9435 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9436 (when (and string (integerp lines) (> lines 0))
9437 (let ((slines (org-split-string s "\n")))
9438 (when (< lines (length slines))
9439 (setq s (mapconcat
9440 'identity
9441 (reverse (nthcdr (- (length slines) lines)
9442 (reverse slines))) "\n")))))
9443 (mapconcat #'identity (split-string s) " ")))
9445 (defconst org-link-escape-chars
9446 ;;%20 %5B %5D %25
9447 '(?\s ?\[ ?\] ?%)
9448 "List of characters that should be escaped in a link when stored to Org.
9449 This is the list that is used for internal purposes.")
9451 (defun org-make-link-string (link &optional description)
9452 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9453 (unless (org-string-nw-p link) (error "Empty link"))
9454 (let ((uri (cond ((string-match org-link-types-re link)
9455 (concat (match-string 1 link)
9456 (org-link-escape (substring link (match-end 1)))))
9457 ((or (file-name-absolute-p link)
9458 (string-match-p "\\`\\.\\.?/" link))
9459 (org-link-escape link))
9460 ;; For readability, do not encode space characters
9461 ;; in fuzzy links.
9462 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9463 (description
9464 (and (org-string-nw-p description)
9465 ;; Remove brackets from description, as they are fatal.
9466 (replace-regexp-in-string
9467 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9468 (org-trim description)))))
9469 (format "[[%s]%s]"
9471 (if description (format "[%s]" description) ""))))
9473 (defun org-link-escape (text &optional table merge)
9474 "Return percent escaped representation of TEXT.
9475 TEXT is a string with the text to escape.
9476 Optional argument TABLE is a list with characters that should be
9477 escaped. When nil, `org-link-escape-chars' is used.
9478 If optional argument MERGE is set, merge TABLE into
9479 `org-link-escape-chars'."
9480 (let ((characters-to-encode
9481 (cond ((null table) org-link-escape-chars)
9482 (merge (append org-link-escape-chars table))
9483 (t table))))
9484 (mapconcat
9485 (lambda (c)
9486 (if (or (memq c characters-to-encode)
9487 (and org-url-hexify-p (or (< c 32) (> c 126))))
9488 (mapconcat (lambda (e) (format "%%%.2X" e))
9489 (or (encode-coding-char c 'utf-8)
9490 (error "Unable to percent escape character: %c" c))
9492 (char-to-string c)))
9493 text "")))
9495 (defun org-link-unescape (str)
9496 "Unhex hexified Unicode parts in string STR.
9497 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9498 reciprocal of `org-link-escape', which see."
9499 (if (org-string-nw-p str)
9500 (replace-regexp-in-string
9501 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9502 str))
9504 (defun org-link-unescape-compound (hex)
9505 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9506 Note: this function also decodes single byte encodings like
9507 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9508 (save-match-data
9509 (let* ((bytes (cdr (split-string hex "%")))
9510 (ret "")
9511 (eat 0)
9512 (sum 0))
9513 (while bytes
9514 (let* ((val (string-to-number (pop bytes) 16))
9515 (shift-xor
9516 (if (= 0 eat)
9517 (cond
9518 ((>= val 252) (cons 6 252))
9519 ((>= val 248) (cons 5 248))
9520 ((>= val 240) (cons 4 240))
9521 ((>= val 224) (cons 3 224))
9522 ((>= val 192) (cons 2 192))
9523 (t (cons 0 0)))
9524 (cons 6 128))))
9525 (when (>= val 192) (setq eat (car shift-xor)))
9526 (setq val (logxor val (cdr shift-xor)))
9527 (setq sum (+ (lsh sum (car shift-xor)) val))
9528 (when (> eat 0) (setq eat (- eat 1)))
9529 (cond
9530 ((= 0 eat) ;multi byte
9531 (setq ret (concat ret (char-to-string sum)))
9532 (setq sum 0))
9533 ((not bytes) ; single byte(s)
9534 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9535 ret)))
9537 (defun org-link-unescape-single-byte-sequence (hex)
9538 "Unhexify hex-encoded single byte character sequences."
9539 (mapconcat (lambda (byte)
9540 (char-to-string (string-to-number byte 16)))
9541 (cdr (split-string hex "%")) ""))
9543 (defun org-fixup-message-id-for-http (s)
9544 "Replace special characters in a message id, so it can be used in an http query."
9545 (when (string-match "%" s)
9546 (setq s (mapconcat (lambda (c)
9547 (if (eq c ?%)
9548 "%25"
9549 (char-to-string c)))
9550 s "")))
9551 (while (string-match "<" s)
9552 (setq s (replace-match "%3C" t t s)))
9553 (while (string-match ">" s)
9554 (setq s (replace-match "%3E" t t s)))
9555 (while (string-match "@" s)
9556 (setq s (replace-match "%40" t t s)))
9559 (defun org-link-prettify (link)
9560 "Return a human-readable representation of LINK.
9561 The car of LINK must be a raw link.
9562 The cdr of LINK must be either a link description or nil."
9563 (let ((desc (or (cadr link) "<no description>")))
9564 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9565 "<" (car link) ">")))
9567 ;;;###autoload
9568 (defun org-insert-link-global ()
9569 "Insert a link like Org mode does.
9570 This command can be called in any mode to insert a link in Org syntax."
9571 (interactive)
9572 (org-load-modules-maybe)
9573 (org-run-like-in-org-mode 'org-insert-link))
9575 (defun org-insert-all-links (arg &optional pre post)
9576 "Insert all links in `org-stored-links'.
9577 When a universal prefix, do not delete the links from `org-stored-links'.
9578 When `ARG' is a number, insert the last N link(s).
9579 `PRE' and `POST' are optional arguments to define a string to
9580 prepend or to append."
9581 (interactive "P")
9582 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9583 (links (copy-sequence org-stored-links))
9584 (pr (or pre "- "))
9585 (po (or post "\n"))
9586 (cnt 1) l)
9587 (if (null org-stored-links)
9588 (message "No link to insert")
9589 (while (and (or (listp arg) (>= arg cnt))
9590 (setq l (if (listp arg)
9591 (pop links)
9592 (pop org-stored-links))))
9593 (setq cnt (1+ cnt))
9594 (insert pr)
9595 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9596 (insert po)))))
9598 (defun org-insert-last-stored-link (arg)
9599 "Insert the last link stored in `org-stored-links'."
9600 (interactive "p")
9601 (org-insert-all-links arg "" "\n"))
9603 (defun org-link-fontify-links-to-this-file ()
9604 "Fontify links to the current file in `org-stored-links'."
9605 (let ((f (buffer-file-name)) a b)
9606 (setq a (mapcar (lambda(l)
9607 (let ((ll (car l)))
9608 (when (and (string-match "^file:\\(.+\\)::" ll)
9609 (equal f (expand-file-name (match-string 1 ll))))
9610 ll)))
9611 org-stored-links))
9612 (when (featurep 'org-id)
9613 (setq b (mapcar (lambda(l)
9614 (let ((ll (car l)))
9615 (when (and (string-match "^id:\\(.+\\)$" ll)
9616 (equal f (expand-file-name
9617 (or (org-id-find-id-file
9618 (match-string 1 ll)) ""))))
9619 ll)))
9620 org-stored-links)))
9621 (mapcar (lambda(l)
9622 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9623 (delq nil (append a b)))))
9625 (defvar org--links-history nil)
9626 (defun org-insert-link (&optional complete-file link-location default-description)
9627 "Insert a link. At the prompt, enter the link.
9629 Completion can be used to insert any of the link protocol prefixes in use.
9631 The history can be used to select a link previously stored with
9632 `org-store-link'. When the empty string is entered (i.e. if you just
9633 press `RET' at the prompt), the link defaults to the most recently
9634 stored link. As `SPC' triggers completion in the minibuffer, you need to
9635 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9637 You will also be prompted for a description, and if one is given, it will
9638 be displayed in the buffer instead of the link.
9640 If there is already a link at point, this command will allow you to edit
9641 link and description parts.
9643 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9644 file name can be
9645 selected using completion. The path to the file will be relative to the
9646 current directory if the file is in the current directory or a subdirectory.
9647 Otherwise, the link will be the absolute path as completed in the minibuffer
9648 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9649 option `org-link-file-path-type'.
9651 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9652 absolute path even if the file is in
9653 the current directory or below.
9655 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9656 prefix negates `org-keep-stored-link-after-insertion'.
9658 If the LINK-LOCATION parameter is non-nil, this value will be used as
9659 the link location instead of reading one interactively.
9661 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9662 be used as the default description. Otherwise, if
9663 `org-make-link-description-function' is non-nil, this function
9664 will be called with the link target, and the result will be the
9665 default link description. When called non-interactivily, don't
9666 allow to edit the default description."
9667 (interactive "P")
9668 (let* ((wcf (current-window-configuration))
9669 (origbuf (current-buffer))
9670 (region (when (org-region-active-p)
9671 (buffer-substring (region-beginning) (region-end))))
9672 (remove (and region (list (region-beginning) (region-end))))
9673 (desc region)
9674 (link link-location)
9675 (abbrevs org-link-abbrev-alist-local)
9676 entry all-prefixes auto-desc)
9677 (cond
9678 (link-location) ; specified by arg, just use it.
9679 ((org-in-regexp org-bracket-link-regexp 1)
9680 ;; We do have a link at point, and we are going to edit it.
9681 (setq remove (list (match-beginning 0) (match-end 0)))
9682 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9683 (setq link (read-string "Link: "
9684 (org-link-unescape
9685 (match-string-no-properties 1)))))
9686 ((or (org-in-regexp org-angle-link-re)
9687 (org-in-regexp org-plain-link-re))
9688 ;; Convert to bracket link
9689 (setq remove (list (match-beginning 0) (match-end 0))
9690 link (read-string "Link: "
9691 (org-unbracket-string "<" ">" (match-string 0)))))
9692 ((member complete-file '((4) (16)))
9693 ;; Completing read for file names.
9694 (setq link (org-file-complete-link complete-file)))
9696 ;; Read link, with completion for stored links.
9697 (org-link-fontify-links-to-this-file)
9698 (org-switch-to-buffer-other-window "*Org Links*")
9699 (with-current-buffer "*Org Links*"
9700 (erase-buffer)
9701 (insert "Insert a link.
9702 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9703 (when org-stored-links
9704 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9705 (insert (mapconcat 'org-link-prettify
9706 (reverse org-stored-links) "\n")))
9707 (goto-char (point-min)))
9708 (let ((cw (selected-window)))
9709 (select-window (get-buffer-window "*Org Links*" 'visible))
9710 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9711 (unless (pos-visible-in-window-p (point-max))
9712 (org-fit-window-to-buffer))
9713 (and (window-live-p cw) (select-window cw)))
9714 (setq all-prefixes (append (mapcar 'car abbrevs)
9715 (mapcar 'car org-link-abbrev-alist)
9716 (org-link-types)))
9717 (unwind-protect
9718 ;; Fake a link history, containing the stored links.
9719 (let ((org--links-history
9720 (append (mapcar #'car org-stored-links)
9721 org-insert-link-history)))
9722 (setq link
9723 (org-completing-read
9724 "Link: "
9725 (append
9726 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9727 (mapcar #'car org-stored-links))
9728 nil nil nil
9729 'org--links-history
9730 (caar org-stored-links)))
9731 (unless (org-string-nw-p link) (user-error "No link selected"))
9732 (dolist (l org-stored-links)
9733 (when (equal link (cadr l))
9734 (setq link (car l))
9735 (setq auto-desc t)))
9736 (when (or (member link all-prefixes)
9737 (and (equal ":" (substring link -1))
9738 (member (substring link 0 -1) all-prefixes)
9739 (setq link (substring link 0 -1))))
9740 (setq link (with-current-buffer origbuf
9741 (org-link-try-special-completion link)))))
9742 (set-window-configuration wcf)
9743 (kill-buffer "*Org Links*"))
9744 (setq entry (assoc link org-stored-links))
9745 (or entry (push link org-insert-link-history))
9746 (setq desc (or desc (nth 1 entry)))))
9748 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9749 (not org-keep-stored-link-after-insertion))
9750 (setq org-stored-links (delq (assoc link org-stored-links)
9751 org-stored-links)))
9753 (when (and (string-match org-plain-link-re link)
9754 (not (string-match org-ts-regexp link)))
9755 ;; URL-like link, normalize the use of angular brackets.
9756 (setq link (org-unbracket-string "<" ">" link)))
9758 ;; Check if we are linking to the current file with a search
9759 ;; option If yes, simplify the link by using only the search
9760 ;; option.
9761 (when (and buffer-file-name
9762 (let ((case-fold-search nil))
9763 (string-match "\\`file:\\(.+?\\)::" link)))
9764 (let ((path (match-string-no-properties 1 link))
9765 (search (substring-no-properties link (match-end 0))))
9766 (save-match-data
9767 (when (equal (file-truename buffer-file-name) (file-truename path))
9768 ;; We are linking to this same file, with a search option
9769 (setq link search)))))
9771 ;; Check if we can/should use a relative path. If yes, simplify
9772 ;; the link.
9773 (let ((case-fold-search nil))
9774 (when (string-match "\\`\\(file\\|docview\\):" link)
9775 (let* ((type (match-string-no-properties 0 link))
9776 (path-start (match-end 0))
9777 (search (and (string-match "::\\(.*\\)\\'" link)
9778 (match-string 1 link)))
9779 (path
9780 (if search
9781 (substring-no-properties
9782 link path-start (match-beginning 0))
9783 (substring-no-properties link (match-end 0))))
9784 (origpath path))
9785 (cond
9786 ((or (eq org-link-file-path-type 'absolute)
9787 (equal complete-file '(16)))
9788 (setq path (abbreviate-file-name (expand-file-name path))))
9789 ((eq org-link-file-path-type 'noabbrev)
9790 (setq path (expand-file-name path)))
9791 ((eq org-link-file-path-type 'relative)
9792 (setq path (file-relative-name path)))
9794 (save-match-data
9795 (if (string-match (concat "^" (regexp-quote
9796 (expand-file-name
9797 (file-name-as-directory
9798 default-directory))))
9799 (expand-file-name path))
9800 ;; We are linking a file with relative path name.
9801 (setq path (substring (expand-file-name path)
9802 (match-end 0)))
9803 (setq path (abbreviate-file-name (expand-file-name path)))))))
9804 (setq link (concat type path (and search (concat "::" search))))
9805 (when (equal desc origpath)
9806 (setq desc path)))))
9808 (unless auto-desc
9809 (let ((initial-input
9810 (cond
9811 (default-description)
9812 ((not org-make-link-description-function) desc)
9813 (t (condition-case nil
9814 (funcall org-make-link-description-function link desc)
9815 (error
9816 (message "Can't get link description from `%s'"
9817 (symbol-name org-make-link-description-function))
9818 (sit-for 2)
9819 nil))))))
9820 (setq desc (if (called-interactively-p 'any)
9821 (read-string "Description: " initial-input)
9822 initial-input))))
9824 (unless (string-match "\\S-" desc) (setq desc nil))
9825 (when remove (apply 'delete-region remove))
9826 (insert (org-make-link-string link desc))
9827 ;; Redisplay so as the new link has proper invisible characters.
9828 (sit-for 0)))
9830 (defun org-link-try-special-completion (type)
9831 "If there is completion support for link type TYPE, offer it."
9832 (let ((fun (org-link-get-parameter type :complete)))
9833 (if (functionp fun)
9834 (funcall fun)
9835 (read-string "Link (no completion support): " (concat type ":")))))
9837 (defun org-file-complete-link (&optional arg)
9838 "Create a file link using completion."
9839 (let ((file (read-file-name "File: "))
9840 (pwd (file-name-as-directory (expand-file-name ".")))
9841 (pwd1 (file-name-as-directory (abbreviate-file-name
9842 (expand-file-name ".")))))
9843 (cond ((equal arg '(16))
9844 (concat "file:"
9845 (abbreviate-file-name (expand-file-name file))))
9846 ((string-match
9847 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9848 (concat "file:" (match-string 1 file)))
9849 ((string-match
9850 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9851 (expand-file-name file))
9852 (concat "file:"
9853 (match-string 1 (expand-file-name file))))
9854 (t (concat "file:" file)))))
9857 ;;; Opening/following a link
9859 (defvar org-link-search-failed nil)
9861 (defvar org-open-link-functions nil
9862 "Hook for functions finding a plain text link.
9863 These functions must take a single argument, the link content.
9864 They will be called for links that look like [[link text][description]]
9865 when LINK TEXT does not have a protocol like \"http:\" and does not look
9866 like a filename (e.g. \"./blue.png\").
9868 These functions will be called *before* Org attempts to resolve the
9869 link by doing text searches in the current buffer - so if you want a
9870 link \"[[target]]\" to still find \"<<target>>\", your function should
9871 handle this as a special case.
9873 When the function does handle the link, it must return a non-nil value.
9874 If it decides that it is not responsible for this link, it must return
9875 nil to indicate that that Org can continue with other options like
9876 exact and fuzzy text search.")
9878 (defun org-next-link (&optional search-backward)
9879 "Move forward to the next link.
9880 If the link is in hidden text, expose it."
9881 (interactive "P")
9882 (when (and org-link-search-failed (eq this-command last-command))
9883 (goto-char (point-min))
9884 (message "Link search wrapped back to beginning of buffer"))
9885 (setq org-link-search-failed nil)
9886 (let* ((pos (point))
9887 (ct (org-context))
9888 (a (assq :link ct))
9889 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9890 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9891 ((looking-at org-any-link-re)
9892 ;; Don't stay stuck at link without an org-link face
9893 (forward-char (if search-backward -1 1))))
9894 (if (funcall srch-fun org-any-link-re nil t)
9895 (progn
9896 (goto-char (match-beginning 0))
9897 (when (org-invisible-p) (org-show-context)))
9898 (goto-char pos)
9899 (setq org-link-search-failed t)
9900 (message "No further link found"))))
9902 (defun org-previous-link ()
9903 "Move backward to the previous link.
9904 If the link is in hidden text, expose it."
9905 (interactive)
9906 (funcall 'org-next-link t))
9908 (defun org-translate-link (s)
9909 "Translate a link string if a translation function has been defined."
9910 (with-temp-buffer
9911 (insert (org-trim s))
9912 (org-trim (org-element-interpret-data (org-element-context)))))
9914 (defun org-translate-link-from-planner (type path)
9915 "Translate a link from Emacs Planner syntax so that Org can follow it.
9916 This is still an experimental function, your mileage may vary."
9917 (cond
9918 ((member type '("http" "https" "news" "ftp"))
9919 ;; standard Internet links are the same.
9920 nil)
9921 ((and (equal type "irc") (string-match "^//" path))
9922 ;; Planner has two / at the beginning of an irc link, we have 1.
9923 ;; We should have zero, actually....
9924 (setq path (substring path 1)))
9925 ((and (equal type "lisp") (string-match "^/" path))
9926 ;; Planner has a slash, we do not.
9927 (setq type "elisp" path (substring path 1)))
9928 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9929 ;; A typical message link. Planner has the id after the final slash,
9930 ;; we separate it with a hash mark
9931 (setq path (concat (match-string 1 path) "#"
9932 (org-unbracket-string "<" ">" (match-string 2 path))))))
9933 (cons type path))
9935 (defun org-find-file-at-mouse (ev)
9936 "Open file link or URL at mouse."
9937 (interactive "e")
9938 (mouse-set-point ev)
9939 (org-open-at-point 'in-emacs))
9941 (defun org-open-at-mouse (ev)
9942 "Open file link or URL at mouse.
9943 See the docstring of `org-open-file' for details."
9944 (interactive "e")
9945 (mouse-set-point ev)
9946 (when (eq major-mode 'org-agenda-mode)
9947 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9948 (org-open-at-point))
9950 (defvar org-window-config-before-follow-link nil
9951 "The window configuration before following a link.
9952 This is saved in case the need arises to restore it.")
9954 ;;;###autoload
9955 (defun org-open-at-point-global ()
9956 "Follow a link or time-stamp like Org mode does.
9957 This command can be called in any mode to follow an external link
9958 or a time-stamp that has Org mode syntax. Its behavior is
9959 undefined when called on internal links (e.g., fuzzy links).
9960 Raise an error when there is nothing to follow. "
9961 (interactive)
9962 (cond ((org-in-regexp org-any-link-re)
9963 (org-open-link-from-string (match-string-no-properties 0)))
9964 ((or (org-in-regexp org-ts-regexp-both nil t)
9965 (org-in-regexp org-tsr-regexp-both nil t))
9966 (org-follow-timestamp-link))
9967 (t (user-error "No link found"))))
9969 ;;;###autoload
9970 (defun org-open-link-from-string (s &optional arg reference-buffer)
9971 "Open a link in the string S, as if it was in Org mode."
9972 (interactive "sLink: \nP")
9973 (let ((reference-buffer (or reference-buffer (current-buffer))))
9974 (with-temp-buffer
9975 (let ((org-inhibit-startup (not reference-buffer)))
9976 (org-mode)
9977 (insert s)
9978 (goto-char (point-min))
9979 (when reference-buffer
9980 (setq org-link-abbrev-alist-local
9981 (with-current-buffer reference-buffer
9982 org-link-abbrev-alist-local)))
9983 (org-open-at-point arg reference-buffer)))))
9985 (defvar org-open-at-point-functions nil
9986 "Hook that is run when following a link at point.
9988 Functions in this hook must return t if they identify and follow
9989 a link at point. If they don't find anything interesting at point,
9990 they must return nil.")
9992 (defvar org-link-search-inhibit-query nil)
9993 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9994 (defun org--open-doi-link (path)
9995 "Open a \"doi\" type link.
9996 PATH is a the path to search for, as a string."
9997 (browse-url (url-encode-url (concat org-doi-server-url path))))
9999 (defun org--open-elisp-link (path)
10000 "Open a \"elisp\" type link.
10001 PATH is the sexp to evaluate, as a string."
10002 (let ((cmd path))
10003 (if (or (and (org-string-nw-p
10004 org-confirm-elisp-link-not-regexp)
10005 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10006 (not org-confirm-elisp-link-function)
10007 (funcall org-confirm-elisp-link-function
10008 (format "Execute \"%s\" as elisp? "
10009 (org-add-props cmd nil 'face 'org-warning))))
10010 (message "%s => %s" cmd
10011 (if (eq (string-to-char cmd) ?\()
10012 (eval (read cmd))
10013 (call-interactively (read cmd))))
10014 (user-error "Abort"))))
10016 (defun org--open-help-link (path)
10017 "Open a \"help\" type link.
10018 PATH is a symbol name, as a string."
10019 (pcase (intern path)
10020 ((and (pred fboundp) variable) (describe-function variable))
10021 ((and (pred boundp) function) (describe-variable function))
10022 (name (user-error "Unknown function or variable: %s" name))))
10024 (defun org--open-shell-link (path)
10025 "Open a \"shell\" type link.
10026 PATH is the command to execute, as a string."
10027 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10028 (cmd path))
10029 (if (or (and (org-string-nw-p
10030 org-confirm-shell-link-not-regexp)
10031 (string-match
10032 org-confirm-shell-link-not-regexp cmd))
10033 (not org-confirm-shell-link-function)
10034 (funcall org-confirm-shell-link-function
10035 (format "Execute \"%s\" in shell? "
10036 (org-add-props cmd nil
10037 'face 'org-warning))))
10038 (progn
10039 (message "Executing %s" cmd)
10040 (shell-command cmd buf)
10041 (when (featurep 'midnight)
10042 (setq clean-buffer-list-kill-buffer-names
10043 (cons (buffer-name buf)
10044 clean-buffer-list-kill-buffer-names))))
10045 (user-error "Abort"))))
10047 (defun org-open-at-point (&optional arg reference-buffer)
10048 "Open link, timestamp, footnote or tags at point.
10050 When point is on a link, follow it. Normally, files will be
10051 opened by an appropriate application. If the optional prefix
10052 argument ARG is non-nil, Emacs will visit the file. With
10053 a double prefix argument, try to open outside of Emacs, in the
10054 application the system uses for this file type.
10056 When point is on a timestamp, open the agenda at the day
10057 specified.
10059 When point is a footnote definition, move to the first reference
10060 found. If it is on a reference, move to the associated
10061 definition.
10063 When point is on a headline, display a list of every link in the
10064 entry, so it is possible to pick one, or all, of them. If point
10065 is on a tag, call `org-tags-view' instead.
10067 When optional argument REFERENCE-BUFFER is non-nil, it should
10068 specify a buffer from where the link search should happen. This
10069 is used internally by `org-open-link-from-string'.
10071 On top of syntactically correct links, this function will also
10072 try to open links and time-stamps in comments, example
10073 blocks... i.e., whenever point is on something looking like
10074 a timestamp or a link."
10075 (interactive "P")
10076 ;; On a code block, open block's results.
10077 (unless (call-interactively 'org-babel-open-src-block-result)
10078 (org-load-modules-maybe)
10079 (setq org-window-config-before-follow-link (current-window-configuration))
10080 (org-remove-occur-highlights nil nil t)
10081 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10082 (let* ((context
10083 ;; Only consider supported types, even if they are not
10084 ;; the closest one.
10085 (org-element-lineage
10086 (org-element-context)
10087 '(clock footnote-definition footnote-reference headline
10088 inlinetask link timestamp)
10090 (type (org-element-type context))
10091 (value (org-element-property :value context)))
10092 (cond
10093 ;; On a headline or an inlinetask, but not on a timestamp,
10094 ;; a link, a footnote reference.
10095 ((memq type '(headline inlinetask))
10096 (org-match-line org-complex-heading-regexp)
10097 (if (and (match-beginning 5)
10098 (>= (point) (match-beginning 5))
10099 (< (point) (match-end 5)))
10100 ;; On tags.
10101 (org-tags-view arg (substring (match-string 5) 0 -1))
10102 ;; Not on tags.
10103 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10104 (`(nil . ,_)
10105 (require 'org-attach)
10106 (org-attach-reveal 'if-exists))
10107 (`(,links . ,links-end)
10108 (dolist (link (if (stringp links) (list links) links))
10109 (search-forward link nil links-end)
10110 (goto-char (match-beginning 0))
10111 (org-open-at-point))))))
10112 ;; On a footnote reference or at definition's label.
10113 ((or (eq type 'footnote-reference)
10114 (and (eq type 'footnote-definition)
10115 (save-excursion
10116 ;; Do not validate action when point is on the
10117 ;; spaces right after the footnote label, in
10118 ;; order to be on par with behavior on links.
10119 (skip-chars-forward " \t")
10120 (let ((begin
10121 (org-element-property :contents-begin context)))
10122 (if begin (< (point) begin)
10123 (= (org-element-property :post-affiliated context)
10124 (line-beginning-position)))))))
10125 (org-footnote-action))
10126 ;; No valid context. Ignore catch-all types like `headline'.
10127 ;; If point is on something looking like a link or
10128 ;; a time-stamp, try opening it. It may be useful in
10129 ;; comments, example blocks...
10130 ((memq type '(footnote-definition headline inlinetask nil))
10131 (call-interactively #'org-open-at-point-global))
10132 ;; On a clock line, make sure point is on the timestamp
10133 ;; before opening it.
10134 ((and (eq type 'clock)
10135 value
10136 (>= (point) (org-element-property :begin value))
10137 (<= (point) (org-element-property :end value)))
10138 (org-follow-timestamp-link))
10139 ;; Do nothing on white spaces after an object.
10140 ((>= (point)
10141 (save-excursion
10142 (goto-char (org-element-property :end context))
10143 (skip-chars-backward " \t")
10144 (point)))
10145 (user-error "No link found"))
10146 ((eq type 'timestamp) (org-follow-timestamp-link))
10147 ((eq type 'link)
10148 (let ((type (org-element-property :type context))
10149 (path (org-link-unescape (org-element-property :path context))))
10150 ;; Switch back to REFERENCE-BUFFER needed when called in
10151 ;; a temporary buffer through `org-open-link-from-string'.
10152 (with-current-buffer (or reference-buffer (current-buffer))
10153 (cond
10154 ((equal type "file")
10155 (if (string-match "[*?{]" (file-name-nondirectory path))
10156 (dired path)
10157 ;; Look into `org-link-parameters' in order to find
10158 ;; a DEDICATED-FUNCTION to open file. The function
10159 ;; will be applied on raw link instead of parsed
10160 ;; link due to the limitation in `org-add-link-type'
10161 ;; ("open" function called with a single argument).
10162 ;; If no such function is found, fallback to
10163 ;; `org-open-file'.
10164 (let* ((option (org-element-property :search-option context))
10165 (app (org-element-property :application context))
10166 (dedicated-function
10167 (org-link-get-parameter
10168 (if app (concat type "+" app) type)
10169 :follow)))
10170 (if dedicated-function
10171 (funcall dedicated-function
10172 (concat path
10173 (and option (concat "::" option))))
10174 (apply #'org-open-file
10175 path
10176 (cond (arg)
10177 ((equal app "emacs") 'emacs)
10178 ((equal app "sys") 'system))
10179 (cond ((not option) nil)
10180 ((string-match-p "\\`[0-9]+\\'" option)
10181 (list (string-to-number option)))
10182 (t (list nil
10183 (org-link-unescape option)))))))))
10184 ((functionp (org-link-get-parameter type :follow))
10185 (funcall (org-link-get-parameter type :follow) path))
10186 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10187 (unless (run-hook-with-args-until-success
10188 'org-open-link-functions path)
10189 (if (not arg) (org-mark-ring-push)
10190 (switch-to-buffer-other-window
10191 (org-get-buffer-for-internal-link (current-buffer))))
10192 (let ((destination
10193 (org-with-wide-buffer
10194 (if (equal type "radio")
10195 (org-search-radio-target
10196 (org-element-property :path context))
10197 (org-link-search
10198 (if (member type '("custom-id" "coderef"))
10199 (org-element-property :raw-link context)
10200 path)
10201 ;; Prevent fuzzy links from matching
10202 ;; themselves.
10203 (and (equal type "fuzzy")
10204 (+ 2 (org-element-property :begin context)))))
10205 (point))))
10206 (unless (and (<= (point-min) destination)
10207 (>= (point-max) destination))
10208 (widen))
10209 (goto-char destination))))
10210 (t (browse-url-at-point))))))
10211 (t (user-error "No link found")))))
10212 (run-hook-with-args 'org-follow-link-hook)))
10214 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10215 "Offer links in the current entry and return the selected link.
10216 If there is only one link, return it.
10217 If NTH is an integer, return the NTH link found.
10218 If ZERO is a string, check also this string for a link, and if
10219 there is one, return it."
10220 (with-current-buffer buffer
10221 (org-with-wide-buffer
10222 (goto-char marker)
10223 (let ((cnt ?0)
10224 have-zero end links link c)
10225 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10226 (push (match-string 0 zero) links)
10227 (setq cnt (1- cnt) have-zero t))
10228 (save-excursion
10229 (org-back-to-heading t)
10230 (setq end (save-excursion (outline-next-heading) (point)))
10231 (while (re-search-forward org-any-link-re end t)
10232 (push (match-string 0) links))
10233 (setq links (org-uniquify (reverse links))))
10234 (cond
10235 ((null links)
10236 (message "No links"))
10237 ((equal (length links) 1)
10238 (setq link (car links)))
10239 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10240 (setq link (nth (if have-zero nth (1- nth)) links)))
10241 (t ; we have to select a link
10242 (save-excursion
10243 (save-window-excursion
10244 (delete-other-windows)
10245 (with-output-to-temp-buffer "*Select Link*"
10246 (dolist (l links)
10247 (cond
10248 ((not (string-match org-bracket-link-regexp l))
10249 (princ (format "[%c] %s\n" (cl-incf cnt)
10250 (org-unbracket-string "<" ">" l))))
10251 ((match-end 3)
10252 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10253 (match-string 3 l) (match-string 1 l))))
10254 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10255 (match-string 1 l)))))))
10256 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10257 (message "Select link to open, RET to open all:")
10258 (setq c (read-char-exclusive))
10259 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10260 (when (equal c ?q) (user-error "Abort"))
10261 (if (equal c ?\C-m)
10262 (setq link links)
10263 (setq nth (- c ?0))
10264 (when have-zero (setq nth (1+ nth)))
10265 (unless (and (integerp nth) (>= (length links) nth))
10266 (user-error "Invalid link selection"))
10267 (setq link (nth (1- nth) links)))))
10268 (cons link end)))))
10270 ;; TODO: These functions are deprecated since `org-open-at-point'
10271 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10272 (defun org-open-file-with-system (path)
10273 "Open file at PATH using the system way of opening it."
10274 (org-open-file path 'system))
10275 (defun org-open-file-with-emacs (path)
10276 "Open file at PATH in Emacs."
10277 (org-open-file path 'emacs))
10280 ;;; File search
10282 (defvar org-create-file-search-functions nil
10283 "List of functions to construct the right search string for a file link.
10284 These functions are called in turn with point at the location to
10285 which the link should point.
10287 A function in the hook should first test if it would like to
10288 handle this file type, for example by checking the `major-mode'
10289 or the file extension. If it decides not to handle this file, it
10290 should just return nil to give other functions a chance. If it
10291 does handle the file, it must return the search string to be used
10292 when following the link. The search string will be part of the
10293 file link, given after a double colon, and `org-open-at-point'
10294 will automatically search for it. If special measures must be
10295 taken to make the search successful, another function should be
10296 added to the companion hook `org-execute-file-search-functions',
10297 which see.
10299 A function in this hook may also use `setq' to set the variable
10300 `description' to provide a suggestion for the descriptive text to
10301 be used for this link when it gets inserted into an Org buffer
10302 with \\[org-insert-link].")
10304 (defvar org-execute-file-search-functions nil
10305 "List of functions to execute a file search triggered by a link.
10307 Functions added to this hook must accept a single argument, the
10308 search string that was part of the file link, the part after the
10309 double colon. The function must first check if it would like to
10310 handle this search, for example by checking the `major-mode' or
10311 the file extension. If it decides not to handle this search, it
10312 should just return nil to give other functions a chance. If it
10313 does handle the search, it must return a non-nil value to keep
10314 other functions from trying.
10316 Each function can access the current prefix argument through the
10317 variable `current-prefix-arg'. Note that a single prefix is used
10318 to force opening a link in Emacs, so it may be good to only use a
10319 numeric or double prefix to guide the search function.
10321 In case this is needed, a function in this hook can also restore
10322 the window configuration before `org-open-at-point' was called using:
10324 (set-window-configuration org-window-config-before-follow-link)")
10326 (defun org-search-radio-target (target)
10327 "Search a radio target matching TARGET in current buffer.
10328 White spaces are not significant."
10329 (let ((re (format "<<<%s>>>"
10330 (mapconcat #'regexp-quote
10331 (split-string target)
10332 "[ \t]+\\(?:\n[ \t]*\\)?")))
10333 (origin (point)))
10334 (goto-char (point-min))
10335 (catch :radio-match
10336 (while (re-search-forward re nil t)
10337 (backward-char)
10338 (let ((object (org-element-context)))
10339 (when (eq (org-element-type object) 'radio-target)
10340 (goto-char (org-element-property :begin object))
10341 (org-show-context 'link-search)
10342 (throw :radio-match nil))))
10343 (goto-char origin)
10344 (user-error "No match for radio target: %s" target))))
10346 (defun org-link-search (s &optional avoid-pos stealth)
10347 "Search for a search string S.
10349 If S starts with \"#\", it triggers a custom ID search.
10351 If S is enclosed within parenthesis, it initiates a coderef
10352 search.
10354 If S is surrounded by forward slashes, it is interpreted as
10355 a regular expression. In Org mode files, this will create an
10356 `org-occur' sparse tree. In ordinary files, `occur' will be used
10357 to list matches. If the current buffer is in `dired-mode', grep
10358 will be used to search in all files.
10360 When AVOID-POS is given, ignore matches near that position.
10362 When optional argument STEALTH is non-nil, do not modify
10363 visibility around point, thus ignoring `org-show-context-detail'
10364 variable.
10366 Search is case-insensitive and ignores white spaces. Return type
10367 of matched result, which is either `dedicated' or `fuzzy'."
10368 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10369 (let* ((case-fold-search t)
10370 (origin (point))
10371 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10372 (starred (eq (string-to-char normalized) ?*))
10373 (words (split-string (if starred (substring s 1) s)))
10374 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10375 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10376 type)
10377 (cond
10378 ;; Check if there are any special search functions.
10379 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10380 ((eq (string-to-char s) ?#)
10381 ;; Look for a custom ID S if S starts with "#".
10382 (let* ((id (substring normalized 1))
10383 (match (org-find-property "CUSTOM_ID" id)))
10384 (if match (progn (goto-char match) (setf type 'dedicated))
10385 (error "No match for custom ID: %s" id))))
10386 ((string-match "\\`(\\(.*\\))\\'" normalized)
10387 ;; Look for coderef targets if S is enclosed within parenthesis.
10388 (let ((coderef (match-string-no-properties 1 normalized))
10389 (re (substring s-single-re 1 -1)))
10390 (goto-char (point-min))
10391 (catch :coderef-match
10392 (while (re-search-forward re nil t)
10393 (let ((element (org-element-at-point)))
10394 (when (and (memq (org-element-type element)
10395 '(example-block src-block))
10396 ;; Build proper regexp according to current
10397 ;; block's label format.
10398 (let ((label-fmt
10399 (regexp-quote
10400 (or (org-element-property :label-fmt element)
10401 org-coderef-label-format))))
10402 (save-excursion
10403 (beginning-of-line)
10404 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10405 (format label-fmt coderef))))))
10406 (setq type 'dedicated)
10407 (goto-char (match-beginning 1))
10408 (throw :coderef-match nil))))
10409 (goto-char origin)
10410 (error "No match for coderef: %s" coderef))))
10411 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10412 ;; Look for a regular expression.
10413 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10414 (match-string 1 s)))
10415 ;; From here, we handle fuzzy links.
10417 ;; Look for targets, only if not in a headline search.
10418 ((and (not starred)
10419 (let ((target (format "<<%s>>" s-multi-re)))
10420 (catch :target-match
10421 (goto-char (point-min))
10422 (while (re-search-forward target nil t)
10423 (backward-char)
10424 (let ((context (org-element-context)))
10425 (when (eq (org-element-type context) 'target)
10426 (setq type 'dedicated)
10427 (goto-char (org-element-property :begin context))
10428 (throw :target-match t))))
10429 nil))))
10430 ;; Look for elements named after S, only if not in a headline
10431 ;; search.
10432 ((and (not starred)
10433 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10434 (catch :name-match
10435 (goto-char (point-min))
10436 (while (re-search-forward name nil t)
10437 (let ((element (org-element-at-point)))
10438 (when (equal words
10439 (split-string
10440 (org-element-property :name element)))
10441 (setq type 'dedicated)
10442 (beginning-of-line)
10443 (throw :name-match t))))
10444 nil))))
10445 ;; Regular text search. Prefer headlines in Org mode buffers.
10446 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10447 ;; statistics cookies and tags.
10448 ((and (derived-mode-p 'org-mode)
10449 (let ((title-re
10450 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10451 org-outline-regexp-bol
10452 org-comment-string
10453 (mapconcat #'regexp-quote words ".+")))
10454 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10455 (comment-re (eval-when-compile
10456 (format "\\`%s[ \t]+" org-comment-string))))
10457 (goto-char (point-min))
10458 (catch :found
10459 (while (re-search-forward title-re nil t)
10460 (when (equal words
10461 (split-string
10462 (replace-regexp-in-string
10463 cookie-re ""
10464 (replace-regexp-in-string
10465 comment-re "" (org-get-heading t t t)))))
10466 (throw :found t)))
10467 nil)))
10468 (beginning-of-line)
10469 (setq type 'dedicated))
10470 ;; Offer to create non-existent headline depending on
10471 ;; `org-link-search-must-match-exact-headline'.
10472 ((and (derived-mode-p 'org-mode)
10473 (not org-link-search-inhibit-query)
10474 (eq org-link-search-must-match-exact-headline 'query-to-create)
10475 (yes-or-no-p "No match - create this as a new heading? "))
10476 (goto-char (point-max))
10477 (unless (bolp) (newline))
10478 (org-insert-heading nil t t)
10479 (insert s "\n")
10480 (beginning-of-line 0))
10481 ;; Only headlines are looked after. No need to process
10482 ;; further: throw an error.
10483 ((and (derived-mode-p 'org-mode)
10484 (or starred org-link-search-must-match-exact-headline))
10485 (goto-char origin)
10486 (error "No match for fuzzy expression: %s" normalized))
10487 ;; Regular text search.
10488 ((catch :fuzzy-match
10489 (goto-char (point-min))
10490 (while (re-search-forward s-multi-re nil t)
10491 ;; Skip match if it contains AVOID-POS or it is included in
10492 ;; a link with a description but outside the description.
10493 (unless (or (and avoid-pos
10494 (<= (match-beginning 0) avoid-pos)
10495 (> (match-end 0) avoid-pos))
10496 (and (save-match-data
10497 (org-in-regexp org-bracket-link-regexp))
10498 (match-beginning 3)
10499 (or (> (match-beginning 3) (point))
10500 (<= (match-end 3) (point)))
10501 (org-element-lineage
10502 (save-match-data (org-element-context))
10503 '(link) t)))
10504 (goto-char (match-beginning 0))
10505 (setq type 'fuzzy)
10506 (throw :fuzzy-match t)))
10507 nil))
10508 ;; All failed. Throw an error.
10509 (t (goto-char origin)
10510 (error "No match for fuzzy expression: %s" normalized)))
10511 ;; Disclose surroundings of match, if appropriate.
10512 (when (and (derived-mode-p 'org-mode) (not stealth))
10513 (org-show-context 'link-search))
10514 type))
10516 (defun org-get-buffer-for-internal-link (buffer)
10517 "Return a buffer to be used for displaying the link target of internal links."
10518 (cond
10519 ((not org-display-internal-link-with-indirect-buffer)
10520 buffer)
10521 ((string-suffix-p "(Clone)" (buffer-name buffer))
10522 (message "Buffer is already a clone, not making another one")
10523 ;; we also do not modify visibility in this case
10524 buffer)
10525 (t ; make a new indirect buffer for displaying the link
10526 (let* ((bn (buffer-name buffer))
10527 (ibn (concat bn "(Clone)"))
10528 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10529 (with-current-buffer ib (org-overview))
10530 ib))))
10532 (defun org-do-occur (regexp &optional cleanup)
10533 "Call the Emacs command `occur'.
10534 If CLEANUP is non-nil, remove the printout of the regular expression
10535 in the *Occur* buffer. This is useful if the regex is long and not useful
10536 to read."
10537 (occur regexp)
10538 (when cleanup
10539 (let ((cwin (selected-window)) win beg end)
10540 (when (setq win (get-buffer-window "*Occur*"))
10541 (select-window win))
10542 (goto-char (point-min))
10543 (when (re-search-forward "match[a-z]+" nil t)
10544 (setq beg (match-end 0))
10545 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10546 (setq end (1- (match-beginning 0)))))
10547 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10548 (goto-char (point-min))
10549 (select-window cwin))))
10552 ;;; The Mark Ring
10554 (defvar org-mark-ring nil
10555 "Mark ring for positions before jumps in Org mode.")
10557 (defvar org-mark-ring-last-goto nil
10558 "Last position in the mark ring used to go back.")
10560 ;; Fill and close the ring
10561 (setq org-mark-ring nil)
10562 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10564 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10565 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10566 org-mark-ring)
10568 (defun org-mark-ring-push (&optional pos buffer)
10569 "Put the current position into the mark ring and rotate it.
10570 Also push position into the Emacs mark ring. If optional
10571 argument POS and BUFFER are not nil, mark this location instead."
10572 (interactive)
10573 (let ((pos (or pos (point)))
10574 (buffer (or buffer (current-buffer))))
10575 (with-current-buffer buffer
10576 (org-with-point-at pos (push-mark nil t)))
10577 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10578 (move-marker (car org-mark-ring) pos buffer))
10579 (message
10580 (substitute-command-keys
10581 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10583 (defun org-mark-ring-goto (&optional n)
10584 "Jump to the previous position in the mark ring.
10585 With prefix arg N, jump back that many stored positions. When
10586 called several times in succession, walk through the entire ring.
10587 Org mode commands jumping to a different position in the current file,
10588 or to another Org file, automatically push the old position onto the ring."
10589 (interactive "p")
10590 (let (p m)
10591 (if (eq last-command this-command)
10592 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10593 (setq p org-mark-ring))
10594 (setq org-mark-ring-last-goto p)
10595 (setq m (car p))
10596 (pop-to-buffer-same-window (marker-buffer m))
10597 (goto-char m)
10598 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10600 (defun org-add-angle-brackets (s)
10601 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10602 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10605 ;;; Following specific links
10607 (defvar org-agenda-buffer-tmp-name)
10608 (defvar org-agenda-start-on-weekday)
10609 (defun org-follow-timestamp-link ()
10610 "Open an agenda view for the time-stamp date/range at point."
10611 (cond
10612 ((org-at-date-range-p t)
10613 (let ((org-agenda-start-on-weekday)
10614 (t1 (match-string 1))
10615 (t2 (match-string 2)) tt1 tt2)
10616 (setq tt1 (time-to-days (org-time-string-to-time t1))
10617 tt2 (time-to-days (org-time-string-to-time t2)))
10618 (let ((org-agenda-buffer-tmp-name
10619 (format "*Org Agenda(a:%s)"
10620 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10621 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10622 ((org-at-timestamp-p 'lax)
10623 (let ((org-agenda-buffer-tmp-name
10624 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10625 (org-agenda-list nil (time-to-days (org-time-string-to-time
10626 (substring (match-string 1) 0 10)))
10627 1)))
10628 (t (error "This should not happen"))))
10631 ;;; Following file links
10632 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10633 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10634 (declare-function mailcap-mime-info
10635 "mailcap" (string &optional request no-decode))
10636 (defvar org-wait nil)
10637 (defun org-open-file (path &optional in-emacs line search)
10638 "Open the file at PATH.
10639 First, this expands any special file name abbreviations. Then the
10640 configuration variable `org-file-apps' is checked if it contains an
10641 entry for this file type, and if yes, the corresponding command is launched.
10643 If no application is found, Emacs simply visits the file.
10645 With optional prefix argument IN-EMACS, Emacs will visit the file.
10646 With a double \\[universal-argument] \\[universal-argument] \
10647 prefix arg, Org tries to avoid opening in Emacs
10648 and to use an external application to visit the file.
10650 Optional LINE specifies a line to go to, optional SEARCH a string
10651 to search for. If LINE or SEARCH is given, the file will be
10652 opened in Emacs, unless an entry from org-file-apps that makes
10653 use of groups in a regexp matches.
10655 If you want to change the way frames are used when following a
10656 link, please customize `org-link-frame-setup'.
10658 If the file does not exist, an error is thrown."
10659 (let* ((file (if (equal path "")
10660 buffer-file-name
10661 (substitute-in-file-name (expand-file-name path))))
10662 (file-apps (append org-file-apps (org-default-apps)))
10663 (apps (cl-remove-if
10664 'org-file-apps-entry-match-against-dlink-p file-apps))
10665 (apps-dlink (cl-remove-if-not
10666 'org-file-apps-entry-match-against-dlink-p file-apps))
10667 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10668 (dirp (unless remp (file-directory-p file)))
10669 (file (if (and dirp org-open-directory-means-index-dot-org)
10670 (concat (file-name-as-directory file) "index.org")
10671 file))
10672 (a-m-a-p (assq 'auto-mode apps))
10673 (dfile (downcase file))
10674 ;; Reconstruct the original link from the PATH, LINE and
10675 ;; SEARCH args.
10676 (link (cond (line (concat file "::" (number-to-string line)))
10677 (search (concat file "::" search))
10678 (t file)))
10679 (dlink (downcase link))
10680 (ext
10681 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10682 (match-string 1 dfile)))
10683 (save-position-maybe
10684 (let ((old-buffer (current-buffer))
10685 (old-pos (point))
10686 (old-mode major-mode))
10687 (lambda ()
10688 (and (derived-mode-p 'org-mode)
10689 (eq old-mode 'org-mode)
10690 (or (not (eq old-buffer (current-buffer)))
10691 (not (eq old-pos (point))))
10692 (org-mark-ring-push old-pos old-buffer)))))
10693 cmd link-match-data)
10694 (cond
10695 ((member in-emacs '((16) system))
10696 (setq cmd (cdr (assq 'system apps))))
10697 (in-emacs (setq cmd 'emacs))
10699 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10700 (and dirp (cdr (assq 'directory apps)))
10701 ;; First, try matching against apps-dlink if we
10702 ;; get a match here, store the match data for
10703 ;; later.
10704 (let ((match (assoc-default dlink apps-dlink
10705 'string-match)))
10706 (if match
10707 (progn (setq link-match-data (match-data))
10708 match)
10709 (progn (setq in-emacs (or in-emacs line search))
10710 nil))) ; if we have no match in apps-dlink,
10711 ; always open the file in emacs if line or search
10712 ; is given (for backwards compatibility)
10713 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10714 'string-match)
10715 (cdr (assoc ext apps))
10716 (cdr (assq t apps))))))
10717 (when (eq cmd 'system)
10718 (setq cmd (cdr (assq 'system apps))))
10719 (when (eq cmd 'default)
10720 (setq cmd (cdr (assoc t apps))))
10721 (when (eq cmd 'mailcap)
10722 (require 'mailcap)
10723 (mailcap-parse-mailcaps)
10724 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10725 (command (mailcap-mime-info mime-type)))
10726 (if (stringp command)
10727 (setq cmd command)
10728 (setq cmd 'emacs))))
10729 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10730 (not (file-exists-p file))
10731 (not org-open-non-existing-files))
10732 (user-error "No such file: %s" file))
10733 (cond
10734 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10735 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10736 (while (string-match "['\"]%s['\"]" cmd)
10737 (setq cmd (replace-match "%s" t t cmd)))
10738 (setq cmd (replace-regexp-in-string
10739 "%s"
10740 (shell-quote-argument (convert-standard-filename file))
10742 nil t))
10744 ;; Replace "%1", "%2" etc. in command with group matches from regex
10745 (save-match-data
10746 (let ((match-index 1)
10747 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10748 (set-match-data link-match-data)
10749 (while (<= match-index number-of-groups)
10750 (let ((regex (concat "%" (number-to-string match-index)))
10751 (replace-with (match-string match-index dlink)))
10752 (while (string-match regex cmd)
10753 (setq cmd (replace-match replace-with t t cmd))))
10754 (setq match-index (+ match-index 1)))))
10756 (save-window-excursion
10757 (message "Running %s...done" cmd)
10758 (start-process-shell-command cmd nil cmd)
10759 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10760 ((or (stringp cmd)
10761 (eq cmd 'emacs))
10762 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10763 (widen)
10764 (cond (line (org-goto-line line)
10765 (when (derived-mode-p 'org-mode) (org-reveal)))
10766 (search (condition-case err
10767 (org-link-search search)
10768 ;; Save position before error-ing out so user
10769 ;; can easily move back to the original buffer.
10770 (error (funcall save-position-maybe)
10771 (error (nth 1 err)))))))
10772 ((functionp cmd)
10773 (save-match-data
10774 (set-match-data link-match-data)
10775 (condition-case nil
10776 (funcall cmd file link)
10777 ;; FIXME: Remove this check when most default installations
10778 ;; of Emacs have at least Org 9.0.
10779 ((debug wrong-number-of-arguments wrong-type-argument
10780 invalid-function)
10781 (user-error "Please see Org News for version 9.0 about \
10782 `org-file-apps'--Lisp error: %S" cmd)))))
10783 ((consp cmd)
10784 ;; FIXME: Remove this check when most default installations of
10785 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10786 ;; fall back to `org-link-frame-setup' for an old usage of
10787 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10788 (user-error "Please see Org News for version 9.0 about \
10789 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10790 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10791 (funcall save-position-maybe)))
10793 (defun org-file-apps-entry-match-against-dlink-p (entry)
10794 "This function returns non-nil if `entry' uses a regular
10795 expression which should be matched against the whole link by
10796 org-open-file.
10798 It assumes that is the case when the entry uses a regular
10799 expression which has at least one grouping construct and the
10800 action is either a lisp form or a command string containing
10801 `%1', i.e. using at least one subexpression match as a
10802 parameter."
10803 (let ((selector (car entry))
10804 (action (cdr entry)))
10805 (if (stringp selector)
10806 (and (> (regexp-opt-depth selector) 0)
10807 (or (and (stringp action)
10808 (string-match "%[0-9]" action))
10809 (consp action)))
10810 nil)))
10812 (defun org-default-apps ()
10813 "Return the default applications for this operating system."
10814 (cond
10815 ((eq system-type 'darwin)
10816 org-file-apps-defaults-macosx)
10817 ((eq system-type 'windows-nt)
10818 org-file-apps-defaults-windowsnt)
10819 (t org-file-apps-defaults-gnu)))
10821 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10822 "Convert extensions to regular expressions in the cars of LIST.
10823 Also, weed out any non-string entries, because the return value is used
10824 only for regexp matching.
10825 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10826 point to the symbol `emacs', indicating that the file should
10827 be opened in Emacs."
10828 (append
10829 (delq nil
10830 (mapcar (lambda (x)
10831 (unless (not (stringp (car x)))
10832 (if (string-match "\\W" (car x))
10834 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10835 list))
10836 (when add-auto-mode
10837 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10839 (defvar ange-ftp-name-format)
10840 (defun org-file-remote-p (file)
10841 "Test whether FILE specifies a location on a remote system.
10842 Return non-nil if the location is indeed remote.
10844 For example, the filename \"/user@host:/foo\" specifies a location
10845 on the system \"/user@host:\"."
10846 (cond ((fboundp 'file-remote-p)
10847 (file-remote-p file))
10848 ((fboundp 'tramp-handle-file-remote-p)
10849 (tramp-handle-file-remote-p file))
10850 ((and (boundp 'ange-ftp-name-format)
10851 (string-match (car ange-ftp-name-format) file))
10852 t)))
10855 ;;;; Refiling
10857 (defun org-get-org-file ()
10858 "Read a filename, with default directory `org-directory'."
10859 (let ((default (or org-default-notes-file remember-data-file)))
10860 (read-file-name (format "File name [%s]: " default)
10861 (file-name-as-directory org-directory)
10862 default)))
10864 (defun org-notes-order-reversed-p ()
10865 "Check if the current file should receive notes in reversed order."
10866 (cond
10867 ((not org-reverse-note-order) nil)
10868 ((eq t org-reverse-note-order) t)
10869 ((not (listp org-reverse-note-order)) nil)
10870 (t (catch 'exit
10871 (dolist (entry org-reverse-note-order)
10872 (when (string-match (car entry) buffer-file-name)
10873 (throw 'exit (cdr entry))))))))
10875 (defvar org-refile-target-table nil
10876 "The list of refile targets, created by `org-refile'.")
10878 (defvar org-agenda-new-buffers nil
10879 "Buffers created to visit agenda files.")
10881 (defvar org-refile-cache nil
10882 "Cache for refile targets.")
10884 (defvar org-refile-markers nil
10885 "All the markers used for caching refile locations.")
10887 (defun org-refile-marker (pos)
10888 "Get a new refile marker, but only if caching is in use."
10889 (if (not org-refile-use-cache)
10891 (let ((m (make-marker)))
10892 (move-marker m pos)
10893 (push m org-refile-markers)
10894 m)))
10896 (defun org-refile-cache-clear ()
10897 "Clear the refile cache and disable all the markers."
10898 (dolist (m org-refile-markers) (move-marker m nil))
10899 (setq org-refile-markers nil)
10900 (setq org-refile-cache nil)
10901 (message "Refile cache has been cleared"))
10903 (defun org-refile-cache-check-set (set)
10904 "Check if all the markers in the cache still have live buffers."
10905 (let (marker)
10906 (catch 'exit
10907 (while (and set (setq marker (nth 3 (pop set))))
10908 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10909 (when (and marker (null (marker-buffer marker)))
10910 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10911 (sit-for 3)
10912 (throw 'exit nil)))
10913 t)))
10915 (defun org-refile-cache-put (set &rest identifiers)
10916 "Push the refile targets SET into the cache, under IDENTIFIERS."
10917 (let* ((key (sha1 (prin1-to-string identifiers)))
10918 (entry (assoc key org-refile-cache)))
10919 (if entry
10920 (setcdr entry set)
10921 (push (cons key set) org-refile-cache))))
10923 (defun org-refile-cache-get (&rest identifiers)
10924 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10925 (cond
10926 ((not org-refile-cache) nil)
10927 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10929 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10930 org-refile-cache))))
10931 (and set (org-refile-cache-check-set set) set)))))
10933 (defvar org-outline-path-cache nil
10934 "Alist between buffer positions and outline paths.
10935 It value is an alist (POSITION . PATH) where POSITION is the
10936 buffer position at the beginning of an entry and PATH is a list
10937 of strings describing the outline path for that entry, in reverse
10938 order.")
10940 (defun org-refile-get-targets (&optional default-buffer)
10941 "Produce a table with refile targets."
10942 (let ((case-fold-search nil)
10943 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10944 (entries (or org-refile-targets '((nil . (:level . 1)))))
10945 targets tgs files desc descre)
10946 (message "Getting targets...")
10947 (with-current-buffer (or default-buffer (current-buffer))
10948 (dolist (entry entries)
10949 (setq files (car entry) desc (cdr entry))
10950 (cond
10951 ((null files) (setq files (list (current-buffer))))
10952 ((eq files 'org-agenda-files)
10953 (setq files (org-agenda-files 'unrestricted)))
10954 ((and (symbolp files) (fboundp files))
10955 (setq files (funcall files)))
10956 ((and (symbolp files) (boundp files))
10957 (setq files (symbol-value files))))
10958 (when (stringp files) (setq files (list files)))
10959 (cond
10960 ((eq (car desc) :tag)
10961 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10962 ((eq (car desc) :todo)
10963 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10964 ((eq (car desc) :regexp)
10965 (setq descre (cdr desc)))
10966 ((eq (car desc) :level)
10967 (setq descre (concat "^\\*\\{" (number-to-string
10968 (if org-odd-levels-only
10969 (1- (* 2 (cdr desc)))
10970 (cdr desc)))
10971 "\\}[ \t]")))
10972 ((eq (car desc) :maxlevel)
10973 (setq descre (concat "^\\*\\{1," (number-to-string
10974 (if org-odd-levels-only
10975 (1- (* 2 (cdr desc)))
10976 (cdr desc)))
10977 "\\}[ \t]")))
10978 (t (error "Bad refiling target description %s" desc)))
10979 (dolist (f files)
10980 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10982 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10983 (progn
10984 (when (bufferp f)
10985 (setq f (buffer-file-name (buffer-base-buffer f))))
10986 (setq f (and f (expand-file-name f)))
10987 (when (eq org-refile-use-outline-path 'file)
10988 (push (list (file-name-nondirectory f) f nil nil) tgs))
10989 (when (eq org-refile-use-outline-path 'buffer-name)
10990 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10991 (when (eq org-refile-use-outline-path 'full-file-path)
10992 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10993 (org-with-wide-buffer
10994 (goto-char (point-min))
10995 (setq org-outline-path-cache nil)
10996 (while (re-search-forward descre nil t)
10997 (beginning-of-line)
10998 (let ((case-fold-search nil))
10999 (looking-at org-complex-heading-regexp))
11000 (let ((begin (point))
11001 (heading (match-string-no-properties 4)))
11002 (unless (or (and
11003 org-refile-target-verify-function
11004 (not
11005 (funcall org-refile-target-verify-function)))
11006 (not heading))
11007 (let ((re (format org-complex-heading-regexp-format
11008 (regexp-quote heading)))
11009 (target
11010 (if (not org-refile-use-outline-path) heading
11011 (mapconcat
11012 #'identity
11013 (append
11014 (pcase org-refile-use-outline-path
11015 (`file (list (file-name-nondirectory
11016 (buffer-file-name
11017 (buffer-base-buffer)))))
11018 (`full-file-path
11019 (list (buffer-file-name
11020 (buffer-base-buffer))))
11021 (`buffer-name
11022 (list (buffer-name
11023 (buffer-base-buffer))))
11024 (_ nil))
11025 (mapcar (lambda (s) (replace-regexp-in-string
11026 "/" "\\/" s nil t))
11027 (org-get-outline-path t t)))
11028 "/"))))
11029 (push (list target f re (org-refile-marker (point)))
11030 tgs)))
11031 (when (= (point) begin)
11032 ;; Verification function has not moved point.
11033 (end-of-line)))))))
11034 (when org-refile-use-cache
11035 (org-refile-cache-put tgs (buffer-file-name) descre))
11036 (setq targets (append tgs targets))))))
11037 (message "Getting targets...done")
11038 (delete-dups (nreverse targets))))
11040 (defun org--get-outline-path-1 (&optional use-cache)
11041 "Return outline path to current headline.
11043 Outline path is a list of strings, in reverse order. When
11044 optional argument USE-CACHE is non-nil, make use of a cache. See
11045 `org-get-outline-path' for details.
11047 Assume buffer is widened and point is on a headline."
11048 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11049 (let ((p (point))
11050 (heading (let ((case-fold-search nil))
11051 (looking-at org-complex-heading-regexp)
11052 (if (not (match-end 4)) ""
11053 ;; Remove statistics cookies.
11054 (org-trim
11055 (org-link-display-format
11056 (replace-regexp-in-string
11057 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11058 (match-string-no-properties 4))))))))
11059 (if (org-up-heading-safe)
11060 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11061 (when use-cache
11062 (push (cons p path) org-outline-path-cache))
11063 path)
11064 ;; This is a new root node. Since we assume we are moving
11065 ;; forward, we can drop previous cache so as to limit number
11066 ;; of associations there.
11067 (let ((path (list heading)))
11068 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11069 path)))))
11071 (defun org-get-outline-path (&optional with-self use-cache)
11072 "Return the outline path to the current entry.
11074 An outline path is a list of ancestors for current headline, as
11075 a list of strings. Statistics cookies are removed and links are
11076 replaced with their description, if any, or their path otherwise.
11078 When optional argument WITH-SELF is non-nil, the path also
11079 includes the current headline.
11081 When optional argument USE-CACHE is non-nil, cache outline paths
11082 between calls to this function so as to avoid backtracking. This
11083 argument is useful when planning to find more than one outline
11084 path in the same document. In that case, there are two
11085 conditions to satisfy:
11086 - `org-outline-path-cache' is set to nil before starting the
11087 process;
11088 - outline paths are computed by increasing buffer positions."
11089 (org-with-wide-buffer
11090 (and (or (and with-self (org-back-to-heading t))
11091 (org-up-heading-safe))
11092 (reverse (org--get-outline-path-1 use-cache)))))
11094 (defun org-format-outline-path (path &optional width prefix separator)
11095 "Format the outline path PATH for display.
11096 WIDTH is the maximum number of characters that is available.
11097 PREFIX is a prefix to be included in the returned string,
11098 such as the file name.
11099 SEPARATOR is inserted between the different parts of the path,
11100 the default is \"/\"."
11101 (setq width (or width 79))
11102 (setq path (delq nil path))
11103 (unless (> width 0)
11104 (user-error "Argument `width' must be positive"))
11105 (setq separator (or separator "/"))
11106 (let* ((org-odd-levels-only nil)
11107 (fpath (concat
11108 prefix (and prefix path separator)
11109 (mapconcat
11110 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11111 (cl-loop for head in path
11112 for n from 0
11113 collect (org-add-props
11114 head nil 'face
11115 (nth (% n org-n-level-faces) org-level-faces)))
11116 separator))))
11117 (when (> (length fpath) width)
11118 (if (< width 7)
11119 ;; It's unlikely that `width' will be this small, but don't
11120 ;; waste characters by adding ".." if it is.
11121 (setq fpath (substring fpath 0 width))
11122 (setf (substring fpath (- width 2)) "..")))
11123 fpath))
11125 (defun org-display-outline-path (&optional file current separator just-return-string)
11126 "Display the current outline path in the echo area.
11128 If FILE is non-nil, prepend the output with the file name.
11129 If CURRENT is non-nil, append the current heading to the output.
11130 SEPARATOR is passed through to `org-format-outline-path'. It separates
11131 the different parts of the path and defaults to \"/\".
11132 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11133 (interactive "P")
11134 (let* (case-fold-search
11135 (bfn (buffer-file-name (buffer-base-buffer)))
11136 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11137 res)
11138 (when current (setq path (append path
11139 (save-excursion
11140 (org-back-to-heading t)
11141 (when (looking-at org-complex-heading-regexp)
11142 (list (match-string 4)))))))
11143 (setq res
11144 (org-format-outline-path
11145 path
11146 (1- (frame-width))
11147 (and file bfn (concat (file-name-nondirectory bfn) separator))
11148 separator))
11149 (if just-return-string
11150 (org-no-properties res)
11151 (org-unlogged-message "%s" res))))
11153 (defvar org-refile-history nil
11154 "History for refiling operations.")
11156 (defvar org-after-refile-insert-hook nil
11157 "Hook run after `org-refile' has inserted its stuff at the new location.
11158 Note that this is still *before* the stuff will be removed from
11159 the *old* location.")
11161 (defvar org-capture-last-stored-marker)
11162 (defvar org-refile-keep nil
11163 "Non-nil means `org-refile' will copy instead of refile.")
11165 (defun org-copy ()
11166 "Like `org-refile', but copy."
11167 (interactive)
11168 (let ((org-refile-keep t))
11169 (funcall 'org-refile nil nil nil "Copy")))
11171 (defun org-refile (&optional arg default-buffer rfloc msg)
11172 "Move the entry or entries at point to another heading.
11174 The list of target headings is compiled using the information in
11175 `org-refile-targets', which see.
11177 At the target location, the entry is filed as a subitem of the
11178 target heading. Depending on `org-reverse-note-order', the new
11179 subitem will either be the first or the last subitem.
11181 If there is an active region, all entries in that region will be
11182 refiled. However, the region must fulfill the requirement that
11183 the first heading sets the top-level of the moved text.
11185 With a `\\[universal-argument]' ARG, the command will only visit the target \
11186 location
11187 and not actually move anything.
11189 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11190 location where the last
11191 refiling operation has put the subtree.
11193 With a numeric prefix argument of `2', refile to the running clock.
11195 With a numeric prefix argument of `3', emulate `org-refile-keep'
11196 being set to t and copy to the target location, don't move it.
11197 Beware that keeping refiled entries may result in duplicated ID
11198 properties.
11200 RFLOC can be a refile location obtained in a different way.
11202 MSG is a string to replace \"Refile\" in the default prompt with
11203 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11205 See also `org-refile-use-outline-path'.
11207 If you are using target caching (see `org-refile-use-cache'), you
11208 have to clear the target cache in order to find new targets.
11209 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11210 prefix argument (`C-u C-u C-u C-c C-w')."
11211 (interactive "P")
11212 (if (member arg '(0 (64)))
11213 (org-refile-cache-clear)
11214 (let* ((actionmsg (cond (msg msg)
11215 ((equal arg 3) "Refile (and keep)")
11216 (t "Refile")))
11217 (regionp (org-region-active-p))
11218 (region-start (and regionp (region-beginning)))
11219 (region-end (and regionp (region-end)))
11220 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11221 pos it nbuf file level reversed)
11222 (setq last-command nil)
11223 (when regionp
11224 (goto-char region-start)
11225 (or (bolp) (goto-char (point-at-bol)))
11226 (setq region-start (point))
11227 (unless (or (org-kill-is-subtree-p
11228 (buffer-substring region-start region-end))
11229 (prog1 org-refile-active-region-within-subtree
11230 (let ((s (point-at-eol)))
11231 (org-toggle-heading)
11232 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11233 (user-error "The region is not a (sequence of) subtree(s)")))
11234 (if (equal arg '(16))
11235 (org-refile-goto-last-stored)
11236 (when (or
11237 (and (equal arg 2)
11238 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11239 (prog1
11240 (setq it (list (or org-clock-heading "running clock")
11241 (buffer-file-name
11242 (marker-buffer org-clock-hd-marker))
11244 (marker-position org-clock-hd-marker)))
11245 (setq arg nil)))
11246 (setq it
11247 (or rfloc
11248 (let (heading-text)
11249 (save-excursion
11250 (unless (and arg (listp arg))
11251 (org-back-to-heading t)
11252 (setq heading-text
11253 (replace-regexp-in-string
11254 org-bracket-link-regexp
11255 "\\3"
11256 (or (nth 4 (org-heading-components))
11257 ""))))
11258 (org-refile-get-location
11259 (cond ((and arg (listp arg)) "Goto")
11260 (regionp (concat actionmsg " region to"))
11261 (t (concat actionmsg " subtree \""
11262 heading-text "\" to")))
11263 default-buffer
11264 (and (not (equal '(4) arg))
11265 org-refile-allow-creating-parent-nodes)))))))
11266 (setq file (nth 1 it)
11267 pos (nth 3 it))
11268 (when (and (not arg)
11270 (equal (buffer-file-name) file)
11271 (if regionp
11272 (and (>= pos region-start)
11273 (<= pos region-end))
11274 (and (>= pos (point))
11275 (< pos (save-excursion
11276 (org-end-of-subtree t t))))))
11277 (error "Cannot refile to position inside the tree or region"))
11278 (setq nbuf (or (find-buffer-visiting file)
11279 (find-file-noselect file)))
11280 (if (and arg (not (equal arg 3)))
11281 (progn
11282 (pop-to-buffer-same-window nbuf)
11283 (goto-char (cond (pos)
11284 ((org-notes-order-reversed-p) (point-min))
11285 (t (point-max))))
11286 (org-show-context 'org-goto))
11287 (if regionp
11288 (progn
11289 (org-kill-new (buffer-substring region-start region-end))
11290 (org-save-markers-in-region region-start region-end))
11291 (org-copy-subtree 1 nil t))
11292 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11293 (find-file-noselect file)))
11294 (setq reversed (org-notes-order-reversed-p))
11295 (org-with-wide-buffer
11296 (if pos
11297 (progn
11298 (goto-char pos)
11299 (setq level (org-get-valid-level (funcall outline-level) 1))
11300 (goto-char
11301 (if reversed
11302 (or (outline-next-heading) (point-max))
11303 (or (save-excursion (org-get-next-sibling))
11304 (org-end-of-subtree t t)
11305 (point-max)))))
11306 (setq level 1)
11307 (if (not reversed)
11308 (goto-char (point-max))
11309 (goto-char (point-min))
11310 (or (outline-next-heading) (goto-char (point-max)))))
11311 (unless (bolp) (newline))
11312 (org-paste-subtree level nil nil t)
11313 (when org-log-refile
11314 (org-add-log-setup 'refile nil nil org-log-refile)
11315 (unless (eq org-log-refile 'note)
11316 (save-excursion (org-add-log-note))))
11317 (and org-auto-align-tags
11318 (let ((org-loop-over-headlines-in-active-region nil))
11319 (org-align-tags)))
11320 (let ((bookmark-name (plist-get org-bookmark-names-plist
11321 :last-refile)))
11322 (when bookmark-name
11323 (with-demoted-errors
11324 (bookmark-set bookmark-name))))
11325 ;; If we are refiling for capture, make sure that the
11326 ;; last-capture pointers point here
11327 (when (bound-and-true-p org-capture-is-refiling)
11328 (let ((bookmark-name (plist-get org-bookmark-names-plist
11329 :last-capture-marker)))
11330 (when bookmark-name
11331 (with-demoted-errors
11332 (bookmark-set bookmark-name))))
11333 (move-marker org-capture-last-stored-marker (point)))
11334 (when (fboundp 'deactivate-mark) (deactivate-mark))
11335 (run-hooks 'org-after-refile-insert-hook)))
11336 (unless org-refile-keep
11337 (if regionp
11338 (delete-region (point) (+ (point) (- region-end region-start)))
11339 (org-preserve-local-variables
11340 (delete-region
11341 (and (org-back-to-heading t) (point))
11342 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11343 (when (featurep 'org-inlinetask)
11344 (org-inlinetask-remove-END-maybe))
11345 (setq org-markers-to-move nil)
11346 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11348 (defun org-refile-goto-last-stored ()
11349 "Go to the location where the last refile was stored."
11350 (interactive)
11351 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11352 (message "This is the location of the last refile"))
11354 (defun org-refile--get-location (refloc tbl)
11355 "When user refile to REFLOC, find the associated target in TBL.
11356 Also check `org-refile-target-table'."
11357 (car (delq
11359 (mapcar
11360 (lambda (r) (or (assoc r tbl)
11361 (assoc r org-refile-target-table)))
11362 (list (replace-regexp-in-string "/$" "" refloc)
11363 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11365 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11366 "Prompt the user for a refile location, using PROMPT.
11367 PROMPT should not be suffixed with a colon and a space, because
11368 this function appends the default value from
11369 `org-refile-history' automatically, if that is not empty."
11370 (let ((org-refile-targets org-refile-targets)
11371 (org-refile-use-outline-path org-refile-use-outline-path))
11372 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11373 (unless org-refile-target-table
11374 (user-error "No refile targets"))
11375 (let* ((cbuf (current-buffer))
11376 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11377 (cfunc (if (and org-refile-use-outline-path
11378 org-outline-path-complete-in-steps)
11379 #'org-olpath-completing-read
11380 #'completing-read))
11381 (extra (if org-refile-use-outline-path "/" ""))
11382 (cbnex (concat (buffer-name) extra))
11383 (filename (and cfn (expand-file-name cfn)))
11384 (tbl (mapcar
11385 (lambda (x)
11386 (if (and (not (member org-refile-use-outline-path
11387 '(file full-file-path)))
11388 (not (equal filename (nth 1 x))))
11389 (cons (concat (car x) extra " ("
11390 (file-name-nondirectory (nth 1 x)) ")")
11391 (cdr x))
11392 (cons (concat (car x) extra) (cdr x))))
11393 org-refile-target-table))
11394 (completion-ignore-case t)
11395 cdef
11396 (prompt (concat prompt
11397 (or (and (car org-refile-history)
11398 (concat " (default " (car org-refile-history) ")"))
11399 (and (assoc cbnex tbl) (setq cdef cbnex)
11400 (concat " (default " cbnex ")"))) ": "))
11401 pa answ parent-target child parent old-hist)
11402 (setq old-hist org-refile-history)
11403 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11404 nil 'org-refile-history (or cdef (car org-refile-history))))
11405 (if (setq pa (org-refile--get-location answ tbl))
11406 (progn
11407 (org-refile-check-position pa)
11408 (when (or (not org-refile-history)
11409 (not (eq old-hist org-refile-history))
11410 (not (equal (car pa) (car org-refile-history))))
11411 (setq org-refile-history
11412 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11413 org-refile-history
11414 (cdr org-refile-history))))
11415 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11416 (pop org-refile-history)))
11418 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11419 (progn
11420 (setq parent (match-string 1 answ)
11421 child (match-string 2 answ))
11422 (setq parent-target (org-refile--get-location parent tbl))
11423 (when (and parent-target
11424 (or (eq new-nodes t)
11425 (and (eq new-nodes 'confirm)
11426 (y-or-n-p (format "Create new node \"%s\"? "
11427 child)))))
11428 (org-refile-new-child parent-target child)))
11429 (user-error "Invalid target location")))))
11431 (declare-function org-string-nw-p "org-macs" (s))
11432 (defun org-refile-check-position (refile-pointer)
11433 "Check if the refile pointer matches the headline to which it points."
11434 (let* ((file (nth 1 refile-pointer))
11435 (re (nth 2 refile-pointer))
11436 (pos (nth 3 refile-pointer))
11437 buffer)
11438 (if (and (not (markerp pos)) (not file))
11439 (user-error "Please indicate a target file in the refile path")
11440 (when (org-string-nw-p re)
11441 (setq buffer (if (markerp pos)
11442 (marker-buffer pos)
11443 (or (find-buffer-visiting file)
11444 (find-file-noselect file))))
11445 (with-current-buffer buffer
11446 (org-with-wide-buffer
11447 (goto-char pos)
11448 (beginning-of-line 1)
11449 (unless (looking-at-p re)
11450 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11452 (defun org-refile-new-child (parent-target child)
11453 "Use refile target PARENT-TARGET to add new CHILD below it."
11454 (unless parent-target
11455 (error "Cannot find parent for new node"))
11456 (let ((file (nth 1 parent-target))
11457 (pos (nth 3 parent-target))
11458 level)
11459 (with-current-buffer (or (find-buffer-visiting file)
11460 (find-file-noselect file))
11461 (org-with-wide-buffer
11462 (if pos
11463 (goto-char pos)
11464 (goto-char (point-max))
11465 (unless (bolp) (newline)))
11466 (when (looking-at org-outline-regexp)
11467 (setq level (funcall outline-level))
11468 (org-end-of-subtree t t))
11469 (org-back-over-empty-lines)
11470 (insert "\n" (make-string
11471 (if pos (org-get-valid-level level 1) 1) ?*)
11472 " " child "\n")
11473 (beginning-of-line 0)
11474 (list (concat (car parent-target) "/" child) file "" (point))))))
11476 (defun org-olpath-completing-read (prompt collection &rest args)
11477 "Read an outline path like a file name."
11478 (let ((thetable collection))
11479 (apply #'completing-read
11480 prompt
11481 (lambda (string predicate &optional flag)
11482 (cond
11483 ((eq flag nil) (try-completion string thetable))
11484 ((eq flag t)
11485 (let ((l (length string)))
11486 (mapcar (lambda (x)
11487 (let ((r (substring x l))
11488 (f (if (string-match " ([^)]*)$" x)
11489 (match-string 0 x)
11490 "")))
11491 (if (string-match "/" r)
11492 (concat string (substring r 0 (match-end 0)) f)
11493 x)))
11494 (all-completions string thetable predicate))))
11495 ;; Exact match?
11496 ((eq flag 'lambda) (assoc string thetable))))
11497 args)))
11499 ;;;; Dynamic blocks
11501 (defun org-find-dblock (name)
11502 "Find the first dynamic block with name NAME in the buffer.
11503 If not found, stay at current position and return nil."
11504 (let ((case-fold-search t) pos)
11505 (save-excursion
11506 (goto-char (point-min))
11507 (setq pos (and (re-search-forward
11508 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11509 (match-beginning 0))))
11510 (when pos (goto-char pos))
11511 pos))
11513 (defun org-create-dblock (plist)
11514 "Create a dynamic block section, with parameters taken from PLIST.
11515 PLIST must contain a :name entry which is used as the name of the block."
11516 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11517 (end-of-line 1)
11518 (newline))
11519 (let ((col (current-column))
11520 (name (plist-get plist :name)))
11521 (insert "#+BEGIN: " name)
11522 (while plist
11523 (if (eq (car plist) :name)
11524 (setq plist (cddr plist))
11525 (insert " " (prin1-to-string (pop plist)))))
11526 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11527 (beginning-of-line -2)))
11529 (defun org-prepare-dblock ()
11530 "Prepare dynamic block for refresh.
11531 This empties the block, puts the cursor at the insert position and returns
11532 the property list including an extra property :name with the block name."
11533 (unless (looking-at org-dblock-start-re)
11534 (user-error "Not at a dynamic block"))
11535 (let* ((begdel (1+ (match-end 0)))
11536 (name (org-no-properties (match-string 1)))
11537 (params (append (list :name name)
11538 (read (concat "(" (match-string 3) ")")))))
11539 (save-excursion
11540 (beginning-of-line 1)
11541 (skip-chars-forward " \t")
11542 (setq params (plist-put params :indentation-column (current-column))))
11543 (unless (re-search-forward org-dblock-end-re nil t)
11544 (error "Dynamic block not terminated"))
11545 (setq params
11546 (append params
11547 (list :content (buffer-substring
11548 begdel (match-beginning 0)))))
11549 (delete-region begdel (match-beginning 0))
11550 (goto-char begdel)
11551 (open-line 1)
11552 params))
11554 (defun org-map-dblocks (&optional command)
11555 "Apply COMMAND to all dynamic blocks in the current buffer.
11556 If COMMAND is not given, use `org-update-dblock'."
11557 (let ((cmd (or command 'org-update-dblock)))
11558 (save-excursion
11559 (goto-char (point-min))
11560 (while (re-search-forward org-dblock-start-re nil t)
11561 (goto-char (match-beginning 0))
11562 (save-excursion
11563 (condition-case nil
11564 (funcall cmd)
11565 (error (message "Error during update of dynamic block"))))
11566 (unless (re-search-forward org-dblock-end-re nil t)
11567 (error "Dynamic block not terminated"))))))
11569 (defun org-dblock-update (&optional arg)
11570 "User command for updating dynamic blocks.
11571 Update the dynamic block at point. With prefix ARG, update all dynamic
11572 blocks in the buffer."
11573 (interactive "P")
11574 (if arg
11575 (org-update-all-dblocks)
11576 (or (looking-at org-dblock-start-re)
11577 (org-beginning-of-dblock))
11578 (org-update-dblock)))
11580 (defun org-update-dblock ()
11581 "Update the dynamic block at point.
11582 This means to empty the block, parse for parameters and then call
11583 the correct writing function."
11584 (interactive)
11585 (save-excursion
11586 (let* ((win (selected-window))
11587 (pos (point))
11588 (line (org-current-line))
11589 (params (org-prepare-dblock))
11590 (name (plist-get params :name))
11591 (indent (plist-get params :indentation-column))
11592 (cmd (intern (concat "org-dblock-write:" name))))
11593 (message "Updating dynamic block `%s' at line %d..." name line)
11594 (funcall cmd params)
11595 (message "Updating dynamic block `%s' at line %d...done" name line)
11596 (goto-char pos)
11597 (when (and indent (> indent 0))
11598 (setq indent (make-string indent ?\ ))
11599 (save-excursion
11600 (select-window win)
11601 (org-beginning-of-dblock)
11602 (forward-line 1)
11603 (while (not (looking-at org-dblock-end-re))
11604 (insert indent)
11605 (beginning-of-line 2))
11606 (when (looking-at org-dblock-end-re)
11607 (and (looking-at "[ \t]+")
11608 (replace-match ""))
11609 (insert indent)))))))
11611 (defun org-beginning-of-dblock ()
11612 "Find the beginning of the dynamic block at point.
11613 Error if there is no such block at point."
11614 (let ((pos (point))
11615 beg)
11616 (end-of-line 1)
11617 (if (and (re-search-backward org-dblock-start-re nil t)
11618 (setq beg (match-beginning 0))
11619 (re-search-forward org-dblock-end-re nil t)
11620 (> (match-end 0) pos))
11621 (goto-char beg)
11622 (goto-char pos)
11623 (error "Not in a dynamic block"))))
11625 (defun org-update-all-dblocks ()
11626 "Update all dynamic blocks in the buffer.
11627 This function can be used in a hook."
11628 (interactive)
11629 (when (derived-mode-p 'org-mode)
11630 (org-map-dblocks 'org-update-dblock)))
11633 ;;;; Completion
11635 (declare-function org-export-backend-options "ox" (cl-x) t)
11636 (defun org-get-export-keywords ()
11637 "Return a list of all currently understood export keywords.
11638 Export keywords include options, block names, attributes and
11639 keywords relative to each registered export back-end."
11640 (let (keywords)
11641 (dolist (backend
11642 (bound-and-true-p org-export-registered-backends)
11643 (delq nil keywords))
11644 ;; Back-end name (for keywords, like #+LATEX:)
11645 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11646 (dolist (option-entry (org-export-backend-options backend))
11647 ;; Back-end options.
11648 (push (nth 1 option-entry) keywords)))))
11650 (defconst org-options-keywords
11651 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11652 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11653 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11654 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11655 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11657 (defcustom org-structure-template-alist
11658 '(("a" . "export ascii")
11659 ("c" . "center")
11660 ("C" . "comment")
11661 ("e" . "example")
11662 ("E" . "export")
11663 ("h" . "export html")
11664 ("l" . "export latex")
11665 ("q" . "quote")
11666 ("s" . "src")
11667 ("v" . "verse"))
11668 "Structure completion elements.
11669 This is an alist of keys and block types. With
11670 `org-insert-structure-template' a block can be inserted through a
11671 menu. The block type is inserted, with \"#+BEGIN_\" and
11672 \"#+END_\" added automatically. The menukeys are determined
11673 based on the key elements in the `org-structure-template-alist'.
11674 If two entries have the keys \"a\" and \"aa\" respectively, the
11675 former will be inserted by typing \"a TAB/RET/SPC\" and the
11676 latter will be inserted by typing \"aa\". If an entry with the
11677 key \"aab\" is later added it would be inserted by typing \"ab\".
11679 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11680 block can be inserted by pressing TAB after the string \"<KEY\".
11682 :group 'org-edit-structure
11683 :type '(repeat
11684 (cons (string :tag "Key")
11685 (string :tag "Template")))
11686 :package-version '(Org . "9.2"))
11688 (defun org--insert-structure-template-mks ()
11689 "Present `org-structure-template-alist' with `org-mks'.
11691 Menus are added if keys require more than one keystroke.
11692 Tabs are added to single key entires when needing more than one stroke.
11693 Keys longer than two characters are reduced to two characters."
11694 (let* (case-fold-search
11695 (templates (append org-structure-template-alist
11696 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11697 (keys (mapcar #'car templates))
11698 (start-letters (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11699 ;; Sort each element of `org-structure-template-alist' into
11700 ;; sublists according to the first letter.
11701 (superlist (mapcar (lambda (letter)
11702 (list letter
11703 (cl-remove-if-not
11704 (apply-partially #'string-match-p (concat "^" letter))
11705 templates :key #'car)))
11706 start-letters)))
11707 (org-mks
11708 (apply #'append
11709 ;; Make an `org-mks' table. If only one element is
11710 ;; present in a sublist, make it part of the top-menu,
11711 ;; otherwise make a submenu according to the starting
11712 ;; letter and populate it.
11713 (mapcar (lambda (sublist)
11714 (if (eq 1 (length (cadr sublist)))
11715 (mapcar (lambda (elm)
11716 (list (substring (car elm) 0 1)
11717 (cdr elm) ""))
11718 (cadr sublist))
11719 ;; Create submenu.
11720 (let* ((topkey (car sublist))
11721 (elms (cadr sublist))
11722 (keys (mapcar #'car elms))
11723 (long (> (length elms) 3)))
11724 (append
11725 (list
11726 ;; Make a description of the submenu.
11727 (list topkey
11728 (concat
11729 (mapconcat #'cdr
11730 (cl-subseq elms 0 (if long 3 (length elms)))
11731 ", ")
11732 (when long ", ..."))))
11733 ;; List of entries in submenu.
11734 (cl-mapcar #'list
11735 (org--insert-structure-template-unique-keys keys)
11736 (mapcar #'cdr elms)
11737 (make-list (length elms) ""))))))
11738 superlist))
11739 "Select a key\n============"
11740 "Key: ")))
11742 (defun org--insert-structure-template-unique-keys (keys)
11743 "Make list of unique, two character long elements from KEYS.
11745 Elements of length one have a tab appended. Elements of length
11746 two are kept as is. Longer elements are truncated to length two.
11748 If an element cannot be made unique an error is raised."
11749 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11750 menu-keys)
11751 (dolist (key orderd-keys)
11752 (let ((potential-key
11753 (cl-case (length key)
11754 (1 (concat key "\t"))
11755 (2 key)
11756 (otherwise
11757 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11758 (mapcar (apply-partially #'concat (substring key 0 1))
11759 (split-string (substring key 1) "" t)))))))
11760 (if (or (not potential-key) (assoc potential-key menu-keys))
11761 (user-error "Could not make unique key for %s." key)
11762 (push (cons potential-key key) menu-keys))))
11763 (mapcar #'car
11764 (cl-sort menu-keys #'<
11765 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11767 (defun org-insert-structure-template (type)
11768 "Insert a block structure of the type #+begin_foo/#+end_foo.
11769 First choose a block based on `org-structure-template-alist'.
11770 Alternatively, type RET, TAB or SPC to write the block type.
11771 With an active region, wrap the region in the block. Otherwise,
11772 insert an empty block."
11773 (interactive
11774 (list (pcase (org--insert-structure-template-mks)
11775 (`("\t" . ,_) (read-string "Structure type: "))
11776 (`(,_ ,choice . ,_) choice))))
11777 (let* ((region? (use-region-p))
11778 (col (current-indentation))
11779 (indent (make-string col ?\s))
11780 (special? (string-match-p "\\(src\\|export\\)\\'" type))
11781 (region-string (and region?
11782 (buffer-substring (region-beginning)
11783 (region-end))))
11784 (region-end-blank (and region?
11785 (save-excursion
11786 (goto-char (region-end))
11787 (when (looking-at "[ \t]*$")
11788 (replace-match "")
11789 t))))
11791 (when region? (delete-region (region-beginning) (region-end)))
11792 (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
11793 (insert "\n"))
11794 (beginning-of-line)
11795 (save-excursion
11796 (insert
11797 (with-temp-buffer
11798 (when region?
11799 (insert region-string "\n")
11800 (when (string-match-p
11801 (concat "\\`" (regexp-opt '("example" "export" "src")))
11802 type)
11803 (org-escape-code-in-region (point-min) (point-max))))
11804 (goto-char (point-min))
11805 ;; Delete trailing white-lines.
11806 (when region?
11807 (while (looking-at-p "^[ \t]*$")
11808 (delete-region (line-beginning-position)
11809 (line-beginning-position 2))))
11810 (save-excursion
11811 (while (not (eobp))
11812 (unless (looking-at-p indent)
11813 (insert indent))
11814 (forward-line)))
11815 (insert
11816 indent
11817 (format "#+begin_%s%s\n" type (if special? " " "")))
11818 (unless region? (indent-to col))
11819 (setq s (point))
11820 (goto-char (point-max))
11821 (skip-chars-backward "[ \t\n]" s)
11822 (delete-region (line-end-position) (point-max))
11823 (insert "\n" indent
11824 (format "#+end_%s" (car (split-string type)))
11825 (if region-end-blank "" "\n"))
11826 (buffer-substring (point-min) (point))))
11827 (when (and (eobp) (not (bolp))) (insert "\n")))
11828 (cond (special?
11829 (end-of-line))
11831 (forward-line)
11832 (skip-chars-forward "[ \t]*")))))
11835 ;;;; TODO, DEADLINE, Comments
11837 (defun org-toggle-comment ()
11838 "Change the COMMENT state of an entry."
11839 (interactive)
11840 (save-excursion
11841 (org-back-to-heading)
11842 (let ((case-fold-search nil))
11843 (looking-at org-complex-heading-regexp))
11844 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11845 (skip-chars-forward " \t")
11846 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11847 (if (org-in-commented-heading-p t)
11848 (delete-region (point)
11849 (progn (search-forward " " (line-end-position) 'move)
11850 (skip-chars-forward " \t")
11851 (point)))
11852 (insert org-comment-string)
11853 (unless (eolp) (insert " ")))))
11855 (defvar org-last-todo-state-is-todo nil
11856 "This is non-nil when the last TODO state change led to a TODO state.
11857 If the last change removed the TODO tag or switched to DONE, then
11858 this is nil.")
11860 (defvar org-todo-setup-filter-hook nil
11861 "Hook for functions that pre-filter todo specs.
11862 Each function takes a todo spec and returns either nil or the spec
11863 transformed into canonical form." )
11865 (defvar org-todo-get-default-hook nil
11866 "Hook for functions that get a default item for todo.
11867 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11868 nil or a string to be used for the todo mark." )
11870 (defvar org-agenda-headline-snapshot-before-repeat)
11872 (defun org-current-effective-time ()
11873 "Return current time adjusted for `org-extend-today-until' variable."
11874 (let* ((ct (org-current-time))
11875 (dct (decode-time ct))
11876 (ct1
11877 (cond
11878 (org-use-last-clock-out-time-as-effective-time
11879 (or (org-clock-get-last-clock-out-time) ct))
11880 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11881 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11882 (t ct))))
11883 ct1))
11885 (defun org-todo-yesterday (&optional arg)
11886 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11887 (interactive "P")
11888 (if (eq major-mode 'org-agenda-mode)
11889 (apply 'org-agenda-todo-yesterday arg)
11890 (let* ((org-use-effective-time t)
11891 (hour (nth 2 (decode-time (org-current-time))))
11892 (org-extend-today-until (1+ hour)))
11893 (org-todo arg))))
11895 (defvar org-block-entry-blocking ""
11896 "First entry preventing the TODO state change.")
11898 (defun org-cancel-repeater ()
11899 "Cancel a repeater by setting its numeric value to zero."
11900 (interactive)
11901 (save-excursion
11902 (org-back-to-heading t)
11903 (let ((bound1 (point))
11904 (bound0 (save-excursion (outline-next-heading) (point))))
11905 (when (and (re-search-forward
11906 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11907 org-deadline-time-regexp "\\)\\|\\("
11908 org-ts-regexp "\\)")
11909 bound0 t)
11910 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11911 bound1 t))
11912 (replace-match "0" t nil nil 1)))))
11914 (defvar org-state)
11915 (defvar org-blocked-by-checkboxes)
11916 (defun org-todo (&optional arg)
11917 "Change the TODO state of an item.
11919 The state of an item is given by a keyword at the start of the heading,
11920 like
11921 *** TODO Write paper
11922 *** DONE Call mom
11924 The different keywords are specified in the variable `org-todo-keywords'.
11925 By default the available states are \"TODO\" and \"DONE\". So, for this
11926 example: when the item starts with TODO, it is changed to DONE.
11927 When it starts with DONE, the DONE is removed. And when neither TODO nor
11928 DONE are present, add TODO at the beginning of the heading.
11930 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11931 state.
11932 With numeric prefix ARG, switch to that state.
11933 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11934 next set of TODO \
11935 keywords (nextset).
11936 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11937 prefix, circumvent any state blocking.
11938 With a numeric prefix arg of 0, inhibit note taking for the change.
11939 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11941 When called through ELisp, arg is also interpreted in the following way:
11942 `none' -> empty state
11943 \"\" -> switch to empty state
11944 `done' -> switch to DONE
11945 `nextset' -> switch to the next set of keywords
11946 `previousset' -> switch to the previous set of keywords
11947 \"WAITING\" -> switch to the specified keyword, but only if it
11948 really is a member of `org-todo-keywords'."
11949 (interactive "P")
11950 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11951 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11952 'region-start-level 'region))
11953 org-loop-over-headlines-in-active-region)
11954 (org-map-entries
11955 `(org-todo ,arg)
11956 org-loop-over-headlines-in-active-region
11957 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11958 (when (equal arg '(16)) (setq arg 'nextset))
11959 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11960 (let ((org-blocker-hook org-blocker-hook)
11961 commentp
11962 case-fold-search)
11963 (when (equal arg '(64))
11964 (setq arg nil org-blocker-hook nil))
11965 (when (and org-blocker-hook
11966 (or org-inhibit-blocking
11967 (org-entry-get nil "NOBLOCKING")))
11968 (setq org-blocker-hook nil))
11969 (save-excursion
11970 (catch 'exit
11971 (org-back-to-heading t)
11972 (when (org-in-commented-heading-p t)
11973 (org-toggle-comment)
11974 (setq commentp t))
11975 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11976 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11977 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11978 (let* ((match-data (match-data))
11979 (startpos (copy-marker (line-beginning-position)))
11980 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11981 (org-log-done org-log-done)
11982 (org-log-repeat org-log-repeat)
11983 (org-todo-log-states org-todo-log-states)
11984 (org-inhibit-logging
11985 (if (equal arg 0)
11986 (progn (setq arg nil) 'note) org-inhibit-logging))
11987 (this (match-string 1))
11988 (hl-pos (match-beginning 0))
11989 (head (org-get-todo-sequence-head this))
11990 (ass (assoc head org-todo-kwd-alist))
11991 (interpret (nth 1 ass))
11992 (done-word (nth 3 ass))
11993 (final-done-word (nth 4 ass))
11994 (org-last-state (or this ""))
11995 (completion-ignore-case t)
11996 (member (member this org-todo-keywords-1))
11997 (tail (cdr member))
11998 (org-state (cond
11999 ((and org-todo-key-trigger
12000 (or (and (equal arg '(4))
12001 (eq org-use-fast-todo-selection 'prefix))
12002 (and (not arg) org-use-fast-todo-selection
12003 (not (eq org-use-fast-todo-selection
12004 'prefix)))))
12005 ;; Use fast selection.
12006 (org-fast-todo-selection))
12007 ((and (equal arg '(4))
12008 (or (not org-use-fast-todo-selection)
12009 (not org-todo-key-trigger)))
12010 ;; Read a state with completion.
12011 (completing-read
12012 "State: " (mapcar #'list org-todo-keywords-1)
12013 nil t))
12014 ((eq arg 'right)
12015 (if this
12016 (if tail (car tail) nil)
12017 (car org-todo-keywords-1)))
12018 ((eq arg 'left)
12019 (unless (equal member org-todo-keywords-1)
12020 (if this
12021 (nth (- (length org-todo-keywords-1)
12022 (length tail) 2)
12023 org-todo-keywords-1)
12024 (org-last org-todo-keywords-1))))
12025 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12026 (setq arg nil))) ;hack to fall back to cycling
12027 (arg
12028 ;; User or caller requests a specific state.
12029 (cond
12030 ((equal arg "") nil)
12031 ((eq arg 'none) nil)
12032 ((eq arg 'done) (or done-word (car org-done-keywords)))
12033 ((eq arg 'nextset)
12034 (or (car (cdr (member head org-todo-heads)))
12035 (car org-todo-heads)))
12036 ((eq arg 'previousset)
12037 (let ((org-todo-heads (reverse org-todo-heads)))
12038 (or (car (cdr (member head org-todo-heads)))
12039 (car org-todo-heads))))
12040 ((car (member arg org-todo-keywords-1)))
12041 ((stringp arg)
12042 (user-error "State `%s' not valid in this file" arg))
12043 ((nth (1- (prefix-numeric-value arg))
12044 org-todo-keywords-1))))
12045 ((null member) (or head (car org-todo-keywords-1)))
12046 ((equal this final-done-word) nil) ;-> make empty
12047 ((null tail) nil) ;-> first entry
12048 ((memq interpret '(type priority))
12049 (if (eq this-command last-command)
12050 (car tail)
12051 (if (> (length tail) 0)
12052 (or done-word (car org-done-keywords))
12053 nil)))
12055 (car tail))))
12056 (org-state (or
12057 (run-hook-with-args-until-success
12058 'org-todo-get-default-hook org-state org-last-state)
12059 org-state))
12060 (next (if org-state (concat " " org-state " ") " "))
12061 (change-plist (list :type 'todo-state-change :from this :to org-state
12062 :position startpos))
12063 dolog now-done-p)
12064 (when org-blocker-hook
12065 (let (org-blocked-by-checkboxes block-reason)
12066 (setq org-last-todo-state-is-todo
12067 (not (member this org-done-keywords)))
12068 (unless (save-excursion
12069 (save-match-data
12070 (org-with-wide-buffer
12071 (run-hook-with-args-until-failure
12072 'org-blocker-hook change-plist))))
12073 (setq block-reason (if org-blocked-by-checkboxes
12074 "contained checkboxes"
12075 (format "\"%s\"" org-block-entry-blocking)))
12076 (if (called-interactively-p 'interactive)
12077 (user-error "TODO state change from %s to %s blocked (by %s)"
12078 this org-state block-reason)
12079 ;; Fail silently.
12080 (message "TODO state change from %s to %s blocked (by %s)"
12081 this org-state block-reason)
12082 (throw 'exit nil)))))
12083 (store-match-data match-data)
12084 (replace-match next t t)
12085 (cond ((equal this org-state)
12086 (message "TODO state was already %s" (org-trim next)))
12087 ((not (pos-visible-in-window-p hl-pos))
12088 (message "TODO state changed to %s" (org-trim next))))
12089 (unless head
12090 (setq head (org-get-todo-sequence-head org-state)
12091 ass (assoc head org-todo-kwd-alist)
12092 interpret (nth 1 ass)
12093 done-word (nth 3 ass)
12094 final-done-word (nth 4 ass)))
12095 (when (memq arg '(nextset previousset))
12096 (message "Keyword-Set %d/%d: %s"
12097 (- (length org-todo-sets) -1
12098 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12099 (length org-todo-sets)
12100 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12101 (setq org-last-todo-state-is-todo
12102 (not (member org-state org-done-keywords)))
12103 (setq now-done-p (and (member org-state org-done-keywords)
12104 (not (member this org-done-keywords))))
12105 (and logging (org-local-logging logging))
12106 (when (and (or org-todo-log-states org-log-done)
12107 (not (eq org-inhibit-logging t))
12108 (not (memq arg '(nextset previousset))))
12109 ;; We need to look at recording a time and note.
12110 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12111 (nth 2 (assoc this org-todo-log-states))))
12112 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12113 (setq dolog 'time))
12114 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12115 (and org-state
12116 (member org-state org-not-done-keywords)
12117 (not (member this org-not-done-keywords))))
12118 ;; This is now a todo state and was not one before
12119 ;; If there was a CLOSED time stamp, get rid of it.
12120 (org-add-planning-info nil nil 'closed))
12121 (when (and now-done-p org-log-done)
12122 ;; It is now done, and it was not done before.
12123 (org-add-planning-info 'closed (org-current-effective-time))
12124 (when (and (not dolog) (eq 'note org-log-done))
12125 (org-add-log-setup 'done org-state this 'note)))
12126 (when (and org-state dolog)
12127 ;; This is a non-nil state, and we need to log it.
12128 (org-add-log-setup 'state org-state this dolog)))
12129 ;; Fixup tag positioning.
12130 (org-todo-trigger-tag-changes org-state)
12131 (when org-auto-align-tags (org-align-tags))
12132 (when org-provide-todo-statistics
12133 (org-update-parent-todo-statistics))
12134 (run-hooks 'org-after-todo-state-change-hook)
12135 (when (and arg (not (member org-state org-done-keywords)))
12136 (setq head (org-get-todo-sequence-head org-state)))
12137 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12138 ;; Do we need to trigger a repeat?
12139 (when now-done-p
12140 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12141 ;; This is for the agenda, take a snapshot of the headline.
12142 (save-match-data
12143 (setq org-agenda-headline-snapshot-before-repeat
12144 (org-get-heading))))
12145 (org-auto-repeat-maybe org-state))
12146 ;; Fixup cursor location if close to the keyword.
12147 (when (and (outline-on-heading-p)
12148 (not (bolp))
12149 (save-excursion (beginning-of-line 1)
12150 (looking-at org-todo-line-regexp))
12151 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12152 (goto-char (or (match-end 2) (match-end 1)))
12153 (and (looking-at " ") (just-one-space)))
12154 (when org-trigger-hook
12155 (save-excursion
12156 (run-hook-with-args 'org-trigger-hook change-plist)))
12157 (when commentp (org-toggle-comment))))))))
12159 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12160 "Block turning an entry into a TODO, using the hierarchy.
12161 This checks whether the current task should be blocked from state
12162 changes. Such blocking occurs when:
12164 1. The task has children which are not all in a completed state.
12166 2. A task has a parent with the property :ORDERED:, and there
12167 are siblings prior to the current task with incomplete
12168 status.
12170 3. The parent of the task is blocked because it has siblings that should
12171 be done first, or is child of a block grandparent TODO entry."
12173 (if (not org-enforce-todo-dependencies)
12174 t ; if locally turned off don't block
12175 (catch 'dont-block
12176 ;; If this is not a todo state change, or if this entry is already DONE,
12177 ;; do not block
12178 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12179 (member (plist-get change-plist :from)
12180 (cons 'done org-done-keywords))
12181 (member (plist-get change-plist :to)
12182 (cons 'todo org-not-done-keywords))
12183 (not (plist-get change-plist :to)))
12184 (throw 'dont-block t))
12185 ;; If this task has children, and any are undone, it's blocked
12186 (save-excursion
12187 (org-back-to-heading t)
12188 (let ((this-level (funcall outline-level)))
12189 (outline-next-heading)
12190 (let ((child-level (funcall outline-level)))
12191 (while (and (not (eobp))
12192 (> child-level this-level))
12193 ;; this todo has children, check whether they are all
12194 ;; completed
12195 (when (and (not (org-entry-is-done-p))
12196 (org-entry-is-todo-p))
12197 (setq org-block-entry-blocking (org-get-heading))
12198 (throw 'dont-block nil))
12199 (outline-next-heading)
12200 (setq child-level (funcall outline-level))))))
12201 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12202 ;; any previous siblings are undone, it's blocked
12203 (save-excursion
12204 (org-back-to-heading t)
12205 (let* ((pos (point))
12206 (parent-pos (and (org-up-heading-safe) (point)))
12207 (case-fold-search nil))
12208 (unless parent-pos (throw 'dont-block t)) ; no parent
12209 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12210 (forward-line 1)
12211 (re-search-forward org-not-done-heading-regexp pos t))
12212 (setq org-block-entry-blocking (match-string 0))
12213 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12214 ;; Search further up the hierarchy, to see if an ancestor is blocked
12215 (while t
12216 (goto-char parent-pos)
12217 (unless (looking-at org-not-done-heading-regexp)
12218 (throw 'dont-block t)) ; do not block, parent is not a TODO
12219 (setq pos (point))
12220 (setq parent-pos (and (org-up-heading-safe) (point)))
12221 (unless parent-pos (throw 'dont-block t)) ; no parent
12222 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12223 (forward-line 1)
12224 (re-search-forward org-not-done-heading-regexp pos t)
12225 (setq org-block-entry-blocking (org-get-heading)))
12226 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12228 (defcustom org-track-ordered-property-with-tag nil
12229 "Should the ORDERED property also be shown as a tag?
12230 The ORDERED property decides if an entry should require subtasks to be
12231 completed in sequence. Since a property is not very visible, setting
12232 this option means that toggling the ORDERED property with the command
12233 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12234 not relevant for the behavior, but it makes things more visible.
12236 Note that toggling the tag with tags commands will not change the property
12237 and therefore not influence behavior!
12239 This can be t, meaning the tag ORDERED should be used, It can also be a
12240 string to select a different tag for this task."
12241 :group 'org-todo
12242 :type '(choice
12243 (const :tag "No tracking" nil)
12244 (const :tag "Track with ORDERED tag" t)
12245 (string :tag "Use other tag")))
12247 (defun org-toggle-ordered-property ()
12248 "Toggle the ORDERED property of the current entry.
12249 For better visibility, you can track the value of this property with a tag.
12250 See variable `org-track-ordered-property-with-tag'."
12251 (interactive)
12252 (let* ((t1 org-track-ordered-property-with-tag)
12253 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12254 (save-excursion
12255 (org-back-to-heading)
12256 (if (org-entry-get nil "ORDERED")
12257 (progn
12258 (org-delete-property "ORDERED")
12259 (and tag (org-toggle-tag tag 'off))
12260 (message "Subtasks can be completed in arbitrary order"))
12261 (org-entry-put nil "ORDERED" "t")
12262 (and tag (org-toggle-tag tag 'on))
12263 (message "Subtasks must be completed in sequence")))))
12265 (defun org-block-todo-from-checkboxes (change-plist)
12266 "Block turning an entry into a TODO, using checkboxes.
12267 This checks whether the current task should be blocked from state
12268 changes because there are unchecked boxes in this entry."
12269 (if (not org-enforce-todo-checkbox-dependencies)
12270 t ; if locally turned off don't block
12271 (catch 'dont-block
12272 ;; If this is not a todo state change, or if this entry is already DONE,
12273 ;; do not block
12274 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12275 (member (plist-get change-plist :from)
12276 (cons 'done org-done-keywords))
12277 (member (plist-get change-plist :to)
12278 (cons 'todo org-not-done-keywords))
12279 (not (plist-get change-plist :to)))
12280 (throw 'dont-block t))
12281 ;; If this task has checkboxes that are not checked, it's blocked
12282 (save-excursion
12283 (org-back-to-heading t)
12284 (let ((beg (point)) end)
12285 (outline-next-heading)
12286 (setq end (point))
12287 (goto-char beg)
12288 (when (org-list-search-forward
12289 (concat (org-item-beginning-re)
12290 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12291 "\\[[- ]\\]")
12292 end t)
12293 (when (boundp 'org-blocked-by-checkboxes)
12294 (setq org-blocked-by-checkboxes t))
12295 (throw 'dont-block nil))))
12296 t))) ; do not block
12298 (defun org-entry-blocked-p ()
12299 "Non-nil if entry at point is blocked."
12300 (and (not (org-entry-get nil "NOBLOCKING"))
12301 (member (org-entry-get nil "TODO") org-not-done-keywords)
12302 (not (run-hook-with-args-until-failure
12303 'org-blocker-hook
12304 (list :type 'todo-state-change
12305 :position (point)
12306 :from 'todo
12307 :to 'done)))))
12309 (defun org-update-statistics-cookies (all)
12310 "Update the statistics cookie, either from TODO or from checkboxes.
12311 This should be called with the cursor in a line with a statistics
12312 cookie. When called with a \\[universal-argument] prefix, update
12313 all statistics cookies in the buffer."
12314 (interactive "P")
12315 (if all
12316 (progn
12317 (org-update-checkbox-count 'all)
12318 (org-map-entries 'org-update-parent-todo-statistics))
12319 (if (not (org-at-heading-p))
12320 (org-update-checkbox-count)
12321 (let ((pos (point-marker))
12322 end l1 l2)
12323 (ignore-errors (org-back-to-heading t))
12324 (if (not (org-at-heading-p))
12325 (org-update-checkbox-count)
12326 (setq l1 (org-outline-level))
12327 (setq end (save-excursion
12328 (outline-next-heading)
12329 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12330 (point)))
12331 (if (and (save-excursion
12332 (re-search-forward
12333 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12334 (not (save-excursion (re-search-forward
12335 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12336 (org-update-checkbox-count)
12337 (if (and l2 (> l2 l1))
12338 (progn
12339 (goto-char end)
12340 (org-update-parent-todo-statistics))
12341 (goto-char pos)
12342 (beginning-of-line 1)
12343 (while (re-search-forward
12344 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12345 (point-at-eol) t)
12346 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12347 (goto-char pos)
12348 (move-marker pos nil)))))
12350 (defvar org-entry-property-inherited-from) ;; defined below
12351 (defun org-update-parent-todo-statistics ()
12352 "Update any statistics cookie in the parent of the current headline.
12353 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12354 the entire subtree and this will travel up the hierarchy and update
12355 statistics everywhere."
12356 (let* ((prop (save-excursion (org-up-heading-safe)
12357 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12358 (recursive (or (not org-hierarchical-todo-statistics)
12359 (and prop (string-match "\\<recursive\\>" prop))))
12360 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12362 (first t)
12363 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12364 level ltoggle l1 new ndel
12365 (cnt-all 0) (cnt-done 0) is-percent kwd
12366 checkbox-beg cookie-present)
12367 (catch 'exit
12368 (save-excursion
12369 (beginning-of-line 1)
12370 (setq ltoggle (funcall outline-level))
12371 ;; Three situations are to consider:
12373 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12374 ;; to the top-level ancestor on the headline;
12376 ;; 2. If parent has "recursive" property, repeat up to the
12377 ;; headline setting that property, taking inheritance into
12378 ;; account;
12380 ;; 3. Else, move up to direct parent and proceed only once.
12381 (while (and (setq level (org-up-heading-safe))
12382 (or recursive first)
12383 (>= (point) lim))
12384 (setq first nil cookie-present nil)
12385 (unless (and level
12386 (not (string-match
12387 "\\<checkbox\\>"
12388 (downcase (or (org-entry-get nil "COOKIE_DATA")
12389 "")))))
12390 (throw 'exit nil))
12391 (while (re-search-forward box-re (point-at-eol) t)
12392 (setq cnt-all 0 cnt-done 0 cookie-present t)
12393 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12394 (save-match-data
12395 (unless (outline-next-heading) (throw 'exit nil))
12396 (while (and (looking-at org-complex-heading-regexp)
12397 (> (setq l1 (length (match-string 1))) level))
12398 (setq kwd (and (or recursive (= l1 ltoggle))
12399 (match-string 2)))
12400 (if (or (eq org-provide-todo-statistics 'all-headlines)
12401 (and (eq org-provide-todo-statistics t)
12402 (or (member kwd org-done-keywords)))
12403 (and (listp org-provide-todo-statistics)
12404 (stringp (car org-provide-todo-statistics))
12405 (or (member kwd org-provide-todo-statistics)
12406 (member kwd org-done-keywords)))
12407 (and (listp org-provide-todo-statistics)
12408 (listp (car org-provide-todo-statistics))
12409 (or (member kwd (car org-provide-todo-statistics))
12410 (and (member kwd org-done-keywords)
12411 (member kwd (cadr org-provide-todo-statistics))))))
12412 (setq cnt-all (1+ cnt-all))
12413 (and (eq org-provide-todo-statistics t)
12415 (setq cnt-all (1+ cnt-all))))
12416 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12417 (member kwd org-done-keywords))
12418 (and (listp org-provide-todo-statistics)
12419 (listp (car org-provide-todo-statistics))
12420 (member kwd org-done-keywords)
12421 (member kwd (cadr org-provide-todo-statistics)))
12422 (and (listp org-provide-todo-statistics)
12423 (stringp (car org-provide-todo-statistics))
12424 (member kwd org-done-keywords)))
12425 (setq cnt-done (1+ cnt-done)))
12426 (outline-next-heading)))
12427 (setq new
12428 (if is-percent
12429 (format "[%d%%]" (floor (* 100.0 cnt-done)
12430 (max 1 cnt-all)))
12431 (format "[%d/%d]" cnt-done cnt-all))
12432 ndel (- (match-end 0) checkbox-beg))
12433 (goto-char checkbox-beg)
12434 (insert new)
12435 (delete-region (point) (+ (point) ndel))
12436 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12437 (when cookie-present
12438 (run-hook-with-args 'org-after-todo-statistics-hook
12439 cnt-done (- cnt-all cnt-done))))))
12440 (run-hooks 'org-todo-statistics-hook)))
12442 (defvar org-after-todo-statistics-hook nil
12443 "Hook that is called after a TODO statistics cookie has been updated.
12444 Each function is called with two arguments: the number of not-done entries
12445 and the number of done entries.
12447 For example, the following function, when added to this hook, will switch
12448 an entry to DONE when all children are done, and back to TODO when new
12449 entries are set to a TODO status. Note that this hook is only called
12450 when there is a statistics cookie in the headline!
12452 (defun org-summary-todo (n-done n-not-done)
12453 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12454 (let (org-log-done org-log-states) ; turn off logging
12455 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12458 (defvar org-todo-statistics-hook nil
12459 "Hook that is run whenever Org thinks TODO statistics should be updated.
12460 This hook runs even if there is no statistics cookie present, in which case
12461 `org-after-todo-statistics-hook' would not run.")
12463 (defun org-todo-trigger-tag-changes (state)
12464 "Apply the changes defined in `org-todo-state-tags-triggers'."
12465 (let ((l org-todo-state-tags-triggers)
12466 changes)
12467 (when (or (not state) (equal state ""))
12468 (setq changes (append changes (cdr (assoc "" l)))))
12469 (when (and (stringp state) (> (length state) 0))
12470 (setq changes (append changes (cdr (assoc state l)))))
12471 (when (member state org-not-done-keywords)
12472 (setq changes (append changes (cdr (assq 'todo l)))))
12473 (when (member state org-done-keywords)
12474 (setq changes (append changes (cdr (assq 'done l)))))
12475 (dolist (c changes)
12476 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12478 (defun org-local-logging (value)
12479 "Get logging settings from a property VALUE."
12480 ;; Directly set the variables, they are already local.
12481 (setq org-log-done nil
12482 org-log-repeat nil
12483 org-todo-log-states nil)
12484 (dolist (w (split-string value))
12485 (let (a)
12486 (cond
12487 ((setq a (assoc w org-startup-options))
12488 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12489 (set (nth 1 a) (nth 2 a))))
12490 ((setq a (org-extract-log-state-settings w))
12491 (and (member (car a) org-todo-keywords-1)
12492 (push a org-todo-log-states)))))))
12494 (defun org-get-todo-sequence-head (kwd)
12495 "Return the head of the TODO sequence to which KWD belongs.
12496 If KWD is not set, check if there is a text property remembering the
12497 right sequence."
12498 (let (p)
12499 (cond
12500 ((not kwd)
12501 (or (get-text-property (point-at-bol) 'org-todo-head)
12502 (progn
12503 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12504 nil (point-at-eol)))
12505 (get-text-property p 'org-todo-head))))
12506 ((not (member kwd org-todo-keywords-1))
12507 (car org-todo-keywords-1))
12508 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12510 (defun org-fast-todo-selection ()
12511 "Fast TODO keyword selection with single keys.
12512 Returns the new TODO keyword, or nil if no state change should occur."
12513 (let* ((fulltable org-todo-key-alist)
12514 (done-keywords org-done-keywords) ;; needed for the faces.
12515 (maxlen (apply 'max (mapcar
12516 (lambda (x)
12517 (if (stringp (car x)) (string-width (car x)) 0))
12518 fulltable)))
12519 (expert nil)
12520 (fwidth (+ maxlen 3 1 3))
12521 (ncol (/ (- (window-width) 4) fwidth))
12522 tg cnt e c tbl
12523 groups ingroup)
12524 (save-excursion
12525 (save-window-excursion
12526 (if expert
12527 (set-buffer (get-buffer-create " *Org todo*"))
12528 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12529 (erase-buffer)
12530 (setq-local org-done-keywords done-keywords)
12531 (setq tbl fulltable cnt 0)
12532 (while (setq e (pop tbl))
12533 (cond
12534 ((equal e '(:startgroup))
12535 (push '() groups) (setq ingroup t)
12536 (unless (= cnt 0)
12537 (setq cnt 0)
12538 (insert "\n"))
12539 (insert "{ "))
12540 ((equal e '(:endgroup))
12541 (setq ingroup nil cnt 0)
12542 (insert "}\n"))
12543 ((equal e '(:newline))
12544 (unless (= cnt 0)
12545 (setq cnt 0)
12546 (insert "\n")
12547 (setq e (car tbl))
12548 (while (equal (car tbl) '(:newline))
12549 (insert "\n")
12550 (setq tbl (cdr tbl)))))
12552 (setq tg (car e) c (cdr e))
12553 (when ingroup (push tg (car groups)))
12554 (setq tg (org-add-props tg nil 'face
12555 (org-get-todo-face tg)))
12556 (when (and (= cnt 0) (not ingroup)) (insert " "))
12557 (insert "[" c "] " tg (make-string
12558 (- fwidth 4 (length tg)) ?\ ))
12559 (when (= (setq cnt (1+ cnt)) ncol)
12560 (insert "\n")
12561 (when ingroup (insert " "))
12562 (setq cnt 0)))))
12563 (insert "\n")
12564 (goto-char (point-min))
12565 (unless expert (org-fit-window-to-buffer))
12566 (message "[a-z..]:Set [SPC]:clear")
12567 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12568 (cond
12569 ((or (= c ?\C-g)
12570 (and (= c ?q) (not (rassoc c fulltable))))
12571 (setq quit-flag t))
12572 ((= c ?\ ) nil)
12573 ((setq e (rassoc c fulltable) tg (car e))
12575 (t (setq quit-flag t)))))))
12577 (defun org-entry-is-todo-p ()
12578 (member (org-get-todo-state) org-not-done-keywords))
12580 (defun org-entry-is-done-p ()
12581 (member (org-get-todo-state) org-done-keywords))
12583 (defun org-get-todo-state ()
12584 "Return the TODO keyword of the current subtree."
12585 (save-excursion
12586 (org-back-to-heading t)
12587 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12588 (match-end 2)
12589 (match-string 2))))
12591 (defun org-at-date-range-p (&optional inactive-ok)
12592 "Non-nil if point is inside a date range.
12594 When optional argument INACTIVE-OK is non-nil, also consider
12595 inactive time ranges.
12597 When this function returns a non-nil value, match data is set
12598 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12599 on INACTIVE-OK."
12600 (interactive)
12601 (save-excursion
12602 (catch 'exit
12603 (let ((pos (point)))
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 (skip-chars-backward "^<[\r\n")
12610 (skip-chars-backward "<[")
12611 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12612 (>= (match-end 0) pos)
12613 (throw 'exit t)))
12614 nil)))
12616 (defun org-get-repeat (&optional timestamp)
12617 "Check if there is a time-stamp with repeater in this entry.
12619 Return the repeater, as a string, or nil. Also return nil when
12620 this function is called before first heading.
12622 When optional argument TIMESTAMP is a string, extract the
12623 repeater from there instead."
12624 (save-match-data
12625 (cond (timestamp
12626 (and (string-match org-repeat-re timestamp)
12627 (match-string-no-properties 1 timestamp)))
12628 ((org-before-first-heading-p) nil)
12630 (save-excursion
12631 (org-back-to-heading t)
12632 (let ((end (org-entry-end-position)))
12633 (catch :repeat
12634 (while (re-search-forward org-repeat-re end t)
12635 (when (save-match-data (org-at-timestamp-p 'agenda))
12636 (throw :repeat (match-string-no-properties 1)))))))))))
12638 (defvar org-last-changed-timestamp)
12639 (defvar org-last-inserted-timestamp)
12640 (defvar org-log-post-message)
12641 (defvar org-log-note-purpose)
12642 (defvar org-log-note-how nil)
12643 (defvar org-log-note-extra)
12644 (defun org-auto-repeat-maybe (done-word)
12645 "Check if the current headline contains a repeated time-stamp.
12647 If yes, set TODO state back to what it was and change the base date
12648 of repeating deadline/scheduled time stamps to new date.
12650 This function is run automatically after each state change to a DONE state."
12651 (let* ((repeat (org-get-repeat))
12652 (aa (assoc org-last-state org-todo-kwd-alist))
12653 (interpret (nth 1 aa))
12654 (head (nth 2 aa))
12655 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12656 (msg "Entry repeats: ")
12657 (org-log-done nil)
12658 (org-todo-log-states nil)
12659 (end (copy-marker (org-entry-end-position))))
12660 (unwind-protect
12661 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12662 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12663 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12664 (and (stringp org-todo-repeat-to-state)
12665 org-todo-repeat-to-state)
12666 (and org-todo-repeat-to-state org-last-state))))
12667 (org-todo (cond
12668 ((and to-state (member to-state org-todo-keywords-1))
12669 to-state)
12670 ((eq interpret 'type) org-last-state)
12671 (head)
12672 (t 'none))))
12673 (org-back-to-heading t)
12674 (org-add-planning-info nil nil 'closed)
12675 ;; When `org-log-repeat' is non-nil or entry contains
12676 ;; a clock, set LAST_REPEAT property.
12677 (when (or org-log-repeat
12678 (catch :clock
12679 (save-excursion
12680 (while (re-search-forward org-clock-line-re end t)
12681 (when (org-at-clock-log-p) (throw :clock t))))))
12682 (org-entry-put nil "LAST_REPEAT" (format-time-string
12683 (org-time-stamp-format t t)
12684 (current-time))))
12685 (when org-log-repeat
12686 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12687 (memq 'org-add-log-note post-command-hook))
12688 ;; We are already setup for some record.
12689 (when (eq org-log-repeat 'note)
12690 ;; Make sure we take a note, not only a time stamp.
12691 (setq org-log-note-how 'note))
12692 ;; Set up for taking a record.
12693 (org-add-log-setup 'state
12694 (or done-word (car org-done-keywords))
12695 org-last-state
12696 org-log-repeat)))
12697 (let ((planning-re (regexp-opt
12698 (list org-scheduled-string org-deadline-string))))
12699 (while (re-search-forward org-ts-regexp end t)
12700 (let* ((ts (match-string 0))
12701 (planning? (org-at-planning-p))
12702 (type (if (not planning?) "Plain:"
12703 (save-excursion
12704 (re-search-backward
12705 planning-re (line-beginning-position) t)
12706 (match-string 0)))))
12707 (cond
12708 ;; Ignore fake time-stamps (e.g., within comments).
12709 ((not (org-at-timestamp-p 'agenda)))
12710 ;; Time-stamps without a repeater are usually
12711 ;; skipped. However, a SCHEDULED time-stamp without
12712 ;; one is removed, as they are no longer relevant.
12713 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12714 ts))
12715 (when (equal type org-scheduled-string)
12716 (org-remove-timestamp-with-keyword type)))
12718 (let ((n (string-to-number (match-string 2 ts)))
12719 (what (match-string 3 ts)))
12720 (when (equal what "w") (setq n (* n 7) what "d"))
12721 (when (and (equal what "h")
12722 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12723 ts)))
12724 (user-error
12725 "Cannot repeat in Repeat in %d hour(s) because no hour \
12726 has been set"
12728 ;; Preparation, see if we need to modify the start
12729 ;; date for the change.
12730 (when (match-end 1)
12731 (let ((time (save-match-data
12732 (org-time-string-to-time ts))))
12733 (cond
12734 ((equal (match-string 1 ts) ".")
12735 ;; Shift starting date to today
12736 (org-timestamp-change
12737 (- (org-today) (time-to-days time))
12738 'day))
12739 ((equal (match-string 1 ts) "+")
12740 (let ((nshiftmax 10)
12741 (nshift 0))
12742 (while (or (= nshift 0)
12743 (not (time-less-p (current-time) time)))
12744 (when (= (cl-incf nshift) nshiftmax)
12745 (or (y-or-n-p
12746 (format "%d repeater intervals were not \
12747 enough to shift date past today. Continue? "
12748 nshift))
12749 (user-error "Abort")))
12750 (org-timestamp-change n (cdr (assoc what whata)))
12751 (org-in-regexp org-ts-regexp3)
12752 (setq ts (match-string 1))
12753 (setq time
12754 (save-match-data
12755 (org-time-string-to-time ts)))))
12756 (org-timestamp-change (- n) (cdr (assoc what whata)))
12757 ;; Rematch, so that we have everything in place
12758 ;; for the real shift.
12759 (org-in-regexp org-ts-regexp3)
12760 (setq ts (match-string 1))
12761 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12762 ts)))))
12763 (save-excursion
12764 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12765 (setq msg
12766 (concat
12767 msg type " " org-last-changed-timestamp " "))))))))
12768 (setq org-log-post-message msg)
12769 (message "%s" msg))
12770 (set-marker end nil))))
12772 (defun org-show-todo-tree (arg)
12773 "Make a compact tree which shows all headlines marked with TODO.
12774 The tree will show the lines where the regexp matches, and all higher
12775 headlines above the match.
12776 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12777 With a numeric prefix N, construct a sparse tree for the Nth element
12778 of `org-todo-keywords-1'."
12779 (interactive "P")
12780 (let ((case-fold-search nil)
12781 (kwd-re
12782 (cond ((null arg) org-not-done-regexp)
12783 ((equal arg '(4))
12784 (let ((kwd
12785 (completing-read "Keyword (or KWD1|KWD2|...): "
12786 (mapcar #'list org-todo-keywords-1))))
12787 (concat "\\("
12788 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12789 "\\)\\>")))
12790 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12791 (regexp-quote (nth (1- (prefix-numeric-value arg))
12792 org-todo-keywords-1)))
12793 (t (user-error "Invalid prefix argument: %s" arg)))))
12794 (message "%d TODO entries found"
12795 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12797 (defun org--deadline-or-schedule (arg type time)
12798 "Insert DEADLINE or SCHEDULE information in current entry.
12799 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12800 `org-schedule' for information about ARG and TIME arguments."
12801 (let* ((deadline? (eq type 'deadline))
12802 (keyword (if deadline? org-deadline-string org-scheduled-string))
12803 (log (if deadline? org-log-redeadline org-log-reschedule))
12804 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12805 (old-date-time (and old-date (org-time-string-to-time old-date)))
12806 ;; Save repeater cookie from either TIME or current scheduled
12807 ;; time stamp. We are going to insert it back at the end of
12808 ;; the process.
12809 (repeater (or (and (org-string-nw-p time)
12810 ;; We use `org-repeat-re' because we need
12811 ;; to tell the difference between a real
12812 ;; repeater and a time delta, e.g. "+2d".
12813 (string-match org-repeat-re time)
12814 (match-string 1 time))
12815 (and (org-string-nw-p old-date)
12816 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12817 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12818 old-date)
12819 (match-string 1 old-date)))))
12820 (pcase arg
12821 (`(4)
12822 (when (and old-date log)
12823 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12824 nil old-date log))
12825 (org-remove-timestamp-with-keyword keyword)
12826 (message (if deadline? "Item no longer has a deadline."
12827 "Item is no longer scheduled.")))
12828 (`(16)
12829 (save-excursion
12830 (org-back-to-heading t)
12831 (let ((regexp (if deadline? org-deadline-time-regexp
12832 org-scheduled-time-regexp)))
12833 (if (not (re-search-forward regexp (line-end-position 2) t))
12834 (user-error (if deadline? "No deadline information to update"
12835 "No scheduled information to update"))
12836 (let* ((rpl0 (match-string 1))
12837 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12838 (msg (if deadline? "Warn starting from" "Delay until")))
12839 (replace-match
12840 (concat keyword
12841 " <" rpl
12842 (format " -%dd"
12843 (abs (- (time-to-days
12844 (save-match-data
12845 (org-read-date
12846 nil t nil msg old-date-time)))
12847 (time-to-days old-date-time))))
12848 ">") t t))))))
12850 (org-add-planning-info type time 'closed)
12851 (when (and old-date
12853 (not (equal old-date org-last-inserted-timestamp)))
12854 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12855 org-last-inserted-timestamp
12856 old-date
12857 log))
12858 (when repeater
12859 (save-excursion
12860 (org-back-to-heading t)
12861 (when (re-search-forward
12862 (concat keyword " " org-last-inserted-timestamp)
12863 (line-end-position 2)
12865 (goto-char (1- (match-end 0)))
12866 (insert " " repeater)
12867 (setq org-last-inserted-timestamp
12868 (concat (substring org-last-inserted-timestamp 0 -1)
12869 " " repeater
12870 (substring org-last-inserted-timestamp -1))))))
12871 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12872 org-last-inserted-timestamp)))))
12874 (defun org-deadline (arg &optional time)
12875 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12876 With one universal prefix argument, remove any deadline from the item.
12877 With two universal prefix arguments, prompt for a warning delay.
12878 With argument TIME, set the deadline at the corresponding date. TIME
12879 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12880 (interactive "P")
12881 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12882 (org-map-entries
12883 (lambda () (org--deadline-or-schedule arg 'deadline time))
12885 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12886 'region-start-level
12887 'region)
12888 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12889 (org--deadline-or-schedule arg 'deadline time)))
12891 (defun org-schedule (arg &optional time)
12892 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12893 With one universal prefix argument, remove any scheduling date from the item.
12894 With two universal prefix arguments, prompt for a delay cookie.
12895 With argument TIME, scheduled at the corresponding date. TIME can
12896 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12897 (interactive "P")
12898 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12899 (org-map-entries
12900 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12902 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12903 'region-start-level
12904 'region)
12905 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12906 (org--deadline-or-schedule arg 'scheduled time)))
12908 (defun org-get-scheduled-time (pom &optional inherit)
12909 "Get the scheduled time as a time tuple, of a format suitable
12910 for calling org-schedule with, or if there is no scheduling,
12911 returns nil."
12912 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12913 (when time
12914 (apply 'encode-time (org-parse-time-string time)))))
12916 (defun org-get-deadline-time (pom &optional inherit)
12917 "Get the deadline as a time tuple, of a format suitable for
12918 calling org-deadline with, or if there is no scheduling, returns
12919 nil."
12920 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12921 (when time
12922 (apply 'encode-time (org-parse-time-string time)))))
12924 (defun org-remove-timestamp-with-keyword (keyword)
12925 "Remove all time stamps with KEYWORD in the current entry."
12926 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12927 beg)
12928 (save-excursion
12929 (org-back-to-heading t)
12930 (setq beg (point))
12931 (outline-next-heading)
12932 (while (re-search-backward re beg t)
12933 (replace-match "")
12934 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12935 (equal (char-before) ?\ ))
12936 (backward-delete-char 1)
12937 (when (string-match "^[ \t]*$" (buffer-substring
12938 (point-at-bol) (point-at-eol)))
12939 (delete-region (point-at-bol)
12940 (min (point-max) (1+ (point-at-eol))))))))))
12942 (defvar org-time-was-given) ; dynamically scoped parameter
12943 (defvar org-end-time-was-given) ; dynamically scoped parameter
12945 (defun org-at-planning-p ()
12946 "Non-nil when point is on a planning info line."
12947 ;; This is as accurate and faster than `org-element-at-point' since
12948 ;; planning info location is fixed in the section.
12949 (org-with-wide-buffer
12950 (beginning-of-line)
12951 (and (looking-at-p org-planning-line-re)
12952 (eq (point)
12953 (ignore-errors
12954 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12955 (org-back-to-heading t)
12956 (org-with-limited-levels (org-back-to-heading t)))
12957 (line-beginning-position 2))))))
12959 (defun org-add-planning-info (what &optional time &rest remove)
12960 "Insert new timestamp with keyword in the planning line.
12961 WHAT indicates what kind of time stamp to add. It is a symbol
12962 among `closed', `deadline', `scheduled' and nil. TIME indicates
12963 the time to use. If none is given, the user is prompted for
12964 a date. REMOVE indicates what kind of entries to remove. An old
12965 WHAT entry will also be removed."
12966 (let (org-time-was-given org-end-time-was-given default-time default-input)
12967 (catch 'exit
12968 (when (and (memq what '(scheduled deadline))
12969 (or (not time)
12970 (and (stringp time)
12971 (string-match "^[-+]+[0-9]" time))))
12972 ;; Try to get a default date/time from existing timestamp
12973 (save-excursion
12974 (org-back-to-heading t)
12975 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12976 (when (re-search-forward (if (eq what 'scheduled)
12977 org-scheduled-time-regexp
12978 org-deadline-time-regexp)
12979 end t)
12980 (setq ts (match-string 1)
12981 default-time (apply 'encode-time (org-parse-time-string ts))
12982 default-input (and ts (org-get-compact-tod ts)))))))
12983 (when what
12984 (setq time
12985 (if (stringp time)
12986 ;; This is a string (relative or absolute), set
12987 ;; proper date.
12988 (apply #'encode-time
12989 (org-read-date-analyze
12990 time default-time (decode-time default-time)))
12991 ;; If necessary, get the time from the user
12992 (or time (org-read-date nil 'to-time nil nil
12993 default-time default-input)))))
12995 (org-with-wide-buffer
12996 (org-back-to-heading t)
12997 (forward-line)
12998 (unless (bolp) (insert "\n"))
12999 (cond ((looking-at-p org-planning-line-re)
13000 ;; Move to current indentation.
13001 (skip-chars-forward " \t")
13002 ;; Check if we have to remove something.
13003 (dolist (type (if what (cons what remove) remove))
13004 (save-excursion
13005 (when (re-search-forward
13006 (cl-case type
13007 (closed org-closed-time-regexp)
13008 (deadline org-deadline-time-regexp)
13009 (scheduled org-scheduled-time-regexp)
13010 (otherwise
13011 (error "Invalid planning type: %s" type)))
13012 (line-end-position) t)
13013 ;; Delete until next keyword or end of line.
13014 (delete-region
13015 (match-beginning 0)
13016 (if (re-search-forward org-keyword-time-not-clock-regexp
13017 (line-end-position)
13019 (match-beginning 0)
13020 (line-end-position))))))
13021 ;; If there is nothing more to add and no more keyword
13022 ;; is left, remove the line completely.
13023 (if (and (looking-at-p "[ \t]*$") (not what))
13024 (delete-region (line-beginning-position)
13025 (line-beginning-position 2))
13026 ;; If we removed last keyword, do not leave trailing
13027 ;; white space at the end of line.
13028 (let ((p (point)))
13029 (save-excursion
13030 (end-of-line)
13031 (unless (= (skip-chars-backward " \t" p) 0)
13032 (delete-region (point) (line-end-position)))))))
13033 ((not what) (throw 'exit nil)) ; Nothing to do.
13034 (t (insert-before-markers "\n")
13035 (backward-char 1)
13036 (when org-adapt-indentation
13037 (indent-to-column (1+ (org-outline-level))))))
13038 (when what
13039 ;; Insert planning keyword.
13040 (insert (cl-case what
13041 (closed org-closed-string)
13042 (deadline org-deadline-string)
13043 (scheduled org-scheduled-string)
13044 (otherwise (error "Invalid planning type: %s" what)))
13045 " ")
13046 ;; Insert associated timestamp.
13047 (let ((ts (org-insert-time-stamp
13048 time
13049 (or org-time-was-given
13050 (and (eq what 'closed) org-log-done-with-time))
13051 (eq what 'closed)
13052 nil nil (list org-end-time-was-given))))
13053 (unless (eolp) (insert " "))
13054 ts))))))
13056 (defvar org-log-note-marker (make-marker)
13057 "Marker pointing at the entry where the note is to be inserted.")
13058 (defvar org-log-note-purpose nil)
13059 (defvar org-log-note-state nil)
13060 (defvar org-log-note-previous-state nil)
13061 (defvar org-log-note-extra nil)
13062 (defvar org-log-note-window-configuration nil)
13063 (defvar org-log-note-return-to (make-marker))
13064 (defvar org-log-note-effective-time nil
13065 "Remembered current time so that dynamically scoped
13066 `org-extend-today-until' affects timestamps in state change log")
13068 (defvar org-log-post-message nil
13069 "Message to be displayed after a log note has been stored.
13070 The auto-repeater uses this.")
13072 (defun org-add-note ()
13073 "Add a note to the current entry.
13074 This is done in the same way as adding a state change note."
13075 (interactive)
13076 (org-add-log-setup 'note))
13078 (defun org-log-beginning (&optional create)
13079 "Return expected start of log notes in current entry.
13080 When optional argument CREATE is non-nil, the function creates
13081 a drawer to store notes, if necessary. Returned position ignores
13082 narrowing."
13083 (org-with-wide-buffer
13084 (let ((drawer (org-log-into-drawer)))
13085 (cond
13086 (drawer
13087 (org-end-of-meta-data)
13088 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13089 (end (if (org-at-heading-p) (point)
13090 (save-excursion (outline-next-heading) (point))))
13091 (case-fold-search t))
13092 (catch 'exit
13093 ;; Try to find existing drawer.
13094 (while (re-search-forward regexp end t)
13095 (let ((element (org-element-at-point)))
13096 (when (eq (org-element-type element) 'drawer)
13097 (let ((cend (org-element-property :contents-end element)))
13098 (when (and (not org-log-states-order-reversed) cend)
13099 (goto-char cend)))
13100 (throw 'exit nil))))
13101 ;; No drawer found. Create one, if permitted.
13102 (when create
13103 (unless (bolp) (insert "\n"))
13104 (let ((beg (point)))
13105 (insert ":" drawer ":\n:END:\n")
13106 (org-indent-region beg (point))
13107 (org-flag-region
13108 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13109 (end-of-line -1)))))
13111 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13112 (skip-chars-forward " \t\n")
13113 (beginning-of-line)
13114 (unless org-log-states-order-reversed
13115 (org-skip-over-state-notes)
13116 (skip-chars-backward " \t\n")
13117 (forward-line)))))
13118 (if (bolp) (point) (line-beginning-position 2))))
13120 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13121 "Set up the post command hook to take a note.
13122 If this is about to TODO state change, the new state is expected in STATE.
13123 HOW is an indicator what kind of note should be created.
13124 EXTRA is additional text that will be inserted into the notes buffer."
13125 (move-marker org-log-note-marker (point))
13126 (setq org-log-note-purpose purpose
13127 org-log-note-state state
13128 org-log-note-previous-state prev-state
13129 org-log-note-how how
13130 org-log-note-extra extra
13131 org-log-note-effective-time (org-current-effective-time))
13132 (add-hook 'post-command-hook 'org-add-log-note 'append))
13134 (defun org-skip-over-state-notes ()
13135 "Skip past the list of State notes in an entry."
13136 (when (ignore-errors (goto-char (org-in-item-p)))
13137 (let* ((struct (org-list-struct))
13138 (prevs (org-list-prevs-alist struct))
13139 (regexp
13140 (concat "[ \t]*- +"
13141 (replace-regexp-in-string
13142 " +" " +"
13143 (org-replace-escapes
13144 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13145 `(("%d" . ,org-ts-regexp-inactive)
13146 ("%D" . ,org-ts-regexp)
13147 ("%s" . "\"\\S-+\"")
13148 ("%S" . "\"\\S-+\"")
13149 ("%t" . ,org-ts-regexp-inactive)
13150 ("%T" . ,org-ts-regexp)
13151 ("%u" . ".*?")
13152 ("%U" . ".*?")))))))
13153 (while (looking-at-p regexp)
13154 (goto-char (or (org-list-get-next-item (point) struct prevs)
13155 (org-list-get-item-end (point) struct)))))))
13157 (defun org-add-log-note (&optional _purpose)
13158 "Pop up a window for taking a note, and add this note later."
13159 (remove-hook 'post-command-hook 'org-add-log-note)
13160 (setq org-log-note-window-configuration (current-window-configuration))
13161 (delete-other-windows)
13162 (move-marker org-log-note-return-to (point))
13163 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13164 (goto-char org-log-note-marker)
13165 (org-switch-to-buffer-other-window "*Org Note*")
13166 (erase-buffer)
13167 (if (memq org-log-note-how '(time state))
13168 (org-store-log-note)
13169 (let ((org-inhibit-startup t)) (org-mode))
13170 (insert (format "# Insert note for %s.
13171 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13172 (cond
13173 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13174 ((eq org-log-note-purpose 'done) "closed todo item")
13175 ((eq org-log-note-purpose 'state)
13176 (format "state change from \"%s\" to \"%s\""
13177 (or org-log-note-previous-state "")
13178 (or org-log-note-state "")))
13179 ((eq org-log-note-purpose 'reschedule)
13180 "rescheduling")
13181 ((eq org-log-note-purpose 'delschedule)
13182 "no longer scheduled")
13183 ((eq org-log-note-purpose 'redeadline)
13184 "changing deadline")
13185 ((eq org-log-note-purpose 'deldeadline)
13186 "removing deadline")
13187 ((eq org-log-note-purpose 'refile)
13188 "refiling")
13189 ((eq org-log-note-purpose 'note)
13190 "this entry")
13191 (t (error "This should not happen")))))
13192 (when org-log-note-extra (insert org-log-note-extra))
13193 (setq-local org-finish-function 'org-store-log-note)
13194 (run-hooks 'org-log-buffer-setup-hook)))
13196 (defvar org-note-abort nil) ; dynamically scoped
13197 (defun org-store-log-note ()
13198 "Finish taking a log note, and insert it to where it belongs."
13199 (let ((txt (prog1 (buffer-string)
13200 (kill-buffer)))
13201 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13202 lines)
13203 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13204 (setq txt (replace-match "" t t txt)))
13205 (when (string-match "\\s-+\\'" txt)
13206 (setq txt (replace-match "" t t txt)))
13207 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13208 (when (org-string-nw-p note)
13209 (setq note
13210 (org-replace-escapes
13211 note
13212 (list (cons "%u" (user-login-name))
13213 (cons "%U" user-full-name)
13214 (cons "%t" (format-time-string
13215 (org-time-stamp-format 'long 'inactive)
13216 org-log-note-effective-time))
13217 (cons "%T" (format-time-string
13218 (org-time-stamp-format 'long nil)
13219 org-log-note-effective-time))
13220 (cons "%d" (format-time-string
13221 (org-time-stamp-format nil 'inactive)
13222 org-log-note-effective-time))
13223 (cons "%D" (format-time-string
13224 (org-time-stamp-format nil nil)
13225 org-log-note-effective-time))
13226 (cons "%s" (cond
13227 ((not org-log-note-state) "")
13228 ((string-match-p org-ts-regexp
13229 org-log-note-state)
13230 (format "\"[%s]\""
13231 (substring org-log-note-state 1 -1)))
13232 (t (format "\"%s\"" org-log-note-state))))
13233 (cons "%S"
13234 (cond
13235 ((not org-log-note-previous-state) "")
13236 ((string-match-p org-ts-regexp
13237 org-log-note-previous-state)
13238 (format "\"[%s]\""
13239 (substring
13240 org-log-note-previous-state 1 -1)))
13241 (t (format "\"%s\""
13242 org-log-note-previous-state)))))))
13243 (when lines (setq note (concat note " \\\\")))
13244 (push note lines))
13245 (when (and lines (not org-note-abort))
13246 (with-current-buffer (marker-buffer org-log-note-marker)
13247 (org-with-wide-buffer
13248 ;; Find location for the new note.
13249 (goto-char org-log-note-marker)
13250 (set-marker org-log-note-marker nil)
13251 ;; Note associated to a clock is to be located right after
13252 ;; the clock. Do not move point.
13253 (unless (eq org-log-note-purpose 'clock-out)
13254 (goto-char (org-log-beginning t)))
13255 ;; Make sure point is at the beginning of an empty line.
13256 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13257 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13258 ;; In an existing list, add a new item at the top level.
13259 ;; Otherwise, indent line like a regular one.
13260 (let ((itemp (org-in-item-p)))
13261 (if itemp
13262 (indent-line-to
13263 (let ((struct (save-excursion
13264 (goto-char itemp) (org-list-struct))))
13265 (org-list-get-ind (org-list-get-top-point struct) struct)))
13266 (org-indent-line)))
13267 (insert (org-list-bullet-string "-") (pop lines))
13268 (let ((ind (org-list-item-body-column (line-beginning-position))))
13269 (dolist (line lines)
13270 (insert "\n")
13271 (indent-line-to ind)
13272 (insert line)))
13273 (message "Note stored")
13274 (org-back-to-heading t))
13275 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13276 ;; from within `org-add-log-note' because `buffer-undo-list'
13277 ;; is then modified outside of `org-with-remote-undo'.
13278 (when (eq this-command 'org-agenda-todo)
13279 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13280 ;; Don't add undo information when called from `org-agenda-todo'.
13281 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13282 (set-window-configuration org-log-note-window-configuration)
13283 (with-current-buffer (marker-buffer org-log-note-return-to)
13284 (goto-char org-log-note-return-to))
13285 (move-marker org-log-note-return-to nil)
13286 (when org-log-post-message (message "%s" org-log-post-message))))
13288 (defun org-remove-empty-drawer-at (pos)
13289 "Remove an empty drawer at position POS.
13290 POS may also be a marker."
13291 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13292 (org-with-wide-buffer
13293 (goto-char pos)
13294 (let ((drawer (org-element-at-point)))
13295 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13296 (not (org-element-property :contents-begin drawer)))
13297 (delete-region (org-element-property :begin drawer)
13298 (progn (goto-char (org-element-property :end drawer))
13299 (skip-chars-backward " \r\t\n")
13300 (forward-line)
13301 (point))))))))
13303 (defvar org-ts-type nil)
13304 (defun org-sparse-tree (&optional arg type)
13305 "Create a sparse tree, prompt for the details.
13306 This command can create sparse trees. You first need to select the type
13307 of match used to create the tree:
13309 t Show all TODO entries.
13310 T Show entries with a specific TODO keyword.
13311 m Show entries selected by a tags/property match.
13312 p Enter a property name and its value (both with completion on existing
13313 names/values) and show entries with that property.
13314 r Show entries matching a regular expression (`/' can be used as well).
13315 b Show deadlines and scheduled items before a date.
13316 a Show deadlines and scheduled items after a date.
13317 d Show deadlines due within `org-deadline-warning-days'.
13318 D Show deadlines and scheduled items between a date range."
13319 (interactive "P")
13320 (setq type (or type org-sparse-tree-default-date-type))
13321 (setq org-ts-type type)
13322 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13323 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13324 \[c]ycle through date types: %s"
13325 (cl-case type
13326 (all "all timestamps")
13327 (scheduled "only scheduled")
13328 (deadline "only deadline")
13329 (active "only active timestamps")
13330 (inactive "only inactive timestamps")
13331 (closed "with a closed time-stamp")
13332 (otherwise "scheduled/deadline")))
13333 (let ((answer (read-char-exclusive)))
13334 (cl-case answer
13336 (org-sparse-tree
13338 (cadr
13339 (memq type '(nil all scheduled deadline active inactive closed)))))
13340 (?d (call-interactively 'org-check-deadlines))
13341 (?b (call-interactively 'org-check-before-date))
13342 (?a (call-interactively 'org-check-after-date))
13343 (?D (call-interactively 'org-check-dates-range))
13344 (?t (call-interactively 'org-show-todo-tree))
13345 (?T (org-show-todo-tree '(4)))
13346 (?m (call-interactively 'org-match-sparse-tree))
13347 ((?p ?P)
13348 (let* ((kwd (completing-read
13349 "Property: " (mapcar #'list (org-buffer-property-keys))))
13350 (value (completing-read
13351 "Value: " (mapcar #'list (org-property-values kwd)))))
13352 (unless (string-match "\\`{.*}\\'" value)
13353 (setq value (concat "\"" value "\"")))
13354 (org-match-sparse-tree arg (concat kwd "=" value))))
13355 ((?r ?R ?/) (call-interactively 'org-occur))
13356 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13358 (defvar-local org-occur-highlights nil
13359 "List of overlays used for occur matches.")
13360 (defvar-local org-occur-parameters nil
13361 "Parameters of the active org-occur calls.
13362 This is a list, each call to org-occur pushes as cons cell,
13363 containing the regular expression and the callback, onto the list.
13364 The list can contain several entries if `org-occur' has been called
13365 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13366 will only contain one set of parameters. When the highlights are
13367 removed (for example with `C-c C-c', or with the next edit (depending
13368 on `org-remove-highlights-with-change'), this variable is emptied
13369 as well.")
13371 (defun org-occur (regexp &optional keep-previous callback)
13372 "Make a compact tree which shows all matches of REGEXP.
13374 The tree will show the lines where the regexp matches, and any other context
13375 defined in `org-show-context-detail', which see.
13377 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13378 done by a previous call to `org-occur' will be kept, to allow stacking of
13379 calls to this command.
13381 Optional argument CALLBACK can be a function of no argument. In this case,
13382 it is called with point at the end of the match, match data being set
13383 accordingly. Current match is shown only if the return value is non-nil.
13384 The function must neither move point nor alter narrowing."
13385 (interactive "sRegexp: \nP")
13386 (when (equal regexp "")
13387 (user-error "Regexp cannot be empty"))
13388 (unless keep-previous
13389 (org-remove-occur-highlights nil nil t))
13390 (push (cons regexp callback) org-occur-parameters)
13391 (let ((cnt 0))
13392 (save-excursion
13393 (goto-char (point-min))
13394 (when (or (not keep-previous) ; do not want to keep
13395 (not org-occur-highlights)) ; no previous matches
13396 ;; hide everything
13397 (org-overview))
13398 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13399 (isearch-no-upper-case-p regexp t)
13400 org-occur-case-fold-search)))
13401 (while (re-search-forward regexp nil t)
13402 (when (or (not callback)
13403 (save-match-data (funcall callback)))
13404 (setq cnt (1+ cnt))
13405 (when org-highlight-sparse-tree-matches
13406 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13407 (org-show-context 'occur-tree)))))
13408 (when org-remove-highlights-with-change
13409 (add-hook 'before-change-functions 'org-remove-occur-highlights
13410 nil 'local))
13411 (unless org-sparse-tree-open-archived-trees
13412 (org-hide-archived-subtrees (point-min) (point-max)))
13413 (run-hooks 'org-occur-hook)
13414 (when (called-interactively-p 'interactive)
13415 (message "%d match(es) for regexp %s" cnt regexp))
13416 cnt))
13418 (defun org-occur-next-match (&optional n _reset)
13419 "Function for `next-error-function' to find sparse tree matches.
13420 N is the number of matches to move, when negative move backwards.
13421 This function always goes back to the starting point when no
13422 match is found."
13423 (let* ((limit (if (< n 0) (point-min) (point-max)))
13424 (search-func (if (< n 0)
13425 'previous-single-char-property-change
13426 'next-single-char-property-change))
13427 (n (abs n))
13428 (pos (point))
13430 (catch 'exit
13431 (while (setq p1 (funcall search-func (point) 'org-type))
13432 (when (equal p1 limit)
13433 (goto-char pos)
13434 (user-error "No more matches"))
13435 (when (equal (get-char-property p1 'org-type) 'org-occur)
13436 (setq n (1- n))
13437 (when (= n 0)
13438 (goto-char p1)
13439 (throw 'exit (point))))
13440 (goto-char p1))
13441 (goto-char p1)
13442 (user-error "No more matches"))))
13444 (defun org-highlight-new-match (beg end)
13445 "Highlight from BEG to END and mark the highlight is an occur headline."
13446 (let ((ov (make-overlay beg end)))
13447 (overlay-put ov 'face 'secondary-selection)
13448 (overlay-put ov 'org-type 'org-occur)
13449 (push ov org-occur-highlights)))
13451 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13452 "Remove the occur highlights from the buffer.
13453 BEG and END are ignored. If NOREMOVE is nil, remove this function
13454 from the `before-change-functions' in the current buffer."
13455 (interactive)
13456 (unless org-inhibit-highlight-removal
13457 (mapc #'delete-overlay org-occur-highlights)
13458 (setq org-occur-highlights nil)
13459 (setq org-occur-parameters nil)
13460 (unless noremove
13461 (remove-hook 'before-change-functions
13462 'org-remove-occur-highlights 'local))))
13464 ;;;; Priorities
13466 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13467 "Regular expression matching the priority indicator.")
13469 (defvar org-remove-priority-next-time nil)
13471 (defun org-priority-up ()
13472 "Increase the priority of the current item."
13473 (interactive)
13474 (org-priority 'up))
13476 (defun org-priority-down ()
13477 "Decrease the priority of the current item."
13478 (interactive)
13479 (org-priority 'down))
13481 (defun org-priority (&optional action _show)
13482 "Change the priority of an item.
13483 ACTION can be `set', `up', `down', or a character."
13484 (interactive "P")
13485 (if (equal action '(4))
13486 (org-show-priority)
13487 (unless org-enable-priority-commands
13488 (user-error "Priority commands are disabled"))
13489 (setq action (or action 'set))
13490 (let (current new news have remove)
13491 (save-excursion
13492 (org-back-to-heading t)
13493 (when (looking-at org-priority-regexp)
13494 (setq current (string-to-char (match-string 2))
13495 have t))
13496 (cond
13497 ((eq action 'remove)
13498 (setq remove t new ?\ ))
13499 ((or (eq action 'set)
13500 (integerp action))
13501 (if (not (eq action 'set))
13502 (setq new action)
13503 (message "Priority %c-%c, SPC to remove: "
13504 org-highest-priority org-lowest-priority)
13505 (save-match-data
13506 (setq new (read-char-exclusive))))
13507 (when (and (= (upcase org-highest-priority) org-highest-priority)
13508 (= (upcase org-lowest-priority) org-lowest-priority))
13509 (setq new (upcase new)))
13510 (cond ((equal new ?\ ) (setq remove t))
13511 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13512 (user-error "Priority must be between `%c' and `%c'"
13513 org-highest-priority org-lowest-priority))))
13514 ((eq action 'up)
13515 (setq new (if have
13516 (1- current) ; normal cycling
13517 ;; last priority was empty
13518 (if (eq last-command this-command)
13519 org-lowest-priority ; wrap around empty to lowest
13520 ;; default
13521 (if org-priority-start-cycle-with-default
13522 org-default-priority
13523 (1- org-default-priority))))))
13524 ((eq action 'down)
13525 (setq new (if have
13526 (1+ current) ; normal cycling
13527 ;; last priority was empty
13528 (if (eq last-command this-command)
13529 org-highest-priority ; wrap around empty to highest
13530 ;; default
13531 (if org-priority-start-cycle-with-default
13532 org-default-priority
13533 (1+ org-default-priority))))))
13534 (t (user-error "Invalid action")))
13535 (when (or (< (upcase new) org-highest-priority)
13536 (> (upcase new) org-lowest-priority))
13537 (if (and (memq action '(up down))
13538 (not have) (not (eq last-command this-command)))
13539 ;; `new' is from default priority
13540 (error
13541 "The default can not be set, see `org-default-priority' why")
13542 ;; normal cycling: `new' is beyond highest/lowest priority
13543 ;; and is wrapped around to the empty priority
13544 (setq remove t)))
13545 (setq news (format "%c" new))
13546 (if have
13547 (if remove
13548 (replace-match "" t t nil 1)
13549 (replace-match news t t nil 2))
13550 (if remove
13551 (user-error "No priority cookie found in line")
13552 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13553 (if (match-end 2)
13554 (progn
13555 (goto-char (match-end 2))
13556 (insert " [#" news "]"))
13557 (goto-char (match-beginning 3))
13558 (insert "[#" news "] "))))
13559 (org-align-tags))
13560 (if remove
13561 (message "Priority removed")
13562 (message "Priority of current item set to %s" news)))))
13564 (defun org-show-priority ()
13565 "Show the priority of the current item.
13566 This priority is composed of the main priority given with the [#A] cookies,
13567 and by additional input from the age of a schedules or deadline entry."
13568 (interactive)
13569 (let ((pri (if (eq major-mode 'org-agenda-mode)
13570 (org-get-at-bol 'priority)
13571 (save-excursion
13572 (save-match-data
13573 (beginning-of-line)
13574 (and (looking-at org-heading-regexp)
13575 (org-get-priority (match-string 0))))))))
13576 (message "Priority is %d" (if pri pri -1000))))
13578 (defun org-get-priority (s)
13579 "Find priority cookie and return priority."
13580 (save-match-data
13581 (if (functionp org-get-priority-function)
13582 (funcall org-get-priority-function)
13583 (if (not (string-match org-priority-regexp s))
13584 (* 1000 (- org-lowest-priority org-default-priority))
13585 (* 1000 (- org-lowest-priority
13586 (string-to-char (match-string 2 s))))))))
13588 ;;;; Tags
13590 (defvar org-agenda-archives-mode)
13591 (defvar org-map-continue-from nil
13592 "Position from where mapping should continue.
13593 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13595 (defvar org-scanner-tags nil
13596 "The current tag list while the tags scanner is running.")
13598 (defvar org-trust-scanner-tags nil
13599 "Should `org-get-tags' use the tags for the scanner.
13600 This is for internal dynamical scoping only.
13601 When this is non-nil, the function `org-get-tags' will return the value
13602 of `org-scanner-tags' instead of building the list by itself. This
13603 can lead to large speed-ups when the tags scanner is used in a file with
13604 many entries, and when the list of tags is retrieved, for example to
13605 obtain a list of properties. Building the tags list for each entry in such
13606 a file becomes an N^2 operation - but with this variable set, it scales
13607 as N.")
13609 (defvar org--matcher-tags-todo-only nil)
13611 (defun org-scan-tags (action matcher todo-only &optional start-level)
13612 "Scan headline tags with inheritance and produce output ACTION.
13614 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13615 or `agenda' to produce an entry list for an agenda view. It can also be
13616 a Lisp form or a function that should be called at each matched headline, in
13617 this case the return value is a list of all return values from these calls.
13619 MATCHER is a function accepting three arguments, returning
13620 a non-nil value whenever a given set of tags qualifies a headline
13621 for inclusion. See `org-make-tags-matcher' for more information.
13622 As a special case, it can also be set to t (respectively nil) in
13623 order to match all (respectively none) headline.
13625 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13626 included in the output.
13628 START-LEVEL can be a string with asterisks, reducing the scope to
13629 headlines matching this string."
13630 (require 'org-agenda)
13631 (let* ((re (concat "^"
13632 (if start-level
13633 ;; Get the correct level to match
13634 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13635 org-outline-regexp)
13636 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
13637 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
13638 (props (list 'face 'default
13639 'done-face 'org-agenda-done
13640 'undone-face 'default
13641 'mouse-face 'highlight
13642 'org-not-done-regexp org-not-done-regexp
13643 'org-todo-regexp org-todo-regexp
13644 'org-complex-heading-regexp org-complex-heading-regexp
13645 'help-echo
13646 (format "mouse-2 or RET jump to Org file %S"
13647 (abbreviate-file-name
13648 (or (buffer-file-name (buffer-base-buffer))
13649 (buffer-name (buffer-base-buffer)))))))
13650 (org-map-continue-from nil)
13651 lspos tags tags-list
13652 (tags-alist (list (cons 0 org-file-tags)))
13653 (llast 0) rtn rtn1 level category i txt
13654 todo marker entry priority
13655 ts-date ts-date-type ts-date-pair)
13656 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13657 (setq action (list 'lambda nil action)))
13658 (save-excursion
13659 (goto-char (point-min))
13660 (when (eq action 'sparse-tree)
13661 (org-overview)
13662 (org-remove-occur-highlights))
13663 (while (let (case-fold-search)
13664 (re-search-forward re nil t))
13665 (setq org-map-continue-from nil)
13666 (catch :skip
13667 ;; Ignore closing parts of inline tasks.
13668 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13669 (throw :skip t))
13670 (setq todo
13671 ;; TODO: is the 1-2 difference a bug?
13672 (when (match-end 1) (match-string-no-properties 2))
13673 tags (when (match-end 4) (match-string-no-properties 4)))
13674 (goto-char (setq lspos (match-beginning 0)))
13675 (setq level (org-reduced-level (org-outline-level))
13676 category (org-get-category))
13677 (when (eq action 'agenda)
13678 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13679 ts-date (car ts-date-pair)
13680 ts-date-type (cdr ts-date-pair)))
13681 (setq i llast llast level)
13682 ;; remove tag lists from same and sublevels
13683 (while (>= i level)
13684 (when (setq entry (assoc i tags-alist))
13685 (setq tags-alist (delete entry tags-alist)))
13686 (setq i (1- i)))
13687 ;; add the next tags
13688 (when tags
13689 (setq tags (org-split-string tags ":")
13690 tags-alist
13691 (cons (cons level tags) tags-alist)))
13692 ;; compile tags for current headline
13693 (setq tags-list
13694 (if org-use-tag-inheritance
13695 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13696 tags)
13697 org-scanner-tags tags-list)
13698 (when org-use-tag-inheritance
13699 (setcdr (car tags-alist)
13700 (mapcar (lambda (x)
13701 (setq x (copy-sequence x))
13702 (org-add-prop-inherited x))
13703 (cdar tags-alist))))
13704 (when (and tags org-use-tag-inheritance
13705 (or (not (eq t org-use-tag-inheritance))
13706 org-tags-exclude-from-inheritance))
13707 ;; Selective inheritance, remove uninherited ones.
13708 (setcdr (car tags-alist)
13709 (org-remove-uninherited-tags (cdar tags-alist))))
13710 (when (and
13712 ;; eval matcher only when the todo condition is OK
13713 (and (or (not todo-only) (member todo org-todo-keywords-1))
13714 (if (functionp matcher)
13715 (let ((case-fold-search t) (org-trust-scanner-tags t))
13716 (funcall matcher todo tags-list level))
13717 matcher))
13719 ;; Call the skipper, but return t if it does not
13720 ;; skip, so that the `and' form continues evaluating.
13721 (progn
13722 (unless (eq action 'sparse-tree) (org-agenda-skip))
13725 ;; Check if timestamps are deselecting this entry
13726 (or (not todo-only)
13727 (and (member todo org-todo-keywords-1)
13728 (or (not org-agenda-tags-todo-honor-ignore-options)
13729 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13731 ;; select this headline
13732 (cond
13733 ((eq action 'sparse-tree)
13734 (and org-highlight-sparse-tree-matches
13735 (org-get-heading) (match-end 0)
13736 (org-highlight-new-match
13737 (match-beginning 1) (match-end 1)))
13738 (org-show-context 'tags-tree))
13739 ((eq action 'agenda)
13740 (setq txt (org-agenda-format-item
13742 (concat
13743 (if (eq org-tags-match-list-sublevels 'indented)
13744 (make-string (1- level) ?.) "")
13745 (org-get-heading))
13746 (make-string level ?\s)
13747 category
13748 tags-list)
13749 priority (org-get-priority txt))
13750 (goto-char lspos)
13751 (setq marker (org-agenda-new-marker))
13752 (org-add-props txt props
13753 'org-marker marker 'org-hd-marker marker 'org-category category
13754 'todo-state todo
13755 'ts-date ts-date
13756 'priority priority
13757 'type (concat "tagsmatch" ts-date-type))
13758 (push txt rtn))
13759 ((functionp action)
13760 (setq org-map-continue-from nil)
13761 (save-excursion
13762 (setq rtn1 (funcall action))
13763 (push rtn1 rtn)))
13764 (t (user-error "Invalid action")))
13766 ;; if we are to skip sublevels, jump to end of subtree
13767 (unless org-tags-match-list-sublevels
13768 (org-end-of-subtree t)
13769 (backward-char 1))))
13770 ;; Get the correct position from where to continue
13771 (if org-map-continue-from
13772 (goto-char org-map-continue-from)
13773 (and (= (point) lspos) (end-of-line 1)))))
13774 (when (and (eq action 'sparse-tree)
13775 (not org-sparse-tree-open-archived-trees))
13776 (org-hide-archived-subtrees (point-min) (point-max)))
13777 (nreverse rtn)))
13779 (defun org-remove-uninherited-tags (tags)
13780 "Remove all tags that are not inherited from the list TAGS."
13781 (cond
13782 ((eq org-use-tag-inheritance t)
13783 (if org-tags-exclude-from-inheritance
13784 (org-delete-all org-tags-exclude-from-inheritance tags)
13785 tags))
13786 ((not org-use-tag-inheritance) nil)
13787 ((stringp org-use-tag-inheritance)
13788 (delq nil (mapcar
13789 (lambda (x)
13790 (if (and (string-match org-use-tag-inheritance x)
13791 (not (member x org-tags-exclude-from-inheritance)))
13792 x nil))
13793 tags)))
13794 ((listp org-use-tag-inheritance)
13795 (delq nil (mapcar
13796 (lambda (x)
13797 (if (member x org-use-tag-inheritance) x nil))
13798 tags)))))
13800 (defun org-match-sparse-tree (&optional todo-only match)
13801 "Create a sparse tree according to tags string MATCH.
13803 MATCH is a string with match syntax. It can contain a selection
13804 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13805 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13806 those. See the manual for details.
13808 If optional argument TODO-ONLY is non-nil, only select lines that
13809 are also TODO tasks."
13810 (interactive "P")
13811 (org-agenda-prepare-buffers (list (current-buffer)))
13812 (let ((org--matcher-tags-todo-only todo-only))
13813 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13814 org--matcher-tags-todo-only)))
13816 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13818 (defvar org-cached-props nil)
13819 (defun org-cached-entry-get (pom property)
13820 (if (or (eq t org-use-property-inheritance)
13821 (and (stringp org-use-property-inheritance)
13822 (let ((case-fold-search t))
13823 (string-match-p org-use-property-inheritance property)))
13824 (and (listp org-use-property-inheritance)
13825 (member-ignore-case property org-use-property-inheritance)))
13826 ;; Caching is not possible, check it directly.
13827 (org-entry-get pom property 'inherit)
13828 ;; Get all properties, so we can do complicated checks easily.
13829 (cdr (assoc-string property
13830 (or org-cached-props
13831 (setq org-cached-props (org-entry-properties pom)))
13832 t))))
13834 (defun org-global-tags-completion-table (&optional files)
13835 "Return the list of all tags in all agenda buffer/files.
13836 Optional FILES argument is a list of files which can be used
13837 instead of the agenda files."
13838 (save-excursion
13839 (org-uniquify
13840 (delq nil
13841 (apply #'append
13842 (mapcar
13843 (lambda (file)
13844 (set-buffer (find-file-noselect file))
13845 (org-tag-add-to-alist
13846 (org-get-buffer-tags)
13847 (mapcar (lambda (x)
13848 (and (stringp (car-safe x))
13849 (list (car-safe x))))
13850 org-current-tag-alist)))
13851 (if (car-safe files) files
13852 (org-agenda-files))))))))
13854 (defun org-make-tags-matcher (match)
13855 "Create the TAGS/TODO matcher form for the selection string MATCH.
13857 Returns a cons of the selection string MATCH and a function
13858 implementing the matcher.
13860 The matcher is to be called at an Org entry, with point on the
13861 headline, and returns non-nil if the entry matches the selection
13862 string MATCH. It must be called with three arguments: the TODO
13863 keyword at the entry (or nil if none), the list of all tags at
13864 the entry including inherited ones and the reduced level of the
13865 headline. Additionally, the category of the entry, if any, must
13866 be specified as the text property `org-category' on the headline.
13868 This function sets the variable `org--matcher-tags-todo-only' to
13869 a non-nil value if the matcher restricts matching to TODO
13870 entries, otherwise it is not touched.
13872 See also `org-scan-tags'."
13873 (unless match
13874 ;; Get a new match request, with completion against the global
13875 ;; tags table and the local tags in current buffer.
13876 (let ((org-last-tags-completion-table
13877 (org-tag-add-to-alist
13878 (org-get-buffer-tags)
13879 (org-global-tags-completion-table))))
13880 (setq match
13881 (completing-read
13882 "Match: "
13883 'org-tags-completion-function nil nil nil 'org-tags-history))))
13885 (let ((match0 match)
13886 (re (concat
13887 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
13888 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
13889 "\\([<>=]\\{1,2\\}\\)"
13890 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
13891 "\\|" org-tag-re "\\)"))
13892 (start 0)
13893 tagsmatch todomatch tagsmatcher todomatcher)
13895 ;; Expand group tags.
13896 (setq match (org-tags-expand match))
13898 ;; Check if there is a TODO part of this match, which would be the
13899 ;; part after a "/". To make sure that this slash is not part of
13900 ;; a property value to be matched against, we also check that
13901 ;; there is no / after that slash. First, find the last slash.
13902 (let ((s 0))
13903 (while (string-match "/+" match s)
13904 (setq start (match-beginning 0))
13905 (setq s (match-end 0))))
13906 (if (and (string-match "/+" match start)
13907 (not (string-match-p "\"" match start)))
13908 ;; Match contains also a TODO-matching request.
13909 (progn
13910 (setq tagsmatch (substring match 0 (match-beginning 0)))
13911 (setq todomatch (substring match (match-end 0)))
13912 (when (string-prefix-p "!" todomatch)
13913 (setq org--matcher-tags-todo-only t)
13914 (setq todomatch (substring todomatch 1)))
13915 (when (string-match "\\`\\s-*\\'" todomatch)
13916 (setq todomatch nil)))
13917 ;; Only matching tags.
13918 (setq tagsmatch match)
13919 (setq todomatch nil))
13921 ;; Make the tags matcher.
13922 (when (org-string-nw-p tagsmatch)
13923 (let ((orlist nil)
13924 (orterms (org-split-string tagsmatch "|"))
13925 term)
13926 (while (setq term (pop orterms))
13927 (while (and (equal (substring term -1) "\\") orterms)
13928 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13929 (while (string-match re term)
13930 (let* ((rest (substring term (match-end 0)))
13931 (minus (and (match-end 1)
13932 (equal (match-string 1 term) "-")))
13933 (tag (save-match-data
13934 (replace-regexp-in-string
13935 "\\\\-" "-" (match-string 2 term))))
13936 (regexp (eq (string-to-char tag) ?{))
13937 (levelp (match-end 4))
13938 (propp (match-end 5))
13940 (cond
13941 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13942 (levelp
13943 `(,(org-op-to-function (match-string 3 term))
13944 level
13945 ,(string-to-number (match-string 4 term))))
13946 (propp
13947 (let* ((gv (pcase (upcase (match-string 5 term))
13948 ("CATEGORY"
13949 '(get-text-property (point) 'org-category))
13950 ("TODO" 'todo)
13951 (p `(org-cached-entry-get nil ,p))))
13952 (pv (match-string 7 term))
13953 (regexp (eq (string-to-char pv) ?{))
13954 (strp (eq (string-to-char pv) ?\"))
13955 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13956 (po (org-op-to-function (match-string 6 term)
13957 (if timep 'time strp))))
13958 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13959 (when timep (setq pv (org-matcher-time pv)))
13960 (cond ((and regexp (eq po '/=))
13961 `(not (string-match ,pv (or ,gv ""))))
13962 (regexp `(string-match ,pv (or ,gv "")))
13963 (strp `(,po (or ,gv "") ,pv))
13965 `(,po
13966 (string-to-number (or ,gv ""))
13967 ,(string-to-number pv))))))
13968 (t `(member ,tag tags-list)))))
13969 (push (if minus `(not ,mm) mm) tagsmatcher)
13970 (setq term rest)))
13971 (push `(and ,@tagsmatcher) orlist)
13972 (setq tagsmatcher nil))
13973 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13975 ;; Make the TODO matcher.
13976 (when (org-string-nw-p todomatch)
13977 (let ((orlist nil))
13978 (dolist (term (org-split-string todomatch "|"))
13979 (while (string-match re term)
13980 (let* ((minus (and (match-end 1)
13981 (equal (match-string 1 term) "-")))
13982 (kwd (match-string 2 term))
13983 (regexp (eq (string-to-char kwd) ?{))
13984 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13985 `(equal todo ,kwd))))
13986 (push (if minus `(not ,mm) mm) todomatcher))
13987 (setq term (substring term (match-end 0))))
13988 (push (if (> (length todomatcher) 1)
13989 (cons 'and todomatcher)
13990 (car todomatcher))
13991 orlist)
13992 (setq todomatcher nil))
13993 (setq todomatcher (cons 'or orlist))))
13995 ;; Return the string and function of the matcher. If no
13996 ;; tags-specific or todo-specific matcher exists, match
13997 ;; everything.
13998 (let ((matcher (if (and tagsmatcher todomatcher)
13999 `(and ,tagsmatcher ,todomatcher)
14000 (or tagsmatcher todomatcher t))))
14001 (when org--matcher-tags-todo-only
14002 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14003 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14005 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14006 "Expand group tags in MATCH.
14008 This replaces every group tag in MATCH with a regexp tag search.
14009 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14010 will be replaced like this:
14012 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14013 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14014 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14016 Replacing by a regexp preserves the structure of the match.
14017 E.g., this expansion
14019 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14021 will match anything tagged with \"Lab\" and \"Home\", or tagged
14022 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14024 A group tag in MATCH can contain regular expressions of its own.
14025 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14026 will be replaced like this:
14028 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14030 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14031 assumed to be a single group tag, and the function will return
14032 the list of tags in this group.
14034 When DOWNCASE is non-nil, expand downcased TAGS."
14035 (if org-group-tags
14036 (let* ((case-fold-search t)
14037 (stable org-mode-syntax-table)
14038 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14039 (taggroups (if downcased
14040 (mapcar (lambda (tg) (mapcar #'downcase tg))
14041 taggroups)
14042 taggroups))
14043 (taggroups-keys (mapcar #'car taggroups))
14044 (return-match (if downcased (downcase match) match))
14045 (count 0)
14046 (work-already-expanded tags-already-expanded)
14047 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14048 ;; @ and _ are allowed as word-components in tags.
14049 (modify-syntax-entry ?@ "w" stable)
14050 (modify-syntax-entry ?_ "w" stable)
14051 ;; Temporarily replace regexp-expressions in the match-expression.
14052 (while (string-match "{.+?}" return-match)
14053 (cl-incf count)
14054 (push (match-string 0 return-match) regexps-in-match)
14055 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14056 (while (and taggroups-keys
14057 (with-syntax-table stable
14058 (string-match
14059 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14060 (regexp-opt taggroups-keys) "\\>\\)")
14061 return-match)))
14062 (let* ((dir (match-string 1 return-match))
14063 (tag (match-string 2 return-match))
14064 (tag (if downcased (downcase tag) tag)))
14065 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14066 (member tag tags-already-expanded))
14067 (setq tags-in-group (assoc tag taggroups))
14068 (push tag work-already-expanded)
14069 ;; Recursively expand each tag in the group, if the tag hasn't
14070 ;; already been expanded. Restore the match-data after all recursive calls.
14071 (save-match-data
14072 (let (tags-expanded)
14073 (dolist (x (cdr tags-in-group))
14074 (if (and (member x taggroups-keys)
14075 (not (member x work-already-expanded)))
14076 (setq tags-expanded
14077 (delete-dups
14078 (append
14079 (org-tags-expand x t downcased
14080 work-already-expanded)
14081 tags-expanded)))
14082 (setq tags-expanded
14083 (append (list x) tags-expanded)))
14084 (setq work-already-expanded
14085 (delete-dups
14086 (append tags-expanded
14087 work-already-expanded))))
14088 (setq tags-in-group
14089 (delete-dups (cons (car tags-in-group)
14090 tags-expanded)))))
14091 ;; Filter tag-regexps from tags.
14092 (setq regexp-in-group-escaped
14093 (delq nil (mapcar (lambda (x)
14094 (if (stringp x)
14095 (and (equal "{" (substring x 0 1))
14096 (equal "}" (substring x -1))
14099 tags-in-group))
14100 regexp-in-group
14101 (mapcar (lambda (x)
14102 (substring x 1 -1))
14103 regexp-in-group-escaped)
14104 tags-in-group
14105 (delq nil (mapcar (lambda (x)
14106 (if (stringp x)
14107 (and (not (equal "{" (substring x 0 1)))
14108 (not (equal "}" (substring x -1)))
14111 tags-in-group)))
14112 ;; If single-as-list, do no more in the while-loop.
14113 (if (not single-as-list)
14114 (progn
14115 (when regexp-in-group
14116 (setq regexp-in-group
14117 (concat "\\|"
14118 (mapconcat 'identity regexp-in-group
14119 "\\|"))))
14120 (setq tags-in-group
14121 (concat dir
14122 "{\\<"
14123 (regexp-opt tags-in-group)
14124 "\\>"
14125 regexp-in-group
14126 "}"))
14127 (when (stringp tags-in-group)
14128 (org-add-props tags-in-group '(grouptag t)))
14129 (setq return-match
14130 (replace-match tags-in-group t t return-match)))
14131 (setq tags-in-group
14132 (append regexp-in-group-escaped tags-in-group))))
14133 (setq taggroups-keys (delete tag taggroups-keys))))
14134 ;; Add the regular expressions back into the match-expression again.
14135 (while regexps-in-match
14136 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14137 (pop regexps-in-match)
14138 return-match t t))
14139 (cl-decf count))
14140 (if single-as-list
14141 (if tags-in-group tags-in-group (list return-match))
14142 return-match))
14143 (if single-as-list
14144 (list (if downcased (downcase match) match))
14145 match)))
14147 (defun org-op-to-function (op &optional stringp)
14148 "Turn an operator into the appropriate function."
14149 (setq op
14150 (cond
14151 ((equal op "<" ) '(< org-string< org-time<))
14152 ((equal op ">" ) '(> org-string> org-time>))
14153 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14154 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14155 ((member op '("=" "==")) '(= string= org-time=))
14156 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14157 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14159 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14160 (defvar org-tags-overlay (make-overlay 1 1))
14161 (delete-overlay org-tags-overlay)
14163 (defun org-add-prop-inherited (s)
14164 (add-text-properties 0 (length s) '(inherited t) s)
14167 (defun org-toggle-tag (tag &optional onoff)
14168 "Toggle the tag TAG for the current line.
14169 If ONOFF is `on' or `off', don't toggle but set to this state."
14170 (save-excursion
14171 (org-back-to-heading t)
14172 (let ((current
14173 ;; Reverse the tags list so any new tag is appended to the
14174 ;; current list of tags.
14175 (nreverse (org-get-tags)))
14176 res)
14177 (pcase onoff
14178 (`off (setq current (delete tag current)))
14179 ((or `on (guard (not (member tag current))))
14180 (setq res t)
14181 (cl-pushnew tag current :test #'equal))
14182 (_ (setq current (delete tag current))))
14183 (org-set-tags (nreverse current))
14184 res)))
14186 (defun org--align-tags-here (to-col)
14187 "Align tags on the current headline to TO-COL.
14188 Assume point is on a headline."
14189 (when (and (org-match-line org-tag-line-re)
14190 (< (point) (match-beginning 1)))
14191 (let ((pos (point))
14192 (shift (if (>= to-col 0) to-col
14193 (- (abs to-col) (string-width (match-string 1))))))
14194 ;; Delete all blanks before tags.
14195 (goto-char (match-beginning 1))
14196 (skip-chars-backward " \t")
14197 (delete-region (point) (match-beginning 1))
14198 ;; Insert new blanks.
14199 (insert (make-string (max 1 (- shift (current-column))) ?\s))
14200 ;; Preserve initial position, if possible. In any case, stop
14201 ;; before tags.
14202 (when (< pos (point)) (goto-char pos)))))
14204 (defun org-set-tags-command (&optional arg)
14205 "Set the tags for the current visible entry.
14207 When called with `\\[universal-argument]' prefix argument ARG,
14208 realign all tags in headings in the current buffer. If a region
14209 is active, set tags for all headlines in the region.
14211 This function is for interactive use only;
14212 in Lisp code use `org-set-tags' instead."
14213 (interactive "P")
14214 (cond
14215 (arg (org-align-tags t))
14216 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
14217 ;; Disable `org-loop-over-headlines-in-active-region' for
14218 ;; successive calls.
14219 (let (org-loop-over-headlines-in-active-region)
14220 (org-map-entries
14221 #'org-set-tags-command
14223 (if (eq org-loop-over-headlines-in-active-region 'start-level)
14224 'region-start-level
14225 'region)
14226 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
14228 (org-back-to-heading)
14229 (let* ((all-tags (org-get-tags))
14230 (table (setq org-last-tags-completion-table
14231 (org-tag-add-to-alist
14232 (and org-complete-tags-always-offer-all-agenda-tags
14233 (org-global-tags-completion-table
14234 (org-agenda-files)))
14235 (or org-current-tag-alist (org-get-buffer-tags)))))
14236 (current-tags
14237 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
14238 all-tags))
14239 (inherited-tags
14240 (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
14241 all-tags))
14242 (tags
14243 (replace-regexp-in-string
14244 ;; Ignore all forbidden characters in tags.
14245 "[^[:alnum:]_@#%]+" ":"
14246 (if (or (eq t org-use-fast-tag-selection)
14247 (and org-use-fast-tag-selection
14248 (delq nil (mapcar #'cdr table))))
14249 (org-fast-tag-selection
14250 current-tags
14251 inherited-tags
14252 table
14253 (and org-fast-tag-selection-include-todo org-todo-key-alist))
14254 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14255 (org-trim (completing-read
14256 "Tags: "
14257 #'org-tags-completion-function
14258 nil nil current-tags 'org-tags-history)))))))
14259 (org-set-tags tags)))))
14261 (defun org-align-tags (&optional all)
14262 "Align tags in current entry.
14263 When optional argument ALL is non-nil, align all tags in the
14264 visible part of the buffer."
14265 (save-excursion
14266 (if all (goto-char (point-min)) (org-back-to-heading t))
14267 (catch :single
14268 (while (re-search-forward org-tag-line-re nil t)
14269 (let* ((offset (if (bound-and-true-p org-indent-mode)
14270 (* (1- org-indent-indentation-per-level)
14271 (1- (org-current-level)))
14273 (tags-column (+ org-tags-column
14274 (if (> org-tags-column 0) (- offset) offset))))
14275 (beginning-of-line)
14276 (org--align-tags-here tags-column)
14277 (if all (forward-line) (throw :single nil)))))))
14279 (defun org-set-tags (tags)
14280 "Set the tags of the current entry to TAGS, replacing current tags.
14282 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
14283 If TAGS is nil or the empty string, all tags are removed.
14285 This function assumes point is on a headline."
14286 (let ((tags (pcase tags
14287 ((pred listp) tags)
14288 ((pred stringp) (split-string (org-trim tags) ":" t))
14289 (_ (error "Invalid tag specification: %S" tags))))
14290 (change-flag nil))
14291 (when (functionp org-tags-sort-function)
14292 (setq tags (sort tags org-tags-sort-function)))
14293 (org-with-wide-buffer
14294 (unless (equal tags (org-get-tags nil t))
14295 (setq change-flag t)
14296 ;; Delete previous tags and any trailing white space.
14297 (goto-char (if (looking-at org-tag-line-re) (match-beginning 1)
14298 (line-end-position)))
14299 (skip-chars-backward " \t")
14300 (delete-region (point) (line-end-position))
14301 (when tags
14302 (save-excursion (insert " " (org-make-tag-string tags)))
14303 ;; When text is being inserted on an invisible region
14304 ;; boundary, it can be inadvertently sucked into
14305 ;; invisibility.
14306 (unless (org-invisible-p (line-beginning-position))
14307 (org-flag-region (point) (line-end-position) nil 'outline))))
14308 ;; Align tags, if any. Fix tags column if `org-indent-mode' is
14309 ;; on.
14310 (when tags (org-align-tags))
14311 (when change-flag (run-hooks 'org-after-tags-change-hook)))))
14313 (defun org-change-tag-in-region (beg end tag off)
14314 "Add or remove TAG for each entry in the region.
14315 This works in the agenda, and also in an Org buffer."
14316 (interactive
14317 (list (region-beginning) (region-end)
14318 (let ((org-last-tags-completion-table
14319 (if (derived-mode-p 'org-mode)
14320 (org-tag-add-to-alist
14321 (org-get-buffer-tags)
14322 (org-global-tags-completion-table))
14323 (org-global-tags-completion-table))))
14324 (completing-read
14325 "Tag: " 'org-tags-completion-function nil nil nil
14326 'org-tags-history))
14327 (progn
14328 (message "[s]et or [r]emove? ")
14329 (equal (read-char-exclusive) ?r))))
14330 (when (fboundp 'deactivate-mark) (deactivate-mark))
14331 (let ((agendap (equal major-mode 'org-agenda-mode))
14332 l1 l2 m buf pos newhead (cnt 0))
14333 (goto-char end)
14334 (setq l2 (1- (org-current-line)))
14335 (goto-char beg)
14336 (setq l1 (org-current-line))
14337 (cl-loop for l from l1 to l2 do
14338 (org-goto-line l)
14339 (setq m (get-text-property (point) 'org-hd-marker))
14340 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14341 (and agendap m))
14342 (setq buf (if agendap (marker-buffer m) (current-buffer))
14343 pos (if agendap m (point)))
14344 (with-current-buffer buf
14345 (save-excursion
14346 (save-restriction
14347 (goto-char pos)
14348 (setq cnt (1+ cnt))
14349 (org-toggle-tag tag (if off 'off 'on))
14350 (setq newhead (org-get-heading)))))
14351 (and agendap (org-agenda-change-all-lines newhead m))))
14352 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14354 (defun org-tags-completion-function (string _predicate &optional flag)
14355 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14356 (confirm (lambda (x) (stringp (car x)))))
14357 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14358 (setq s1 (match-string 1 string)
14359 s2 (match-string 2 string))
14360 (setq s1 "" s2 string))
14361 (cond
14362 ((eq flag nil)
14363 ;; try completion
14364 (setq rtn (try-completion s2 ctable confirm))
14365 (when (stringp rtn)
14366 (setq rtn
14367 (concat s1 s2 (substring rtn (length s2))
14368 (if (and org-add-colon-after-tag-completion
14369 (assoc rtn ctable))
14370 ":" ""))))
14371 rtn)
14372 ((eq flag t)
14373 ;; all-completions
14374 (all-completions s2 ctable confirm))
14375 ((eq flag 'lambda)
14376 ;; exact match?
14377 (assoc s2 ctable)))))
14379 (defun org-fast-tag-insert (kwd tags face &optional end)
14380 "Insert KDW, and the TAGS, the latter with face FACE.
14381 Also insert END."
14382 (insert (format "%-12s" (concat kwd ":"))
14383 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14384 (or end "")))
14386 (defun org-fast-tag-show-exit (flag)
14387 (save-excursion
14388 (org-goto-line 3)
14389 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14390 (replace-match ""))
14391 (when flag
14392 (end-of-line 1)
14393 (org-move-to-column (- (window-width) 19) t)
14394 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14396 (defun org-set-current-tags-overlay (current prefix)
14397 "Add an overlay to CURRENT tag with PREFIX."
14398 (let ((s (org-make-tag-string current)))
14399 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14400 (org-overlay-display org-tags-overlay (concat prefix s))))
14402 (defvar org-last-tag-selection-key nil)
14403 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14404 "Fast tag selection with single keys.
14405 CURRENT is the current list of tags in the headline, INHERITED is the
14406 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14407 possibly with grouping information. TODO-TABLE is a similar table with
14408 TODO keywords, should these have keys assigned to them.
14409 If the keys are nil, a-z are automatically assigned.
14410 Returns the new tags string, or nil to not change the current settings."
14411 (let* ((fulltable (append table todo-table))
14412 (maxlen (apply 'max (mapcar
14413 (lambda (x)
14414 (if (stringp (car x)) (string-width (car x)) 0))
14415 fulltable)))
14416 (buf (current-buffer))
14417 (expert (eq org-fast-tag-selection-single-key 'expert))
14418 (buffer-tags nil)
14419 (fwidth (+ maxlen 3 1 3))
14420 (ncol (/ (- (window-width) 4) fwidth))
14421 (i-face 'org-done)
14422 (c-face 'org-todo)
14423 tg cnt e c char c1 c2 ntable tbl rtn
14424 ov-start ov-end ov-prefix
14425 (exit-after-next org-fast-tag-selection-single-key)
14426 (done-keywords org-done-keywords)
14427 groups ingroup intaggroup)
14428 (save-excursion
14429 (beginning-of-line)
14430 (if (looking-at org-tag-line-re)
14431 (setq ov-start (match-beginning 1)
14432 ov-end (match-end 1)
14433 ov-prefix "")
14434 (setq ov-start (1- (point-at-eol))
14435 ov-end (1+ ov-start))
14436 (skip-chars-forward "^\n\r")
14437 (setq ov-prefix
14438 (concat
14439 (buffer-substring (1- (point)) (point))
14440 (if (> (current-column) org-tags-column)
14442 (make-string (- org-tags-column (current-column)) ?\ ))))))
14443 (move-overlay org-tags-overlay ov-start ov-end)
14444 (save-window-excursion
14445 (if expert
14446 (set-buffer (get-buffer-create " *Org tags*"))
14447 (delete-other-windows)
14448 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14449 (org-switch-to-buffer-other-window " *Org tags*"))
14450 (erase-buffer)
14451 (setq-local org-done-keywords done-keywords)
14452 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14453 (org-fast-tag-insert "Current" current c-face "\n\n")
14454 (org-fast-tag-show-exit exit-after-next)
14455 (org-set-current-tags-overlay current ov-prefix)
14456 (setq tbl fulltable char ?a cnt 0)
14457 (while (setq e (pop tbl))
14458 (cond
14459 ((eq (car e) :startgroup)
14460 (push '() groups) (setq ingroup t)
14461 (unless (zerop cnt)
14462 (setq cnt 0)
14463 (insert "\n"))
14464 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14465 ((eq (car e) :endgroup)
14466 (setq ingroup nil cnt 0)
14467 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14468 ((eq (car e) :startgrouptag)
14469 (setq intaggroup t)
14470 (unless (zerop cnt)
14471 (setq cnt 0)
14472 (insert "\n"))
14473 (insert "[ "))
14474 ((eq (car e) :endgrouptag)
14475 (setq intaggroup nil cnt 0)
14476 (insert "]\n"))
14477 ((equal e '(:newline))
14478 (unless (zerop cnt)
14479 (setq cnt 0)
14480 (insert "\n")
14481 (setq e (car tbl))
14482 (while (equal (car tbl) '(:newline))
14483 (insert "\n")
14484 (setq tbl (cdr tbl)))))
14485 ((equal e '(:grouptags)) (insert " : "))
14487 (setq tg (copy-sequence (car e)) c2 nil)
14488 (if (cdr e)
14489 (setq c (cdr e))
14490 ;; automatically assign a character.
14491 (setq c1 (string-to-char
14492 (downcase (substring
14493 tg (if (= (string-to-char tg) ?@) 1 0)))))
14494 (if (or (rassoc c1 ntable) (rassoc c1 table))
14495 (while (or (rassoc char ntable) (rassoc char table))
14496 (setq char (1+ char)))
14497 (setq c2 c1))
14498 (setq c (or c2 char)))
14499 (when ingroup (push tg (car groups)))
14500 (setq tg (org-add-props tg nil 'face
14501 (cond
14502 ((not (assoc tg table))
14503 (org-get-todo-face tg))
14504 ((member tg current) c-face)
14505 ((member tg inherited) i-face))))
14506 (when (equal (caar tbl) :grouptags)
14507 (org-add-props tg nil 'face 'org-tag-group))
14508 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14509 (insert "[" c "] " tg (make-string
14510 (- fwidth 4 (length tg)) ?\ ))
14511 (push (cons tg c) ntable)
14512 (when (= (cl-incf cnt) ncol)
14513 (insert "\n")
14514 (when (or ingroup intaggroup) (insert " "))
14515 (setq cnt 0)))))
14516 (setq ntable (nreverse ntable))
14517 (insert "\n")
14518 (goto-char (point-min))
14519 (unless expert (org-fit-window-to-buffer))
14520 (setq rtn
14521 (catch 'exit
14522 (while t
14523 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14524 (if (not groups) "no " "")
14525 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14526 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14527 (setq org-last-tag-selection-key c)
14528 (cond
14529 ((= c ?\r) (throw 'exit t))
14530 ((= c ?!)
14531 (setq groups (not groups))
14532 (goto-char (point-min))
14533 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14534 ((= c ?\C-c)
14535 (if (not expert)
14536 (org-fast-tag-show-exit
14537 (setq exit-after-next (not exit-after-next)))
14538 (setq expert nil)
14539 (delete-other-windows)
14540 (set-window-buffer (split-window-vertically) " *Org tags*")
14541 (org-switch-to-buffer-other-window " *Org tags*")
14542 (org-fit-window-to-buffer)))
14543 ((or (= c ?\C-g)
14544 (and (= c ?q) (not (rassoc c ntable))))
14545 (delete-overlay org-tags-overlay)
14546 (setq quit-flag t))
14547 ((= c ?\ )
14548 (setq current nil)
14549 (when exit-after-next (setq exit-after-next 'now)))
14550 ((= c ?\t)
14551 (condition-case nil
14552 (setq tg (completing-read
14553 "Tag: "
14554 (or buffer-tags
14555 (with-current-buffer buf
14556 (setq buffer-tags
14557 (org-get-buffer-tags))))))
14558 (quit (setq tg "")))
14559 (when (string-match "\\S-" tg)
14560 (cl-pushnew (list tg) buffer-tags :test #'equal)
14561 (if (member tg current)
14562 (setq current (delete tg current))
14563 (push tg current)))
14564 (when exit-after-next (setq exit-after-next 'now)))
14565 ((setq e (rassoc c todo-table) tg (car e))
14566 (with-current-buffer buf
14567 (save-excursion (org-todo tg)))
14568 (when exit-after-next (setq exit-after-next 'now)))
14569 ((setq e (rassoc c ntable) tg (car e))
14570 (if (member tg current)
14571 (setq current (delete tg current))
14572 (cl-loop for g in groups do
14573 (when (member tg g)
14574 (dolist (x g) (setq current (delete x current)))))
14575 (push tg current))
14576 (when exit-after-next (setq exit-after-next 'now))))
14578 ;; Create a sorted list
14579 (setq current
14580 (sort current
14581 (lambda (a b)
14582 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14583 (when (eq exit-after-next 'now) (throw 'exit t))
14584 (goto-char (point-min))
14585 (beginning-of-line 2)
14586 (delete-region (point) (point-at-eol))
14587 (org-fast-tag-insert "Current" current c-face)
14588 (org-set-current-tags-overlay current ov-prefix)
14589 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
14590 (while (re-search-forward tag-re nil t)
14591 (let ((tag (match-string 1)))
14592 (add-text-properties
14593 (match-beginning 1) (match-end 1)
14594 (list 'face
14595 (cond
14596 ((member tag current) c-face)
14597 ((member tag inherited) i-face)
14598 (t (get-text-property (match-beginning 1) '
14599 face))))))))
14600 (goto-char (point-min)))))
14601 (delete-overlay org-tags-overlay)
14602 (if rtn
14603 (mapconcat 'identity current ":")
14604 nil))))
14606 (defun org-make-tag-string (tags)
14607 "Return string associated to TAGS.
14608 TAGS is a list of strings."
14609 (if (null tags) ""
14610 (format ":%s:" (mapconcat #'identity tags ":"))))
14612 (defun org--get-local-tags ()
14613 "Return list of tags for the current headline.
14614 Assume point is at the beginning of the headline."
14615 (and (looking-at org-tag-line-re)
14616 (split-string (match-string-no-properties 2) ":" t)))
14618 (defun org-get-tags (&optional pos local)
14619 "Get the list of tags specified in the current headline.
14621 When argument POS is non-nil, retrieve tags for headline at POS.
14623 Accoring to `org-use-tags-inheritance', tags may be inherited
14624 from parent headlines, and from the whole document, through
14625 `org-file-tags'. However, when optional argument LOCAL is
14626 non-nil, only return tags really specified in the considered
14627 headline.
14629 Inherited tags have the `inherited' text property."
14630 (if (and org-trust-scanner-tags
14631 (or (not pos) (eq pos (point)))
14632 (not local))
14633 org-scanner-tags
14634 (org-with-point-at (or pos (point))
14635 (unless (org-before-first-heading-p)
14636 (org-back-to-heading t)
14637 (let ((tags (org--get-local-tags)))
14638 (if (or local (not org-use-tag-inheritance)) tags
14639 (while (org-up-heading-safe)
14640 (setq tags (append (mapcar #'org-add-prop-inherited
14641 (org--get-local-tags))
14642 tags)))
14643 (org-remove-uninherited-tags
14644 (delete-dups (append org-file-tags tags)))))))))
14646 (defun org-get-buffer-tags ()
14647 "Get a table of all tags used in the buffer, for completion."
14648 (org-with-point-at 1
14649 (let (tags)
14650 (while (re-search-forward org-tag-line-re nil t)
14651 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
14652 tags)))
14653 (mapcar #'list (delete-dups (append org-file-tags tags))))))
14655 ;;;; The mapping API
14657 (defvar org-agenda-skip-comment-trees)
14658 (defvar org-agenda-skip-function)
14659 (defun org-map-entries (func &optional match scope &rest skip)
14660 "Call FUNC at each headline selected by MATCH in SCOPE.
14662 FUNC is a function or a lisp form. The function will be called without
14663 arguments, with the cursor positioned at the beginning of the headline.
14664 The return values of all calls to the function will be collected and
14665 returned as a list.
14667 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14668 does not need to preserve point. After evaluation, the cursor will be
14669 moved to the end of the line (presumably of the headline of the
14670 processed entry) and search continues from there. Under some
14671 circumstances, this may not produce the wanted results. For example,
14672 if you have removed (e.g. archived) the current (sub)tree it could
14673 mean that the next entry will be skipped entirely. In such cases, you
14674 can specify the position from where search should continue by making
14675 FUNC set the variable `org-map-continue-from' to the desired buffer
14676 position.
14678 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14679 Only headlines that are matched by this query will be considered during
14680 the iteration. When MATCH is nil or t, all headlines will be
14681 visited by the iteration.
14683 SCOPE determines the scope of this command. It can be any of:
14685 nil The current buffer, respecting the restriction if any
14686 tree The subtree started with the entry at point
14687 region The entries within the active region, if any
14688 region-start-level
14689 The entries within the active region, but only those at
14690 the same level than the first one.
14691 file The current buffer, without restriction
14692 file-with-archives
14693 The current buffer, and any archives associated with it
14694 agenda All agenda files
14695 agenda-with-archives
14696 All agenda files with any archive files associated with them
14697 \(file1 file2 ...)
14698 If this is a list, all files in the list will be scanned
14700 The remaining args are treated as settings for the skipping facilities of
14701 the scanner. The following items can be given here:
14703 archive skip trees with the archive tag
14704 comment skip trees with the COMMENT keyword
14705 function or Emacs Lisp form:
14706 will be used as value for `org-agenda-skip-function', so
14707 whenever the function returns a position, FUNC will not be
14708 called for that entry and search will continue from the
14709 position returned
14711 If your function needs to retrieve the tags including inherited tags
14712 at the *current* entry, you can use the value of the variable
14713 `org-scanner-tags' which will be much faster than getting the value
14714 with `org-get-tags'. If your function gets properties with
14715 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14716 to t around the call to `org-entry-properties' to get the same speedup.
14717 Note that if your function moves around to retrieve tags and properties at
14718 a *different* entry, you cannot use these techniques."
14719 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14720 (not (org-region-active-p)))
14721 (let* ((org-agenda-archives-mode nil) ; just to make sure
14722 (org-agenda-skip-archived-trees (memq 'archive skip))
14723 (org-agenda-skip-comment-trees (memq 'comment skip))
14724 (org-agenda-skip-function
14725 (car (org-delete-all '(comment archive) skip)))
14726 (org-tags-match-list-sublevels t)
14727 (start-level (eq scope 'region-start-level))
14728 matcher res
14729 org-todo-keywords-for-agenda
14730 org-done-keywords-for-agenda
14731 org-todo-keyword-alist-for-agenda
14732 org-tag-alist-for-agenda
14733 org--matcher-tags-todo-only)
14735 (cond
14736 ((eq match t) (setq matcher t))
14737 ((eq match nil) (setq matcher t))
14738 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14740 (save-excursion
14741 (save-restriction
14742 (cond ((eq scope 'tree)
14743 (org-back-to-heading t)
14744 (org-narrow-to-subtree)
14745 (setq scope nil))
14746 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14747 (org-region-active-p))
14748 ;; If needed, set start-level to a string like "2"
14749 (when start-level
14750 (save-excursion
14751 (goto-char (region-beginning))
14752 (unless (org-at-heading-p) (outline-next-heading))
14753 (setq start-level (org-current-level))))
14754 (narrow-to-region (region-beginning)
14755 (save-excursion
14756 (goto-char (region-end))
14757 (unless (and (bolp) (org-at-heading-p))
14758 (outline-next-heading))
14759 (point)))
14760 (setq scope nil)))
14762 (if (not scope)
14763 (progn
14764 (org-agenda-prepare-buffers
14765 (and buffer-file-name (list buffer-file-name)))
14766 (setq res
14767 (org-scan-tags
14768 func matcher org--matcher-tags-todo-only start-level)))
14769 ;; Get the right scope
14770 (cond
14771 ((and scope (listp scope) (symbolp (car scope)))
14772 (setq scope (eval scope)))
14773 ((eq scope 'agenda)
14774 (setq scope (org-agenda-files t)))
14775 ((eq scope 'agenda-with-archives)
14776 (setq scope (org-agenda-files t))
14777 (setq scope (org-add-archive-files scope)))
14778 ((eq scope 'file)
14779 (setq scope (and buffer-file-name (list buffer-file-name))))
14780 ((eq scope 'file-with-archives)
14781 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14782 (org-agenda-prepare-buffers scope)
14783 (dolist (file scope)
14784 (with-current-buffer (org-find-base-buffer-visiting file)
14785 (org-with-wide-buffer
14786 (goto-char (point-min))
14787 (setq res
14788 (append
14790 (org-scan-tags
14791 func matcher org--matcher-tags-todo-only)))))))))
14792 res)))
14794 ;;; Properties API
14796 (defconst org-special-properties
14797 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14798 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14799 "The special properties valid in Org mode.
14800 These are properties that are not defined in the property drawer,
14801 but in some other way.")
14803 (defconst org-default-properties
14804 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14805 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14806 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14807 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14808 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14809 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14810 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14811 "Some properties that are used by Org mode for various purposes.
14812 Being in this list makes sure that they are offered for completion.")
14814 (defun org--valid-property-p (property)
14815 "Non nil when string PROPERTY is a valid property name."
14816 (not
14817 (or (equal property "")
14818 (string-match-p "\\s-" property))))
14820 (defun org--update-property-plist (key val props)
14821 "Associate KEY to VAL in alist PROPS.
14822 Modifications are made by side-effect. Return new alist."
14823 (let* ((appending (string= (substring key -1) "+"))
14824 (key (if appending (substring key 0 -1) key))
14825 (old (assoc-string key props t)))
14826 (if (not old) (cons (cons key val) props)
14827 (setcdr old (if appending (concat (cdr old) " " val) val))
14828 props)))
14830 (defun org-get-property-block (&optional beg force)
14831 "Return the (beg . end) range of the body of the property drawer.
14832 BEG is the beginning of the current subtree, or of the part
14833 before the first headline. If it is not given, it will be found.
14834 If the drawer does not exist, create it if FORCE is non-nil, or
14835 return nil."
14836 (org-with-wide-buffer
14837 (when beg (goto-char beg))
14838 (unless (org-before-first-heading-p)
14839 (let ((beg (cond (beg)
14840 ((or (not (featurep 'org-inlinetask))
14841 (org-inlinetask-in-task-p))
14842 (org-back-to-heading t))
14843 (t (org-with-limited-levels (org-back-to-heading t))))))
14844 (forward-line)
14845 (when (looking-at-p org-planning-line-re) (forward-line))
14846 (cond ((looking-at org-property-drawer-re)
14847 (forward-line)
14848 (cons (point) (progn (goto-char (match-end 0))
14849 (line-beginning-position))))
14850 (force
14851 (goto-char beg)
14852 (org-insert-property-drawer)
14853 (let ((pos (save-excursion (search-forward ":END:")
14854 (line-beginning-position))))
14855 (cons pos pos))))))))
14857 (defun org-at-property-p ()
14858 "Non-nil when point is inside a property drawer.
14859 See `org-property-re' for match data, if applicable."
14860 (save-excursion
14861 (beginning-of-line)
14862 (and (looking-at org-property-re)
14863 (let ((property-drawer (save-match-data (org-get-property-block))))
14864 (and property-drawer
14865 (>= (point) (car property-drawer))
14866 (< (point) (cdr property-drawer)))))))
14868 (defun org-property-action ()
14869 "Do an action on properties."
14870 (interactive)
14871 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14872 (let ((c (read-char-exclusive)))
14873 (cl-case c
14874 (?s (call-interactively #'org-set-property))
14875 (?d (call-interactively #'org-delete-property))
14876 (?D (call-interactively #'org-delete-property-globally))
14877 (?c (call-interactively #'org-compute-property-at-point))
14878 (otherwise (user-error "No such property action %c" c)))))
14880 (defun org-inc-effort ()
14881 "Increment the value of the effort property in the current entry."
14882 (interactive)
14883 (org-set-effort t))
14885 (defvar org-clock-effort) ; Defined in org-clock.el.
14886 (defvar org-clock-current-task) ; Defined in org-clock.el.
14887 (defun org-set-effort (&optional increment value)
14888 "Set the effort property of the current entry.
14889 If INCREMENT is non-nil, set the property to the next allowed
14890 value. Otherwise, if optional argument VALUE is provided, use
14891 it. Eventually, prompt for the new value if none of the previous
14892 variables is set."
14893 (interactive "P")
14894 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14895 (current (org-entry-get nil org-effort-property))
14896 (value
14897 (cond
14898 (increment
14899 (unless allowed (user-error "Allowed effort values are not set"))
14900 (or (cl-caadr (member (list current) allowed))
14901 (user-error "Unknown value %S among allowed values" current)))
14902 (value
14903 (if (stringp value) value
14904 (error "Invalid effort value: %S" value)))
14906 (let ((must-match
14907 (and allowed
14908 (not (get-text-property 0 'org-unrestricted
14909 (caar allowed))))))
14910 (completing-read "Effort: " allowed nil must-match))))))
14911 (unless (equal current value)
14912 (org-entry-put nil org-effort-property value))
14913 (org-refresh-property '((effort . identity)
14914 (effort-minutes . org-duration-to-minutes))
14915 value)
14916 (when (equal (org-get-heading t t t t)
14917 (bound-and-true-p org-clock-current-task))
14918 (setq org-clock-effort (org-get-at-bol 'effort))
14919 (org-clock-update-mode-line))
14920 (message "%s is now %s" org-effort-property value)))
14922 (defun org-entry-properties (&optional pom which)
14923 "Get all properties of the current entry.
14925 When POM is a buffer position, get all properties from the entry
14926 there instead.
14928 This includes the TODO keyword, the tags, time strings for
14929 deadline, scheduled, and clocking, and any additional properties
14930 defined in the entry.
14932 If WHICH is nil or `all', get all properties. If WHICH is
14933 `special' or `standard', only get that subclass. If WHICH is
14934 a string, only get that property.
14936 Return value is an alist. Keys are properties, as upcased
14937 strings."
14938 (org-with-point-at pom
14939 (when (and (derived-mode-p 'org-mode)
14940 (ignore-errors (org-back-to-heading t)))
14941 (catch 'exit
14942 (let* ((beg (point))
14943 (specific (and (stringp which) (upcase which)))
14944 (which (cond ((not specific) which)
14945 ((member specific org-special-properties) 'special)
14946 (t 'standard)))
14947 props)
14948 ;; Get the special properties, like TODO and TAGS.
14949 (when (memq which '(nil all special))
14950 (when (or (not specific) (string= specific "CLOCKSUM"))
14951 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
14952 (when clocksum
14953 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
14954 props)))
14955 (when specific (throw 'exit props)))
14956 (when (or (not specific) (string= specific "CLOCKSUM_T"))
14957 (let ((clocksumt (get-text-property (point)
14958 :org-clock-minutes-today)))
14959 (when clocksumt
14960 (push (cons "CLOCKSUM_T"
14961 (org-duration-from-minutes clocksumt))
14962 props)))
14963 (when specific (throw 'exit props)))
14964 (when (or (not specific) (string= specific "ITEM"))
14965 (let ((case-fold-search nil))
14966 (when (looking-at org-complex-heading-regexp)
14967 (push (cons "ITEM"
14968 (let ((title (match-string-no-properties 4)))
14969 (if (org-string-nw-p title)
14970 (org-remove-tabs title)
14971 "")))
14972 props)))
14973 (when specific (throw 'exit props)))
14974 (when (or (not specific) (string= specific "TODO"))
14975 (let ((case-fold-search nil))
14976 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14977 (push (cons "TODO" (match-string-no-properties 2)) props)))
14978 (when specific (throw 'exit props)))
14979 (when (or (not specific) (string= specific "PRIORITY"))
14980 (push (cons "PRIORITY"
14981 (if (looking-at org-priority-regexp)
14982 (match-string-no-properties 2)
14983 (char-to-string org-default-priority)))
14984 props)
14985 (when specific (throw 'exit props)))
14986 (when (or (not specific) (string= specific "FILE"))
14987 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
14988 props)
14989 (when specific (throw 'exit props)))
14990 (when (or (not specific) (string= specific "TAGS"))
14991 (let ((tags (org-get-tags nil t)))
14992 (when tags
14993 (push (cons "TAGS" (org-make-tag-string tags))
14994 props)))
14995 (when specific (throw 'exit props)))
14996 (when (or (not specific) (string= specific "ALLTAGS"))
14997 (let ((tags (org-get-tags)))
14998 (when tags
14999 (push (cons "ALLTAGS" (org-make-tag-string tags))
15000 props)))
15001 (when specific (throw 'exit props)))
15002 (when (or (not specific) (string= specific "BLOCKED"))
15003 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15004 (when specific (throw 'exit props)))
15005 (when (or (not specific)
15006 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15007 (forward-line)
15008 (when (looking-at-p org-planning-line-re)
15009 (end-of-line)
15010 (let ((bol (line-beginning-position))
15011 ;; Backward compatibility: time keywords used to
15012 ;; be configurable (before 8.3). Make sure we
15013 ;; get the correct keyword.
15014 (key-assoc `(("CLOSED" . ,org-closed-string)
15015 ("DEADLINE" . ,org-deadline-string)
15016 ("SCHEDULED" . ,org-scheduled-string))))
15017 (dolist (pair (if specific (list (assoc specific key-assoc))
15018 key-assoc))
15019 (save-excursion
15020 (when (search-backward (cdr pair) bol t)
15021 (goto-char (match-end 0))
15022 (skip-chars-forward " \t")
15023 (and (looking-at org-ts-regexp-both)
15024 (push (cons (car pair)
15025 (match-string-no-properties 0))
15026 props)))))))
15027 (when specific (throw 'exit props)))
15028 (when (or (not specific)
15029 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15030 (let ((find-ts
15031 (lambda (end ts)
15032 ;; Fix next time-stamp before END. TS is the
15033 ;; list of time-stamps found so far.
15034 (let ((ts ts)
15035 (regexp (cond
15036 ((string= specific "TIMESTAMP")
15037 org-ts-regexp)
15038 ((string= specific "TIMESTAMP_IA")
15039 org-ts-regexp-inactive)
15040 ((assoc "TIMESTAMP_IA" ts)
15041 org-ts-regexp)
15042 ((assoc "TIMESTAMP" ts)
15043 org-ts-regexp-inactive)
15044 (t org-ts-regexp-both))))
15045 (catch 'next
15046 (while (re-search-forward regexp end t)
15047 (backward-char)
15048 (let ((object (org-element-context)))
15049 ;; Accept to match timestamps in node
15050 ;; properties, too.
15051 (when (memq (org-element-type object)
15052 '(node-property timestamp))
15053 (let ((type
15054 (org-element-property :type object)))
15055 (cond
15056 ((and (memq type '(active active-range))
15057 (not (equal specific "TIMESTAMP_IA")))
15058 (unless (assoc "TIMESTAMP" ts)
15059 (push (cons "TIMESTAMP"
15060 (org-element-property
15061 :raw-value object))
15063 (when specific (throw 'exit ts))))
15064 ((and (memq type '(inactive inactive-range))
15065 (not (string= specific "TIMESTAMP")))
15066 (unless (assoc "TIMESTAMP_IA" ts)
15067 (push (cons "TIMESTAMP_IA"
15068 (org-element-property
15069 :raw-value object))
15071 (when specific (throw 'exit ts))))))
15072 ;; Both timestamp types are found,
15073 ;; move to next part.
15074 (when (= (length ts) 2) (throw 'next ts)))))
15075 ts)))))
15076 (goto-char beg)
15077 ;; First look for timestamps within headline.
15078 (let ((ts (funcall find-ts (line-end-position) nil)))
15079 (if (= (length ts) 2) (setq props (nconc ts props))
15080 ;; Then find timestamps in the section, skipping
15081 ;; planning line.
15082 (let ((end (save-excursion (outline-next-heading))))
15083 (forward-line)
15084 (when (looking-at-p org-planning-line-re) (forward-line))
15085 (setq props (nconc (funcall find-ts end ts) props))))))))
15086 ;; Get the standard properties, like :PROP:.
15087 (when (memq which '(nil all standard))
15088 ;; If we are looking after a specific property, delegate
15089 ;; to `org-entry-get', which is faster. However, make an
15090 ;; exception for "CATEGORY", since it can be also set
15091 ;; through keywords (i.e. #+CATEGORY).
15092 (if (and specific (not (equal specific "CATEGORY")))
15093 (let ((value (org-entry-get beg specific nil t)))
15094 (throw 'exit (and value (list (cons specific value)))))
15095 (let ((range (org-get-property-block beg)))
15096 (when range
15097 (let ((end (cdr range)) seen-base)
15098 (goto-char (car range))
15099 ;; Unlike to `org--update-property-plist', we
15100 ;; handle the case where base values is found
15101 ;; after its extension. We also forbid standard
15102 ;; properties to be named as special properties.
15103 (while (re-search-forward org-property-re end t)
15104 (let* ((key (upcase (match-string-no-properties 2)))
15105 (extendp (string-match-p "\\+\\'" key))
15106 (key-base (if extendp (substring key 0 -1) key))
15107 (value (match-string-no-properties 3)))
15108 (cond
15109 ((member-ignore-case key-base org-special-properties))
15110 (extendp
15111 (setq props
15112 (org--update-property-plist key value props)))
15113 ((member key seen-base))
15114 (t (push key seen-base)
15115 (let ((p (assoc-string key props t)))
15116 (if p (setcdr p (concat value " " (cdr p)))
15117 (push (cons key value) props))))))))))))
15118 (unless (assoc "CATEGORY" props)
15119 (push (cons "CATEGORY" (org-get-category beg)) props)
15120 (when (string= specific "CATEGORY") (throw 'exit props)))
15121 ;; Return value.
15122 props)))))
15124 (defun org--property-local-values (property literal-nil)
15125 "Return value for PROPERTY in current entry.
15126 Value is a list whose car is the base value for PROPERTY and cdr
15127 a list of accumulated values. Return nil if neither is found in
15128 the entry. Also return nil when PROPERTY is set to \"nil\",
15129 unless LITERAL-NIL is non-nil."
15130 (let ((range (org-get-property-block)))
15131 (when range
15132 (goto-char (car range))
15133 (let* ((case-fold-search t)
15134 (end (cdr range))
15135 (value
15136 ;; Base value.
15137 (save-excursion
15138 (let ((v (and (re-search-forward
15139 (org-re-property property nil t) end t)
15140 (match-string-no-properties 3))))
15141 (list (if literal-nil v (org-not-nil v)))))))
15142 ;; Find additional values.
15143 (let* ((property+ (org-re-property (concat property "+") nil t)))
15144 (while (re-search-forward property+ end t)
15145 (push (match-string-no-properties 3) value)))
15146 ;; Return final values.
15147 (and (not (equal value '(nil))) (nreverse value))))))
15149 (defun org--property-global-value (property literal-nil)
15150 "Return value for PROPERTY in current buffer.
15151 Return value is a string. Return nil if property is not set
15152 globally. Also return nil when PROPERTY is set to \"nil\",
15153 unless LITERAL-NIL is non-nil."
15154 (let ((global
15155 (cdr (or (assoc-string property org-file-properties t)
15156 (assoc-string property org-global-properties t)
15157 (assoc-string property org-global-properties-fixed t)))))
15158 (if literal-nil global (org-not-nil global))))
15160 (defun org-entry-get (pom property &optional inherit literal-nil)
15161 "Get value of PROPERTY for entry or content at point-or-marker POM.
15163 If INHERIT is non-nil and the entry does not have the property,
15164 then also check higher levels of the hierarchy. If INHERIT is
15165 the symbol `selective', use inheritance only if the setting in
15166 `org-use-property-inheritance' selects PROPERTY for inheritance.
15168 If the property is present but empty, the return value is the
15169 empty string. If the property is not present at all, nil is
15170 returned. In any other case, return the value as a string.
15171 Search is case-insensitive.
15173 If LITERAL-NIL is set, return the string value \"nil\" as
15174 a string, do not interpret it as the list atom nil. This is used
15175 for inheritance when a \"nil\" value can supersede a non-nil
15176 value higher up the hierarchy."
15177 (org-with-point-at pom
15178 (cond
15179 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15180 ;; We need a special property. Use `org-entry-properties' to
15181 ;; retrieve it, but specify the wanted property.
15182 (cdr (assoc-string property (org-entry-properties nil property))))
15183 ((and inherit
15184 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15185 (org-entry-get-with-inheritance property literal-nil))
15187 (let* ((local (org--property-local-values property literal-nil))
15188 (value (and local (mapconcat #'identity (delq nil local) " "))))
15189 (if literal-nil value (org-not-nil value)))))))
15191 (defun org-property-or-variable-value (var &optional inherit)
15192 "Check if there is a property fixing the value of VAR.
15193 If yes, return this value. If not, return the current value of the variable."
15194 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15195 (if (and prop (stringp prop) (string-match "\\S-" prop))
15196 (read prop)
15197 (symbol-value var))))
15199 (defun org-entry-delete (pom property)
15200 "Delete PROPERTY from entry at point-or-marker POM.
15201 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15202 non-nil when a property was removed."
15203 (org-with-point-at pom
15204 (pcase (org-get-property-block)
15205 (`(,begin . ,origin)
15206 (let* ((end (copy-marker origin))
15207 (re (org-re-property
15208 (concat (regexp-quote property) "\\+?") t t)))
15209 (goto-char begin)
15210 (while (re-search-forward re end t)
15211 (delete-region (match-beginning 0) (line-beginning-position 2)))
15212 ;; If drawer is empty, remove it altogether.
15213 (when (= begin end)
15214 (delete-region (line-beginning-position 0)
15215 (line-beginning-position 2)))
15216 ;; Return non-nil if some property was removed.
15217 (prog1 (/= end origin) (set-marker end nil))))
15218 (_ nil))))
15220 ;; Multi-values properties are properties that contain multiple values
15221 ;; These values are assumed to be single words, separated by whitespace.
15222 (defun org-entry-add-to-multivalued-property (pom property value)
15223 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15224 (let* ((old (org-entry-get pom property))
15225 (values (and old (split-string old))))
15226 (setq value (org-entry-protect-space value))
15227 (unless (member value values)
15228 (setq values (append values (list value)))
15229 (org-entry-put pom property (mapconcat #'identity values " ")))))
15231 (defun org-entry-remove-from-multivalued-property (pom property value)
15232 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15233 (let* ((old (org-entry-get pom property))
15234 (values (and old (split-string old))))
15235 (setq value (org-entry-protect-space value))
15236 (when (member value values)
15237 (setq values (delete value values))
15238 (org-entry-put pom property (mapconcat #'identity values " ")))))
15240 (defun org-entry-member-in-multivalued-property (pom property value)
15241 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15242 (let* ((old (org-entry-get pom property))
15243 (values (and old (split-string old))))
15244 (setq value (org-entry-protect-space value))
15245 (member value values)))
15247 (defun org-entry-get-multivalued-property (pom property)
15248 "Return a list of values in a multivalued property."
15249 (let* ((value (org-entry-get pom property))
15250 (values (and value (split-string value))))
15251 (mapcar #'org-entry-restore-space values)))
15253 (defun org-entry-put-multivalued-property (pom property &rest values)
15254 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15255 VALUES should be a list of strings. Spaces will be protected."
15256 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15257 (let* ((value (org-entry-get pom property))
15258 (values (and value (split-string value))))
15259 (mapcar #'org-entry-restore-space values)))
15261 (defun org-entry-protect-space (s)
15262 "Protect spaces and newline in string S."
15263 (while (string-match " " s)
15264 (setq s (replace-match "%20" t t s)))
15265 (while (string-match "\n" s)
15266 (setq s (replace-match "%0A" t t s)))
15269 (defun org-entry-restore-space (s)
15270 "Restore spaces and newline in string S."
15271 (while (string-match "%20" s)
15272 (setq s (replace-match " " t t s)))
15273 (while (string-match "%0A" s)
15274 (setq s (replace-match "\n" t t s)))
15277 (defvar org-entry-property-inherited-from (make-marker)
15278 "Marker pointing to the entry from where a property was inherited.
15279 Each call to `org-entry-get-with-inheritance' will set this marker to the
15280 location of the entry where the inheritance search matched. If there was
15281 no match, the marker will point nowhere.
15282 Note that also `org-entry-get' calls this function, if the INHERIT flag
15283 is set.")
15285 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15286 "Get PROPERTY of entry or content at point, search higher levels if needed.
15287 The search will stop at the first ancestor which has the property defined.
15288 If the value found is \"nil\", return nil to show that the property
15289 should be considered as undefined (this is the meaning of nil here).
15290 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15291 (move-marker org-entry-property-inherited-from nil)
15292 (org-with-wide-buffer
15293 (let (value)
15294 (catch 'exit
15295 (while t
15296 (let ((v (org--property-local-values property literal-nil)))
15297 (when v
15298 (setq value
15299 (concat (mapconcat #'identity (delq nil v) " ")
15300 (and value " ")
15301 value)))
15302 (cond
15303 ((car v)
15304 (org-back-to-heading t)
15305 (move-marker org-entry-property-inherited-from (point))
15306 (throw 'exit nil))
15307 ((org-up-heading-safe))
15309 (let ((global (org--property-global-value property literal-nil)))
15310 (cond ((not global))
15311 (value (setq value (concat global " " value)))
15312 (t (setq value global))))
15313 (throw 'exit nil))))))
15314 (if literal-nil value (org-not-nil value)))))
15316 (defvar org-property-changed-functions nil
15317 "Hook called when the value of a property has changed.
15318 Each hook function should accept two arguments, the name of the property
15319 and the new value.")
15321 (defun org-entry-put (pom property value)
15322 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15324 If the value is nil, it is converted to the empty string. If it
15325 is not a string, an error is raised. Also raise an error on
15326 invalid property names.
15328 PROPERTY can be any regular property (see
15329 `org-special-properties'). It can also be \"TODO\",
15330 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15332 For the last two properties, VALUE may have any of the special
15333 values \"earlier\" and \"later\". The function then increases or
15334 decreases scheduled or deadline date by one day."
15335 (cond ((null value) (setq value ""))
15336 ((not (stringp value)) (error "Properties values should be strings"))
15337 ((not (org--valid-property-p property))
15338 (user-error "Invalid property name: \"%s\"" property)))
15339 (org-with-point-at pom
15340 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15341 (org-back-to-heading t)
15342 (org-with-limited-levels (org-back-to-heading t)))
15343 (let ((beg (point)))
15344 (cond
15345 ((equal property "TODO")
15346 (cond ((not (org-string-nw-p value)) (setq value 'none))
15347 ((not (member value org-todo-keywords-1))
15348 (user-error "\"%s\" is not a valid TODO state" value)))
15349 (org-todo value)
15350 (org-align-tags))
15351 ((equal property "PRIORITY")
15352 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15353 (org-align-tags))
15354 ((equal property "SCHEDULED")
15355 (forward-line)
15356 (if (and (looking-at-p org-planning-line-re)
15357 (re-search-forward
15358 org-scheduled-time-regexp (line-end-position) t))
15359 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15360 ((string= value "later") (org-timestamp-change 1 'day))
15361 ((string= value "") (org-schedule '(4)))
15362 (t (org-schedule nil value)))
15363 (if (member value '("earlier" "later" ""))
15364 (call-interactively #'org-schedule)
15365 (org-schedule nil value))))
15366 ((equal property "DEADLINE")
15367 (forward-line)
15368 (if (and (looking-at-p org-planning-line-re)
15369 (re-search-forward
15370 org-deadline-time-regexp (line-end-position) t))
15371 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15372 ((string= value "later") (org-timestamp-change 1 'day))
15373 ((string= value "") (org-deadline '(4)))
15374 (t (org-deadline nil value)))
15375 (if (member value '("earlier" "later" ""))
15376 (call-interactively #'org-deadline)
15377 (org-deadline nil value))))
15378 ((member property org-special-properties)
15379 (error "The %s property cannot be set with `org-entry-put'" property))
15381 (let* ((range (org-get-property-block beg 'force))
15382 (end (cdr range))
15383 (case-fold-search t))
15384 (goto-char (car range))
15385 (if (re-search-forward (org-re-property property nil t) end t)
15386 (progn (delete-region (match-beginning 0) (match-end 0))
15387 (goto-char (match-beginning 0)))
15388 (goto-char end)
15389 (insert "\n")
15390 (backward-char))
15391 (insert ":" property ":")
15392 (when value (insert " " value))
15393 (org-indent-line)))))
15394 (run-hook-with-args 'org-property-changed-functions property value)))
15396 (defun org-buffer-property-keys (&optional specials defaults columns)
15397 "Get all property keys in the current buffer.
15399 When SPECIALS is non-nil, also list the special properties that
15400 reflect things like tags and TODO state.
15402 When DEFAULTS is non-nil, also include properties that has
15403 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15404 DESCRIPTION, LOCATION, and LOGGING and others.
15406 When COLUMNS in non-nil, also include property names given in
15407 COLUMN formats in the current buffer."
15408 (let ((case-fold-search t)
15409 (props (append
15410 (and specials org-special-properties)
15411 (and defaults (cons org-effort-property org-default-properties))
15412 nil)))
15413 (org-with-wide-buffer
15414 (goto-char (point-min))
15415 (while (re-search-forward org-property-start-re nil t)
15416 (catch :skip
15417 (let ((range (org-get-property-block)))
15418 (unless range (throw :skip nil))
15419 (goto-char (car range))
15420 (let ((begin (car range))
15421 (end (cdr range)))
15422 ;; Make sure that found property block is not located
15423 ;; before current point, as it would generate an infloop.
15424 ;; It can happen, for example, in the following
15425 ;; situation:
15427 ;; * Headline
15428 ;; :PROPERTIES:
15429 ;; ...
15430 ;; :END:
15431 ;; *************** Inlinetask
15432 ;; #+BEGIN_EXAMPLE
15433 ;; :PROPERTIES:
15434 ;; #+END_EXAMPLE
15436 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15437 (while (< (point) end)
15438 (let ((p (progn (looking-at org-property-re)
15439 (match-string-no-properties 2))))
15440 ;; Only add true property name, not extension symbol.
15441 (push (if (not (string-match-p "\\+\\'" p)) p
15442 (substring p 0 -1))
15443 props))
15444 (forward-line))))
15445 (outline-next-heading)))
15446 (when columns
15447 (goto-char (point-min))
15448 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15449 (let ((element (org-element-at-point)))
15450 (when (memq (org-element-type element) '(keyword node-property))
15451 (let ((value (org-element-property :value element))
15452 (start 0))
15453 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15454 \\(?:{[^}]+}\\)?"
15455 value start)
15456 (setq start (match-end 0))
15457 (let ((p (match-string-no-properties 1 value)))
15458 (unless (member-ignore-case p org-special-properties)
15459 (push p props))))))))))
15460 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15462 (defun org-property-values (key)
15463 "List all non-nil values of property KEY in current buffer."
15464 (org-with-wide-buffer
15465 (goto-char (point-min))
15466 (let ((case-fold-search t)
15467 (re (org-re-property key))
15468 values)
15469 (while (re-search-forward re nil t)
15470 (push (org-entry-get (point) key) values))
15471 (delete-dups values))))
15473 (defun org-insert-property-drawer ()
15474 "Insert a property drawer into the current entry."
15475 (org-with-wide-buffer
15476 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15477 (org-back-to-heading t)
15478 (org-with-limited-levels (org-back-to-heading t)))
15479 (forward-line)
15480 (when (looking-at-p org-planning-line-re) (forward-line))
15481 (unless (looking-at-p org-property-drawer-re)
15482 ;; Make sure we start editing a line from current entry, not from
15483 ;; next one. It prevents extending text properties or overlays
15484 ;; belonging to the latter.
15485 (when (bolp) (backward-char))
15486 (let ((begin (1+ (point)))
15487 (inhibit-read-only t))
15488 (insert "\n:PROPERTIES:\n:END:")
15489 (when (eobp) (insert "\n"))
15490 (org-indent-region begin (point))))))
15492 (defun org-insert-drawer (&optional arg drawer)
15493 "Insert a drawer at point.
15495 When optional argument ARG is non-nil, insert a property drawer.
15497 Optional argument DRAWER, when non-nil, is a string representing
15498 drawer's name. Otherwise, the user is prompted for a name.
15500 If a region is active, insert the drawer around that region
15501 instead.
15503 Point is left between drawer's boundaries."
15504 (interactive "P")
15505 (let* ((drawer (if arg "PROPERTIES"
15506 (or drawer (read-from-minibuffer "Drawer: ")))))
15507 (cond
15508 ;; With C-u, fall back on `org-insert-property-drawer'
15509 (arg (org-insert-property-drawer))
15510 ;; Check validity of suggested drawer's name.
15511 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15512 (user-error "Invalid drawer name"))
15513 ;; With an active region, insert a drawer at point.
15514 ((not (org-region-active-p))
15515 (progn
15516 (unless (bolp) (insert "\n"))
15517 (insert (format ":%s:\n\n:END:\n" drawer))
15518 (forward-line -2)))
15519 ;; Otherwise, insert the drawer at point
15521 (let ((rbeg (region-beginning))
15522 (rend (copy-marker (region-end))))
15523 (unwind-protect
15524 (progn
15525 (goto-char rbeg)
15526 (beginning-of-line)
15527 (when (save-excursion
15528 (re-search-forward org-outline-regexp-bol rend t))
15529 (user-error "Drawers cannot contain headlines"))
15530 ;; Position point at the beginning of the first
15531 ;; non-blank line in region. Insert drawer's opening
15532 ;; there, then indent it.
15533 (org-skip-whitespace)
15534 (beginning-of-line)
15535 (insert ":" drawer ":\n")
15536 (forward-line -1)
15537 (indent-for-tab-command)
15538 ;; Move point to the beginning of the first blank line
15539 ;; after the last non-blank line in region. Insert
15540 ;; drawer's closing, then indent it.
15541 (goto-char rend)
15542 (skip-chars-backward " \r\t\n")
15543 (insert "\n:END:")
15544 (deactivate-mark t)
15545 (indent-for-tab-command)
15546 (unless (eolp) (insert "\n")))
15547 ;; Clear marker, whatever the outcome of insertion is.
15548 (set-marker rend nil)))))))
15550 (defvar org-property-set-functions-alist nil
15551 "Property set function alist.
15552 Each entry should have the following format:
15554 (PROPERTY . READ-FUNCTION)
15556 The read function will be called with the same argument as
15557 `org-completing-read'.")
15559 (defun org-set-property-function (property)
15560 "Get the function that should be used to set PROPERTY.
15561 This is computed according to `org-property-set-functions-alist'."
15562 (or (cdr (assoc property org-property-set-functions-alist))
15563 'org-completing-read))
15565 (defun org-read-property-value (property)
15566 "Read PROPERTY value from user."
15567 (let* ((completion-ignore-case t)
15568 (allowed (org-property-get-allowed-values nil property 'table))
15569 (cur (org-entry-get nil property))
15570 (prompt (concat property " value"
15571 (if (and cur (string-match "\\S-" cur))
15572 (concat " [" cur "]") "") ": "))
15573 (set-function (org-set-property-function property))
15574 (val (if allowed
15575 (funcall set-function prompt allowed nil
15576 (not (get-text-property 0 'org-unrestricted
15577 (caar allowed))))
15578 (funcall set-function prompt
15579 (mapcar 'list (org-property-values property))
15580 nil nil "" nil cur))))
15581 (org-trim val)))
15583 (defvar org-last-set-property nil)
15584 (defvar org-last-set-property-value nil)
15585 (defun org-read-property-name ()
15586 "Read a property name."
15587 (let ((completion-ignore-case t)
15588 (default-prop (or (and (org-at-property-p)
15589 (match-string-no-properties 2))
15590 org-last-set-property)))
15591 (org-completing-read
15592 (concat "Property"
15593 (if default-prop (concat " [" default-prop "]") "")
15594 ": ")
15595 (mapcar #'list (org-buffer-property-keys nil t t))
15596 nil nil nil nil default-prop)))
15598 (defun org-set-property-and-value (use-last)
15599 "Allow to set [PROPERTY]: [value] direction from prompt.
15600 When use-default, don't even ask, just use the last
15601 \"[PROPERTY]: [value]\" string from the history."
15602 (interactive "P")
15603 (let* ((completion-ignore-case t)
15604 (pv (or (and use-last org-last-set-property-value)
15605 (org-completing-read
15606 "Enter a \"[Property]: [value]\" pair: "
15607 nil nil nil nil nil
15608 org-last-set-property-value)))
15609 prop val)
15610 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15611 (setq prop (match-string 1 pv)
15612 val (match-string 2 pv))
15613 (org-set-property prop val))))
15615 (defun org-set-property (property value)
15616 "In the current entry, set PROPERTY to VALUE.
15618 When called interactively, this will prompt for a property name, offering
15619 completion on existing and default properties. And then it will prompt
15620 for a value, offering completion either on allowed values (via an inherited
15621 xxx_ALL property) or on existing values in other instances of this property
15622 in the current file.
15624 Throw an error when trying to set a property with an invalid name."
15625 (interactive (list nil nil))
15626 (let ((property (or property (org-read-property-name))))
15627 ;; `org-entry-put' also makes the following check, but this one
15628 ;; avoids polluting `org-last-set-property' and
15629 ;; `org-last-set-property-value' needlessly.
15630 (unless (org--valid-property-p property)
15631 (user-error "Invalid property name: \"%s\"" property))
15632 (let ((value (or value (org-read-property-value property)))
15633 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15634 (setq org-last-set-property property)
15635 (setq org-last-set-property-value (concat property ": " value))
15636 ;; Possibly postprocess the inserted value:
15637 (when fn (setq value (funcall fn value)))
15638 (unless (equal (org-entry-get nil property) value)
15639 (org-entry-put nil property value)))))
15641 (defun org-find-property (property &optional value)
15642 "Find first entry in buffer that sets PROPERTY.
15644 When optional argument VALUE is non-nil, only consider an entry
15645 if it contains PROPERTY set to this value. If PROPERTY should be
15646 explicitly set to nil, use string \"nil\" for VALUE.
15648 Return position where the entry begins, or nil if there is no
15649 such entry. If narrowing is in effect, only search the visible
15650 part of the buffer."
15651 (save-excursion
15652 (goto-char (point-min))
15653 (let ((case-fold-search t)
15654 (re (org-re-property property nil (not value) value)))
15655 (catch 'exit
15656 (while (re-search-forward re nil t)
15657 (when (if value (org-at-property-p)
15658 (org-entry-get (point) property nil t))
15659 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15661 (defun org-delete-property (property)
15662 "In the current entry, delete PROPERTY."
15663 (interactive
15664 (let* ((completion-ignore-case t)
15665 (cat (org-entry-get (point) "CATEGORY"))
15666 (props0 (org-entry-properties nil 'standard))
15667 (props (if cat props0
15668 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15669 (prop (if (< 1 (length props))
15670 (completing-read "Property: " props nil t)
15671 (caar props))))
15672 (list prop)))
15673 (if (not property)
15674 (message "No property to delete in this entry")
15675 (org-entry-delete nil property)
15676 (message "Property \"%s\" deleted" property)))
15678 (defun org-delete-property-globally (property)
15679 "Remove PROPERTY globally, from all entries.
15680 This function ignores narrowing, if any."
15681 (interactive
15682 (let* ((completion-ignore-case t)
15683 (prop (completing-read
15684 "Globally remove property: "
15685 (mapcar #'list (org-buffer-property-keys)))))
15686 (list prop)))
15687 (org-with-wide-buffer
15688 (goto-char (point-min))
15689 (let ((count 0)
15690 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15691 (while (re-search-forward re nil t)
15692 (when (org-entry-delete (point) property) (cl-incf count)))
15693 (message "Property \"%s\" removed from %d entries" property count))))
15695 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15697 (defun org-compute-property-at-point ()
15698 "Compute the property at point.
15699 This looks for an enclosing column format, extracts the operator and
15700 then applies it to the property in the column format's scope."
15701 (interactive)
15702 (unless (org-at-property-p)
15703 (user-error "Not at a property"))
15704 (let ((prop (match-string-no-properties 2)))
15705 (org-columns-get-format-and-top-level)
15706 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15707 (user-error "No operator defined for property %s" prop))
15708 (org-columns-compute prop)))
15710 (defvar org-property-allowed-value-functions nil
15711 "Hook for functions supplying allowed values for a specific property.
15712 The functions must take a single argument, the name of the property, and
15713 return a flat list of allowed values. If \":ETC\" is one of
15714 the values, this means that these values are intended as defaults for
15715 completion, but that other values should be allowed too.
15716 The functions must return nil if they are not responsible for this
15717 property.")
15719 (defun org-property-get-allowed-values (pom property &optional table)
15720 "Get allowed values for the property PROPERTY.
15721 When TABLE is non-nil, return an alist that can directly be used for
15722 completion."
15723 (let (vals)
15724 (cond
15725 ((equal property "TODO")
15726 (setq vals (org-with-point-at pom
15727 (append org-todo-keywords-1 '("")))))
15728 ((equal property "PRIORITY")
15729 (let ((n org-lowest-priority))
15730 (while (>= n org-highest-priority)
15731 (push (char-to-string n) vals)
15732 (setq n (1- n)))))
15733 ((equal property "CATEGORY"))
15734 ((member property org-special-properties))
15735 ((setq vals (run-hook-with-args-until-success
15736 'org-property-allowed-value-functions property)))
15738 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15739 (when (and vals (string-match "\\S-" vals))
15740 (setq vals (car (read-from-string (concat "(" vals ")"))))
15741 (setq vals (mapcar (lambda (x)
15742 (cond ((stringp x) x)
15743 ((numberp x) (number-to-string x))
15744 ((symbolp x) (symbol-name x))
15745 (t "???")))
15746 vals)))))
15747 (when (member ":ETC" vals)
15748 (setq vals (remove ":ETC" vals))
15749 (org-add-props (car vals) '(org-unrestricted t)))
15750 (if table (mapcar 'list vals) vals)))
15752 (defun org-property-previous-allowed-value (&optional _previous)
15753 "Switch to the next allowed value for this property."
15754 (interactive)
15755 (org-property-next-allowed-value t))
15757 (defun org-property-next-allowed-value (&optional previous)
15758 "Switch to the next allowed value for this property."
15759 (interactive)
15760 (unless (org-at-property-p)
15761 (user-error "Not at a property"))
15762 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15763 (key (match-string 2))
15764 (value (match-string 3))
15765 (allowed (or (org-property-get-allowed-values (point) key)
15766 (and (member value '("[ ]" "[-]" "[X]"))
15767 '("[ ]" "[X]"))))
15768 (heading (save-match-data (nth 4 (org-heading-components))))
15769 nval)
15770 (unless allowed
15771 (user-error "Allowed values for this property have not been defined"))
15772 (when previous (setq allowed (reverse allowed)))
15773 (when (member value allowed)
15774 (setq nval (car (cdr (member value allowed)))))
15775 (setq nval (or nval (car allowed)))
15776 (when (equal nval value)
15777 (user-error "Only one allowed value for this property"))
15778 (org-at-property-p)
15779 (replace-match (concat " :" key ": " nval) t t)
15780 (org-indent-line)
15781 (beginning-of-line 1)
15782 (skip-chars-forward " \t")
15783 (when (equal prop org-effort-property)
15784 (org-refresh-property
15785 '((effort . identity)
15786 (effort-minutes . org-duration-to-minutes))
15787 nval)
15788 (when (string= org-clock-current-task heading)
15789 (setq org-clock-effort nval)
15790 (org-clock-update-mode-line)))
15791 (run-hook-with-args 'org-property-changed-functions key nval)))
15793 (defun org-find-olp (path &optional this-buffer)
15794 "Return a marker pointing to the entry at outline path OLP.
15795 If anything goes wrong, throw an error.
15796 You can wrap this call to catch the error like this:
15798 (condition-case msg
15799 (org-mobile-locate-entry (match-string 4))
15800 (error (nth 1 msg)))
15802 The return value will then be either a string with the error message,
15803 or a marker if everything is OK.
15805 If THIS-BUFFER is set, the outline path does not contain a file,
15806 only headings."
15807 (let* ((file (if this-buffer buffer-file-name (pop path)))
15808 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15809 (level 1)
15810 (lmin 1)
15811 (lmax 1)
15812 end found flevel)
15813 (unless buffer (error "File not found :%s" file))
15814 (with-current-buffer buffer
15815 (unless (derived-mode-p 'org-mode)
15816 (error "Buffer %s needs to be in Org mode" buffer))
15817 (org-with-wide-buffer
15818 (goto-char (point-min))
15819 (dolist (heading path)
15820 (let ((re (format org-complex-heading-regexp-format
15821 (regexp-quote heading)))
15822 (cnt 0))
15823 (while (re-search-forward re end t)
15824 (setq level (- (match-end 1) (match-beginning 1)))
15825 (when (and (>= level lmin) (<= level lmax))
15826 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15827 (when (= cnt 0)
15828 (error "Heading not found on level %d: %s" lmax heading))
15829 (when (> cnt 1)
15830 (error "Heading not unique on level %d: %s" lmax heading))
15831 (goto-char found)
15832 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15833 (setq end (save-excursion (org-end-of-subtree t t)))))
15834 (when (org-at-heading-p)
15835 (point-marker))))))
15837 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15838 "Find node HEADING in BUFFER.
15839 Return a marker to the heading if it was found, or nil if not.
15840 If POS-ONLY is set, return just the position instead of a marker.
15842 The heading text must match exact, but it may have a TODO keyword,
15843 a priority cookie and tags in the standard locations."
15844 (with-current-buffer (or buffer (current-buffer))
15845 (org-with-wide-buffer
15846 (goto-char (point-min))
15847 (let (case-fold-search)
15848 (when (re-search-forward
15849 (format org-complex-heading-regexp-format
15850 (regexp-quote heading)) nil t)
15851 (if pos-only
15852 (match-beginning 0)
15853 (move-marker (make-marker) (match-beginning 0))))))))
15855 (defun org-find-exact-heading-in-directory (heading &optional dir)
15856 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15857 When the target headline is found, return a marker to this location."
15858 (let ((files (directory-files (or dir default-directory)
15859 t "\\`[^.#].*\\.org\\'"))
15860 visiting m buffer)
15861 (catch 'found
15862 (dolist (file files)
15863 (message "trying %s" file)
15864 (setq visiting (org-find-base-buffer-visiting file))
15865 (setq buffer (or visiting (find-file-noselect file)))
15866 (setq m (org-find-exact-headline-in-buffer
15867 heading buffer))
15868 (when (and (not m) (not visiting)) (kill-buffer buffer))
15869 (and m (throw 'found m))))))
15871 (defun org-find-entry-with-id (ident)
15872 "Locate the entry that contains the ID property with exact value IDENT.
15873 IDENT can be a string, a symbol or a number, this function will search for
15874 the string representation of it.
15875 Return the position where this entry starts, or nil if there is no such entry."
15876 (interactive "sID: ")
15877 (let ((id (cond
15878 ((stringp ident) ident)
15879 ((symbolp ident) (symbol-name ident))
15880 ((numberp ident) (number-to-string ident))
15881 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15882 (org-with-wide-buffer (org-find-property "ID" id))))
15884 ;;;; Timestamps
15886 (defvar org-last-changed-timestamp nil)
15887 (defvar org-last-inserted-timestamp nil
15888 "The last time stamp inserted with `org-insert-time-stamp'.")
15890 (defun org-time-stamp (arg &optional inactive)
15891 "Prompt for a date/time and insert a time stamp.
15893 If the user specifies a time like HH:MM or if this command is
15894 called with at least one prefix argument, the time stamp contains
15895 the date and the time. Otherwise, only the date is included.
15897 All parts of a date not specified by the user are filled in from
15898 the timestamp at point, if any, or the current date/time
15899 otherwise.
15901 If there is already a timestamp at the cursor, it is replaced.
15903 With two universal prefix arguments, insert an active timestamp
15904 with the current time without prompting the user.
15906 When called from lisp, the timestamp is inactive if INACTIVE is
15907 non-nil."
15908 (interactive "P")
15909 (let* ((ts (cond
15910 ((org-at-date-range-p t)
15911 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15912 ((org-at-timestamp-p 'lax) (match-string 0))))
15913 ;; Default time is either the timestamp at point or today.
15914 ;; When entering a range, only the range start is considered.
15915 (default-time (if (not ts) (current-time)
15916 (apply #'encode-time (org-parse-time-string ts))))
15917 (default-input (and ts (org-get-compact-tod ts)))
15918 (repeater (and ts
15919 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15920 (match-string 0 ts)))
15921 org-time-was-given
15922 org-end-time-was-given
15923 (time
15924 (and (if (equal arg '(16)) (current-time)
15925 ;; Preserve `this-command' and `last-command'.
15926 (let ((this-command this-command)
15927 (last-command last-command))
15928 (org-read-date
15929 arg 'totime nil nil default-time default-input
15930 inactive))))))
15931 (cond
15932 ((and ts
15933 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15934 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15935 (insert "--")
15936 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15938 ;; Make sure we're on a timestamp. When in the middle of a date
15939 ;; range, move arbitrarily to range end.
15940 (unless (org-at-timestamp-p 'lax)
15941 (skip-chars-forward "-")
15942 (org-at-timestamp-p 'lax))
15943 (replace-match "")
15944 (setq org-last-changed-timestamp
15945 (org-insert-time-stamp
15946 time (or org-time-was-given arg)
15947 inactive nil nil (list org-end-time-was-given)))
15948 (when repeater
15949 (backward-char)
15950 (insert " " repeater)
15951 (setq org-last-changed-timestamp
15952 (concat (substring org-last-inserted-timestamp 0 -1)
15953 " " repeater ">")))
15954 (message "Timestamp updated"))
15955 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
15956 (t (org-insert-time-stamp
15957 time (or org-time-was-given arg) inactive nil nil
15958 (list org-end-time-was-given))))))
15960 ;; FIXME: can we use this for something else, like computing time differences?
15961 (defun org-get-compact-tod (s)
15962 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15963 (let* ((t1 (match-string 1 s))
15964 (h1 (string-to-number (match-string 2 s)))
15965 (m1 (string-to-number (match-string 3 s)))
15966 (t2 (and (match-end 4) (match-string 5 s)))
15967 (h2 (and t2 (string-to-number (match-string 6 s))))
15968 (m2 (and t2 (string-to-number (match-string 7 s))))
15969 dh dm)
15970 (if (not t2)
15972 (setq dh (- h2 h1) dm (- m2 m1))
15973 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15974 (concat t1 "+" (number-to-string dh)
15975 (and (/= 0 dm) (format ":%02d" dm)))))))
15977 (defun org-time-stamp-inactive (&optional arg)
15978 "Insert an inactive time stamp.
15980 An inactive time stamp is enclosed in square brackets instead of angle
15981 brackets. It is inactive in the sense that it does not trigger agenda entries,
15982 does not link to the calendar and cannot be changed with the S-cursor keys.
15983 So these are more for recording a certain time/date.
15985 If the user specifies a time like HH:MM or if this command is called with
15986 at least one prefix argument, the time stamp contains the date and the time.
15987 Otherwise, only the date is included.
15989 When called with two universal prefix arguments, insert an active time stamp
15990 with the current time without prompting the user."
15991 (interactive "P")
15992 (org-time-stamp arg 'inactive))
15994 (defvar org-date-ovl (make-overlay 1 1))
15995 (overlay-put org-date-ovl 'face 'org-date-selected)
15996 (delete-overlay org-date-ovl)
15998 (defvar org-ans1) ; dynamically scoped parameter
15999 (defvar org-ans2) ; dynamically scoped parameter
16001 (defvar org-plain-time-of-day-regexp) ; defined below
16003 (defvar org-overriding-default-time nil) ; dynamically scoped
16004 (defvar org-read-date-overlay nil)
16005 (defvar org-dcst nil) ; dynamically scoped
16006 (defvar org-read-date-history nil)
16007 (defvar org-read-date-final-answer nil)
16008 (defvar org-read-date-analyze-futurep nil)
16009 (defvar org-read-date-analyze-forced-year nil)
16010 (defvar org-read-date-inactive)
16012 (defvar org-read-date-minibuffer-local-map
16013 (let* ((map (make-sparse-keymap)))
16014 (set-keymap-parent map minibuffer-local-map)
16015 (org-defkey map (kbd ".")
16016 (lambda () (interactive)
16017 ;; Are we at the beginning of the prompt?
16018 (if (looking-back "^[^:]+: "
16019 (let ((inhibit-field-text-motion t))
16020 (line-beginning-position)))
16021 (org-eval-in-calendar '(calendar-goto-today))
16022 (insert "."))))
16023 (org-defkey map (kbd "C-.")
16024 (lambda () (interactive)
16025 (org-eval-in-calendar '(calendar-goto-today))))
16026 (org-defkey map (kbd "M-S-<left>")
16027 (lambda () (interactive)
16028 (org-eval-in-calendar '(calendar-backward-month 1))))
16029 (org-defkey map (kbd "ESC S-<left>")
16030 (lambda () (interactive)
16031 (org-eval-in-calendar '(calendar-backward-month 1))))
16032 (org-defkey map (kbd "M-S-<right>")
16033 (lambda () (interactive)
16034 (org-eval-in-calendar '(calendar-forward-month 1))))
16035 (org-defkey map (kbd "ESC S-<right>")
16036 (lambda () (interactive)
16037 (org-eval-in-calendar '(calendar-forward-month 1))))
16038 (org-defkey map (kbd "M-S-<up>")
16039 (lambda () (interactive)
16040 (org-eval-in-calendar '(calendar-backward-year 1))))
16041 (org-defkey map (kbd "ESC S-<up>")
16042 (lambda () (interactive)
16043 (org-eval-in-calendar '(calendar-backward-year 1))))
16044 (org-defkey map (kbd "M-S-<down>")
16045 (lambda () (interactive)
16046 (org-eval-in-calendar '(calendar-forward-year 1))))
16047 (org-defkey map (kbd "ESC S-<down>")
16048 (lambda () (interactive)
16049 (org-eval-in-calendar '(calendar-forward-year 1))))
16050 (org-defkey map (kbd "S-<up>")
16051 (lambda () (interactive)
16052 (org-eval-in-calendar '(calendar-backward-week 1))))
16053 (org-defkey map (kbd "S-<down>")
16054 (lambda () (interactive)
16055 (org-eval-in-calendar '(calendar-forward-week 1))))
16056 (org-defkey map (kbd "S-<left>")
16057 (lambda () (interactive)
16058 (org-eval-in-calendar '(calendar-backward-day 1))))
16059 (org-defkey map (kbd "S-<right>")
16060 (lambda () (interactive)
16061 (org-eval-in-calendar '(calendar-forward-day 1))))
16062 (org-defkey map (kbd "!")
16063 (lambda () (interactive)
16064 (org-eval-in-calendar '(diary-view-entries))
16065 (message "")))
16066 (org-defkey map (kbd ">")
16067 (lambda () (interactive)
16068 (org-eval-in-calendar '(calendar-scroll-left 1))))
16069 (org-defkey map (kbd "<")
16070 (lambda () (interactive)
16071 (org-eval-in-calendar '(calendar-scroll-right 1))))
16072 (org-defkey map (kbd "C-v")
16073 (lambda () (interactive)
16074 (org-eval-in-calendar
16075 '(calendar-scroll-left-three-months 1))))
16076 (org-defkey map (kbd "M-v")
16077 (lambda () (interactive)
16078 (org-eval-in-calendar
16079 '(calendar-scroll-right-three-months 1))))
16080 map)
16081 "Keymap for minibuffer commands when using `org-read-date'.")
16083 (defvar org-def)
16084 (defvar org-defdecode)
16085 (defvar org-with-time)
16087 (defvar calendar-setup) ; Dynamically scoped.
16088 (defun org-read-date (&optional with-time to-time from-string prompt
16089 default-time default-input inactive)
16090 "Read a date, possibly a time, and make things smooth for the user.
16091 The prompt will suggest to enter an ISO date, but you can also enter anything
16092 which will at least partially be understood by `parse-time-string'.
16093 Unrecognized parts of the date will default to the current day, month, year,
16094 hour and minute. If this command is called to replace a timestamp at point,
16095 or to enter the second timestamp of a range, the default time is taken
16096 from the existing stamp. Furthermore, the command prefers the future,
16097 so if you are giving a date where the year is not given, and the day-month
16098 combination is already past in the current year, it will assume you
16099 mean next year. For details, see the manual. A few examples:
16101 3-2-5 --> 2003-02-05
16102 feb 15 --> currentyear-02-15
16103 2/15 --> currentyear-02-15
16104 sep 12 9 --> 2009-09-12
16105 12:45 --> today 12:45
16106 22 sept 0:34 --> currentyear-09-22 0:34
16107 12 --> currentyear-currentmonth-12
16108 Fri --> nearest Friday after today
16109 -Tue --> last Tuesday
16110 etc.
16112 Furthermore you can specify a relative date by giving, as the *first* thing
16113 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16114 change in days weeks, months, years.
16115 With a single plus or minus, the date is relative to today. With a double
16116 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16117 +4d --> four days from today
16118 +4 --> same as above
16119 +2w --> two weeks from today
16120 ++5 --> five days from default date
16122 The function understands only English month and weekday abbreviations.
16124 While prompting, a calendar is popped up - you can also select the
16125 date with the mouse (button 1). The calendar shows a period of three
16126 months. To scroll it to other months, use the keys `>' and `<'.
16127 If you don't like the calendar, turn it off with
16128 (setq org-read-date-popup-calendar nil)
16130 With optional argument TO-TIME, the date will immediately be converted
16131 to an internal time.
16132 With an optional argument WITH-TIME, the prompt will suggest to
16133 also insert a time. Note that when WITH-TIME is not set, you can
16134 still enter a time, and this function will inform the calling routine
16135 about this change. The calling routine may then choose to change the
16136 format used to insert the time stamp into the buffer to include the time.
16137 With optional argument FROM-STRING, read from this string instead from
16138 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16139 the time/date that is used for everything that is not specified by the
16140 user."
16141 (require 'parse-time)
16142 (let* ((org-with-time with-time)
16143 (org-time-stamp-rounding-minutes
16144 (if (equal org-with-time '(16))
16145 '(0 0)
16146 org-time-stamp-rounding-minutes))
16147 (org-dcst org-display-custom-times)
16148 (ct (org-current-time))
16149 (org-def (or org-overriding-default-time default-time ct))
16150 (org-defdecode (decode-time org-def))
16151 (cur-frame (selected-frame))
16152 (mouse-autoselect-window nil) ; Don't let the mouse jump
16153 (calendar-setup
16154 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16155 (calendar-move-hook nil)
16156 (calendar-view-diary-initially-flag nil)
16157 (calendar-view-holidays-initially-flag nil)
16158 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16159 ;; Rationalize `org-def' and `org-defdecode', if required.
16160 (when (< (nth 2 org-defdecode) org-extend-today-until)
16161 (setf (nth 2 org-defdecode) -1)
16162 (setf (nth 1 org-defdecode) 59)
16163 (setq org-def (apply #'encode-time org-defdecode))
16164 (setq org-defdecode (decode-time org-def)))
16165 (let* ((timestr (format-time-string
16166 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16167 org-def))
16168 (prompt (concat (if prompt (concat prompt " ") "")
16169 (format "Date+time [%s]: " timestr))))
16170 (cond
16171 (from-string (setq ans from-string))
16172 (org-read-date-popup-calendar
16173 (save-excursion
16174 (save-window-excursion
16175 (calendar)
16176 (when (eq calendar-setup 'calendar-only)
16177 (setq cal-frame
16178 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16179 (select-frame cal-frame))
16180 (org-eval-in-calendar '(setq cursor-type nil) t)
16181 (unwind-protect
16182 (progn
16183 (calendar-forward-day (- (time-to-days org-def)
16184 (calendar-absolute-from-gregorian
16185 (calendar-current-date))))
16186 (org-eval-in-calendar nil t)
16187 (let* ((old-map (current-local-map))
16188 (map (copy-keymap calendar-mode-map))
16189 (minibuffer-local-map
16190 (copy-keymap org-read-date-minibuffer-local-map)))
16191 (org-defkey map (kbd "RET") 'org-calendar-select)
16192 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16193 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16194 (unwind-protect
16195 (progn
16196 (use-local-map map)
16197 (setq org-read-date-inactive inactive)
16198 (add-hook 'post-command-hook 'org-read-date-display)
16199 (setq org-ans0
16200 (read-string prompt
16201 default-input
16202 'org-read-date-history
16203 nil))
16204 ;; org-ans0: from prompt
16205 ;; org-ans1: from mouse click
16206 ;; org-ans2: from calendar motion
16207 (setq ans
16208 (concat org-ans0 " " (or org-ans1 org-ans2))))
16209 (remove-hook 'post-command-hook 'org-read-date-display)
16210 (use-local-map old-map)
16211 (when org-read-date-overlay
16212 (delete-overlay org-read-date-overlay)
16213 (setq org-read-date-overlay nil)))))
16214 (bury-buffer "*Calendar*")
16215 (when cal-frame
16216 (delete-frame cal-frame)
16217 (select-frame-set-input-focus cur-frame))))))
16219 (t ; Naked prompt only
16220 (unwind-protect
16221 (setq ans (read-string prompt default-input
16222 'org-read-date-history timestr))
16223 (when org-read-date-overlay
16224 (delete-overlay org-read-date-overlay)
16225 (setq org-read-date-overlay nil))))))
16227 (setq final (org-read-date-analyze ans org-def org-defdecode))
16229 (when org-read-date-analyze-forced-year
16230 (message "Year was forced into %s"
16231 (if org-read-date-force-compatible-dates
16232 "compatible range (1970-2037)"
16233 "range representable on this machine"))
16234 (ding))
16236 ;; One round trip to get rid of 34th of August and stuff like that....
16237 (setq final (decode-time (apply 'encode-time final)))
16239 (setq org-read-date-final-answer ans)
16241 (if to-time
16242 (apply 'encode-time final)
16243 (if (and (boundp 'org-time-was-given) org-time-was-given)
16244 (format "%04d-%02d-%02d %02d:%02d"
16245 (nth 5 final) (nth 4 final) (nth 3 final)
16246 (nth 2 final) (nth 1 final))
16247 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16249 (defun org-read-date-display ()
16250 "Display the current date prompt interpretation in the minibuffer."
16251 (when org-read-date-display-live
16252 (when org-read-date-overlay
16253 (delete-overlay org-read-date-overlay))
16254 (when (minibufferp (current-buffer))
16255 (save-excursion
16256 (end-of-line 1)
16257 (while (not (equal (buffer-substring
16258 (max (point-min) (- (point) 4)) (point))
16259 " "))
16260 (insert " ")))
16261 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16262 " " (or org-ans1 org-ans2)))
16263 (org-end-time-was-given nil)
16264 (f (org-read-date-analyze ans org-def org-defdecode))
16265 (fmts (if org-dcst
16266 org-time-stamp-custom-formats
16267 org-time-stamp-formats))
16268 (fmt (if (or org-with-time
16269 (and (boundp 'org-time-was-given) org-time-was-given))
16270 (cdr fmts)
16271 (car fmts)))
16272 (txt (format-time-string fmt (apply 'encode-time f)))
16273 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16274 (txt (concat "=> " txt)))
16275 (when (and org-end-time-was-given
16276 (string-match org-plain-time-of-day-regexp txt))
16277 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16278 org-end-time-was-given
16279 (substring txt (match-end 0)))))
16280 (when org-read-date-analyze-futurep
16281 (setq txt (concat txt " (=>F)")))
16282 (setq org-read-date-overlay
16283 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16284 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16286 (defun org-read-date-analyze (ans def defdecode)
16287 "Analyze the combined answer of the date prompt."
16288 ;; FIXME: cleanup and comment
16289 ;; Pass `current-time' result to `decode-time' (instead of calling
16290 ;; without arguments) so that only `current-time' has to be
16291 ;; overridden in tests.
16292 (let ((org-def def)
16293 (org-defdecode defdecode)
16294 (nowdecode (decode-time (current-time)))
16295 delta deltan deltaw deltadef year month day
16296 hour minute second wday pm h2 m2 tl wday1
16297 iso-year iso-weekday iso-week iso-date futurep kill-year)
16298 (setq org-read-date-analyze-futurep nil
16299 org-read-date-analyze-forced-year nil)
16300 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16301 (setq ans "+0"))
16303 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16304 (setq ans (replace-match "" t t ans)
16305 deltan (car delta)
16306 deltaw (nth 1 delta)
16307 deltadef (nth 2 delta)))
16309 ;; Check if there is an iso week date in there. If yes, store the
16310 ;; info and postpone interpreting it until the rest of the parsing
16311 ;; is done.
16312 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16313 (setq iso-year (when (match-end 1)
16314 (org-small-year-to-year
16315 (string-to-number (match-string 1 ans))))
16316 iso-weekday (when (match-end 3)
16317 (string-to-number (match-string 3 ans)))
16318 iso-week (string-to-number (match-string 2 ans)))
16319 (setq ans (replace-match "" t t ans)))
16321 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16322 (when (string-match
16323 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16324 (setq year (if (match-end 2)
16325 (string-to-number (match-string 2 ans))
16326 (progn (setq kill-year t)
16327 (string-to-number (format-time-string "%Y"))))
16328 month (string-to-number (match-string 3 ans))
16329 day (string-to-number (match-string 4 ans)))
16330 (setq year (org-small-year-to-year year))
16331 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16332 t nil ans)))
16334 ;; Help matching dotted european dates
16335 (when (string-match
16336 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16337 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16338 (setq kill-year t)
16339 (string-to-number (format-time-string "%Y")))
16340 day (string-to-number (match-string 1 ans))
16341 month (string-to-number (match-string 2 ans))
16342 ans (replace-match (format "%04d-%02d-%02d" year month day)
16343 t nil ans)))
16345 ;; Help matching american dates, like 5/30 or 5/30/7
16346 (when (string-match
16347 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16348 (setq year (if (match-end 4)
16349 (string-to-number (match-string 4 ans))
16350 (progn (setq kill-year t)
16351 (string-to-number (format-time-string "%Y"))))
16352 month (string-to-number (match-string 1 ans))
16353 day (string-to-number (match-string 2 ans)))
16354 (setq year (org-small-year-to-year year))
16355 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16356 t nil ans)))
16357 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16358 ;; If there is a time with am/pm, and *no* time without it, we convert
16359 ;; so that matching will be successful.
16360 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16361 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16362 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16363 (setq hour (string-to-number (match-string 1 ans))
16364 minute (if (match-end 3)
16365 (string-to-number (match-string 3 ans))
16367 pm (equal ?p
16368 (string-to-char (downcase (match-string 4 ans)))))
16369 (if (and (= hour 12) (not pm))
16370 (setq hour 0)
16371 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16372 (setq ans (replace-match (format "%02d:%02d" hour minute)
16373 t t ans))))
16375 ;; Check if a time range is given as a duration
16376 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16377 (setq hour (string-to-number (match-string 1 ans))
16378 h2 (+ hour (string-to-number (match-string 3 ans)))
16379 minute (string-to-number (match-string 2 ans))
16380 m2 (+ minute (if (match-end 5) (string-to-number
16381 (match-string 5 ans))0)))
16382 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16383 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16384 t t ans)))
16386 ;; Check if there is a time range
16387 (when (boundp 'org-end-time-was-given)
16388 (setq org-time-was-given nil)
16389 (when (and (string-match org-plain-time-of-day-regexp ans)
16390 (match-end 8))
16391 (setq org-end-time-was-given (match-string 8 ans))
16392 (setq ans (concat (substring ans 0 (match-beginning 7))
16393 (substring ans (match-end 7))))))
16395 (setq tl (parse-time-string ans)
16396 day (or (nth 3 tl) (nth 3 org-defdecode))
16397 month
16398 (cond ((nth 4 tl))
16399 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16400 ;; Day was specified. Make sure DAY+MONTH
16401 ;; combination happens in the future.
16402 ((nth 3 tl)
16403 (setq futurep t)
16404 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16405 (nth 4 nowdecode)))
16406 (t (nth 4 org-defdecode)))
16407 year
16408 (cond ((and (not kill-year) (nth 5 tl)))
16409 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16410 ;; Month was guessed in the future and is at least
16411 ;; equal to NOWDECODE's. Fix year accordingly.
16412 (futurep
16413 (if (or (> month (nth 4 nowdecode))
16414 (>= day (nth 3 nowdecode)))
16415 (nth 5 nowdecode)
16416 (1+ (nth 5 nowdecode))))
16417 ;; Month was specified. Make sure MONTH+YEAR
16418 ;; combination happens in the future.
16419 ((nth 4 tl)
16420 (setq futurep t)
16421 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16422 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16423 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16424 (t (nth 5 nowdecode))))
16425 (t (nth 5 org-defdecode)))
16426 hour (or (nth 2 tl) (nth 2 org-defdecode))
16427 minute (or (nth 1 tl) (nth 1 org-defdecode))
16428 second (or (nth 0 tl) 0)
16429 wday (nth 6 tl))
16431 (when (and (eq org-read-date-prefer-future 'time)
16432 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16433 (equal day (nth 3 nowdecode))
16434 (equal month (nth 4 nowdecode))
16435 (equal year (nth 5 nowdecode))
16436 (nth 2 tl)
16437 (or (< (nth 2 tl) (nth 2 nowdecode))
16438 (and (= (nth 2 tl) (nth 2 nowdecode))
16439 (nth 1 tl)
16440 (< (nth 1 tl) (nth 1 nowdecode)))))
16441 (setq day (1+ day)
16442 futurep t))
16444 ;; Special date definitions below
16445 (cond
16446 (iso-week
16447 ;; There was an iso week
16448 (require 'cal-iso)
16449 (setq futurep nil)
16450 (setq year (or iso-year year)
16451 day (or iso-weekday wday 1)
16452 wday nil ; to make sure that the trigger below does not match
16453 iso-date (calendar-gregorian-from-absolute
16454 (calendar-iso-to-absolute
16455 (list iso-week day year))))
16456 ; FIXME: Should we also push ISO weeks into the future?
16457 ; (when (and org-read-date-prefer-future
16458 ; (not iso-year)
16459 ; (< (calendar-absolute-from-gregorian iso-date)
16460 ; (time-to-days (current-time))))
16461 ; (setq year (1+ year)
16462 ; iso-date (calendar-gregorian-from-absolute
16463 ; (calendar-iso-to-absolute
16464 ; (list iso-week day year)))))
16465 (setq month (car iso-date)
16466 year (nth 2 iso-date)
16467 day (nth 1 iso-date)))
16468 (deltan
16469 (setq futurep nil)
16470 (unless deltadef
16471 ;; Pass `current-time' result to `decode-time' (instead of
16472 ;; calling without arguments) so that only `current-time' has
16473 ;; to be overridden in tests.
16474 (let ((now (decode-time (current-time))))
16475 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16476 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16477 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16478 ((equal deltaw "m") (setq month (+ month deltan)))
16479 ((equal deltaw "y") (setq year (+ year deltan)))))
16480 ((and wday (not (nth 3 tl)))
16481 ;; Weekday was given, but no day, so pick that day in the week
16482 ;; on or after the derived date.
16483 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16484 (unless (equal wday wday1)
16485 (setq day (+ day (% (- wday wday1 -7) 7))))))
16486 (when (and (boundp 'org-time-was-given)
16487 (nth 2 tl))
16488 (setq org-time-was-given t))
16489 (when (< year 100) (setq year (+ 2000 year)))
16490 ;; Check of the date is representable
16491 (if org-read-date-force-compatible-dates
16492 (progn
16493 (when (< year 1970)
16494 (setq year 1970 org-read-date-analyze-forced-year t))
16495 (when (> year 2037)
16496 (setq year 2037 org-read-date-analyze-forced-year t)))
16497 (condition-case nil
16498 (ignore (encode-time second minute hour day month year))
16499 (error
16500 (setq year (nth 5 org-defdecode))
16501 (setq org-read-date-analyze-forced-year t))))
16502 (setq org-read-date-analyze-futurep futurep)
16503 (list second minute hour day month year)))
16505 (defvar parse-time-weekdays)
16506 (defun org-read-date-get-relative (s today default)
16507 "Check string S for special relative date string.
16508 TODAY and DEFAULT are internal times, for today and for a default.
16509 Return shift list (N what def-flag)
16510 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16511 N is the number of WHATs to shift.
16512 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16513 the DEFAULT date rather than TODAY."
16514 (require 'parse-time)
16515 (when (and
16516 (string-match
16517 (concat
16518 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16519 "\\([0-9]+\\)?"
16520 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16521 "\\([ \t]\\|$\\)") s)
16522 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16523 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16524 (string-to-char (substring (match-string 1 s) -1))
16525 ?+))
16526 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16527 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16528 (what (if (match-end 3) (match-string 3 s) "d"))
16529 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16530 (date (if rel default today))
16531 (wday (nth 6 (decode-time date)))
16532 delta)
16533 (if wday1
16534 (progn
16535 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16536 (when (= delta 0) (setq delta 7))
16537 (when (= dir ?-)
16538 (setq delta (- delta 7))
16539 (when (= delta 0) (setq delta -7)))
16540 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16541 (list delta "d" rel))
16542 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16544 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16545 "Turn a user-specified date into the internal representation.
16546 The internal representation needed by the calendar is (month day year).
16547 This is a wrapper to handle the brain-dead convention in calendar that
16548 user function argument order change dependent on argument order."
16549 (pcase calendar-date-style
16550 (`american (list arg1 arg2 arg3))
16551 (`european (list arg2 arg1 arg3))
16552 (`iso (list arg2 arg3 arg1))))
16554 (defun org-eval-in-calendar (form &optional keepdate)
16555 "Eval FORM in the calendar window and return to current window.
16556 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16557 (let ((sf (selected-frame))
16558 (sw (selected-window)))
16559 (select-window (get-buffer-window "*Calendar*" t))
16560 (eval form)
16561 (when (and (not keepdate) (calendar-cursor-to-date))
16562 (let* ((date (calendar-cursor-to-date))
16563 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16564 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16565 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16566 (select-window sw)
16567 (select-frame-set-input-focus sf)))
16569 (defun org-calendar-select ()
16570 "Return to `org-read-date' with the date currently selected.
16571 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16572 (interactive)
16573 (when (calendar-cursor-to-date)
16574 (let* ((date (calendar-cursor-to-date))
16575 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16576 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16577 (when (active-minibuffer-window) (exit-minibuffer))))
16579 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16580 "Insert a date stamp for the date given by the internal TIME.
16581 See `format-time-string' for the format of TIME.
16582 WITH-HM means use the stamp format that includes the time of the day.
16583 INACTIVE means use square brackets instead of angular ones, so that the
16584 stamp will not contribute to the agenda.
16585 PRE and POST are optional strings to be inserted before and after the
16586 stamp.
16587 The command returns the inserted time stamp."
16588 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16589 stamp)
16590 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16591 (insert-before-markers (or pre ""))
16592 (when (listp extra)
16593 (setq extra (car extra))
16594 (if (and (stringp extra)
16595 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16596 (setq extra (format "-%02d:%02d"
16597 (string-to-number (match-string 1 extra))
16598 (string-to-number (match-string 2 extra))))
16599 (setq extra nil)))
16600 (when extra
16601 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16602 (insert-before-markers (setq stamp (format-time-string fmt time)))
16603 (insert-before-markers (or post ""))
16604 (setq org-last-inserted-timestamp stamp)))
16606 (defun org-toggle-time-stamp-overlays ()
16607 "Toggle the use of custom time stamp formats."
16608 (interactive)
16609 (setq org-display-custom-times (not org-display-custom-times))
16610 (unless org-display-custom-times
16611 (let ((p (point-min)) (bmp (buffer-modified-p)))
16612 (while (setq p (next-single-property-change p 'display))
16613 (when (and (get-text-property p 'display)
16614 (eq (get-text-property p 'face) 'org-date))
16615 (remove-text-properties
16616 p (setq p (next-single-property-change p 'display))
16617 '(display t))))
16618 (set-buffer-modified-p bmp)))
16619 (org-restart-font-lock)
16620 (setq org-table-may-need-update t)
16621 (if org-display-custom-times
16622 (message "Time stamps are overlaid with custom format")
16623 (message "Time stamp overlays removed")))
16625 (defun org-display-custom-time (beg end)
16626 "Overlay modified time stamp format over timestamp between BEG and END."
16627 (let* ((ts (buffer-substring beg end))
16628 t1 with-hm tf time str (off 0))
16629 (save-match-data
16630 (setq t1 (org-parse-time-string ts t))
16631 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16632 (setq off (- (match-end 0) (match-beginning 0)))))
16633 (setq end (- end off))
16634 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16635 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16636 time (org-fix-decoded-time t1)
16637 str (org-add-props
16638 (format-time-string
16639 (substring tf 1 -1) (apply 'encode-time time))
16640 nil 'mouse-face 'highlight))
16641 (put-text-property beg end 'display str)))
16643 (defun org-fix-decoded-time (time)
16644 "Set 0 instead of nil for the first 6 elements of time.
16645 Don't touch the rest."
16646 (let ((n 0))
16647 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16649 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16650 "Difference between TIMESTAMP-STRING and now in days.
16651 If SECONDS is non-nil, return the difference in seconds."
16652 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16653 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16654 (funcall fdiff (current-time)))))
16656 (defun org-deadline-close-p (timestamp-string &optional ndays)
16657 "Is the time in TIMESTAMP-STRING close to the current date?"
16658 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16659 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16660 (not (org-entry-is-done-p))))
16662 (defun org-get-wdays (ts &optional delay zero-delay)
16663 "Get the deadline lead time appropriate for timestring TS.
16664 When DELAY is non-nil, get the delay time for scheduled items
16665 instead of the deadline lead time. When ZERO-DELAY is non-nil
16666 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16667 don't try to find the delay cookie in the scheduled timestamp."
16668 (let ((tv (if delay org-scheduled-delay-days
16669 org-deadline-warning-days)))
16670 (cond
16671 ((or (and delay (< tv 0))
16672 (and delay zero-delay (<= tv 0))
16673 (and (not delay) (<= tv 0)))
16674 ;; Enforce this value no matter what
16675 (- tv))
16676 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16677 ;; lead time is specified.
16678 (floor (* (string-to-number (match-string 1 ts))
16679 (cdr (assoc (match-string 2 ts)
16680 '(("d" . 1) ("w" . 7)
16681 ("m" . 30.4) ("y" . 365.25)
16682 ("h" . 0.041667)))))))
16683 ;; go for the default.
16684 (t tv))))
16686 (defun org-calendar-select-mouse (ev)
16687 "Return to `org-read-date' with the date currently selected.
16688 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16689 (interactive "e")
16690 (mouse-set-point ev)
16691 (when (calendar-cursor-to-date)
16692 (let* ((date (calendar-cursor-to-date))
16693 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16694 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16695 (when (active-minibuffer-window) (exit-minibuffer))))
16697 (defun org-check-deadlines (ndays)
16698 "Check if there are any deadlines due or past due.
16699 A deadline is considered due if it happens within `org-deadline-warning-days'
16700 days from today's date. If the deadline appears in an entry marked DONE,
16701 it is not shown. A numeric prefix argument NDAYS can be used to test that
16702 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16703 are shown."
16704 (interactive "P")
16705 (let* ((org-warn-days
16706 (cond
16707 ((equal ndays '(4)) 100000)
16708 (ndays (prefix-numeric-value ndays))
16709 (t (abs org-deadline-warning-days))))
16710 (case-fold-search nil)
16711 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16712 (callback
16713 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16714 (message "%d deadlines past-due or due within %d days"
16715 (org-occur regexp nil callback)
16716 org-warn-days)))
16718 (defsubst org-re-timestamp (type)
16719 "Return a regexp for timestamp TYPE.
16720 Allowed values for TYPE are:
16722 all: all timestamps
16723 active: only active timestamps (<...>)
16724 inactive: only inactive timestamps ([...])
16725 scheduled: only scheduled timestamps
16726 deadline: only deadline timestamps
16727 closed: only closed time-stamps
16729 When TYPE is nil, fall back on returning a regexp that matches
16730 both scheduled and deadline timestamps."
16731 (cl-case type
16732 (all org-ts-regexp-both)
16733 (active org-ts-regexp)
16734 (inactive org-ts-regexp-inactive)
16735 (scheduled org-scheduled-time-regexp)
16736 (deadline org-deadline-time-regexp)
16737 (closed org-closed-time-regexp)
16738 (otherwise
16739 (concat "\\<"
16740 (regexp-opt (list org-deadline-string org-scheduled-string))
16741 " *<\\([^>]+\\)>"))))
16743 (defun org-check-before-date (d)
16744 "Check if there are deadlines or scheduled entries before date D."
16745 (interactive (list (org-read-date)))
16746 (let* ((case-fold-search nil)
16747 (regexp (org-re-timestamp org-ts-type))
16748 (ts-type org-ts-type)
16749 (callback
16750 (lambda ()
16751 (let ((match (match-string 1)))
16752 (and (if (memq ts-type '(active inactive all))
16753 (eq (org-element-type (save-excursion
16754 (backward-char)
16755 (org-element-context)))
16756 'timestamp)
16757 (org-at-planning-p))
16758 (time-less-p
16759 (org-time-string-to-time match)
16760 (org-time-string-to-time d)))))))
16761 (message "%d entries before %s"
16762 (org-occur regexp nil callback)
16763 d)))
16765 (defun org-check-after-date (d)
16766 "Check if there are deadlines or scheduled entries after date D."
16767 (interactive (list (org-read-date)))
16768 (let* ((case-fold-search nil)
16769 (regexp (org-re-timestamp org-ts-type))
16770 (ts-type org-ts-type)
16771 (callback
16772 (lambda ()
16773 (let ((match (match-string 1)))
16774 (and (if (memq ts-type '(active inactive all))
16775 (eq (org-element-type (save-excursion
16776 (backward-char)
16777 (org-element-context)))
16778 'timestamp)
16779 (org-at-planning-p))
16780 (not (time-less-p
16781 (org-time-string-to-time match)
16782 (org-time-string-to-time d))))))))
16783 (message "%d entries after %s"
16784 (org-occur regexp nil callback)
16785 d)))
16787 (defun org-check-dates-range (start-date end-date)
16788 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16789 (interactive (list (org-read-date nil nil nil "Range starts")
16790 (org-read-date nil nil nil "Range end")))
16791 (let ((case-fold-search nil)
16792 (regexp (org-re-timestamp org-ts-type))
16793 (callback
16794 (let ((type org-ts-type))
16795 (lambda ()
16796 (let ((match (match-string 1)))
16797 (and
16798 (if (memq type '(active inactive all))
16799 (eq (org-element-type (save-excursion
16800 (backward-char)
16801 (org-element-context)))
16802 'timestamp)
16803 (org-at-planning-p))
16804 (not (time-less-p
16805 (org-time-string-to-time match)
16806 (org-time-string-to-time start-date)))
16807 (time-less-p
16808 (org-time-string-to-time match)
16809 (org-time-string-to-time end-date))))))))
16810 (message "%d entries between %s and %s"
16811 (org-occur regexp nil callback) start-date end-date)))
16813 (defun org-evaluate-time-range (&optional to-buffer)
16814 "Evaluate a time range by computing the difference between start and end.
16815 Normally the result is just printed in the echo area, but with prefix arg
16816 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16817 If the time range is actually in a table, the result is inserted into the
16818 next column.
16819 For time difference computation, a year is assumed to be exactly 365
16820 days in order to avoid rounding problems."
16821 (interactive "P")
16823 (org-clock-update-time-maybe)
16824 (save-excursion
16825 (unless (org-at-date-range-p t)
16826 (goto-char (point-at-bol))
16827 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16828 (unless (org-at-date-range-p t)
16829 (user-error "Not at a time-stamp range, and none found in current line")))
16830 (let* ((ts1 (match-string 1))
16831 (ts2 (match-string 2))
16832 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16833 (match-end (match-end 0))
16834 (time1 (org-time-string-to-time ts1))
16835 (time2 (org-time-string-to-time ts2))
16836 (t1 (float-time time1))
16837 (t2 (float-time time2))
16838 (diff (abs (- t2 t1)))
16839 (negative (< (- t2 t1) 0))
16840 ;; (ys (floor (* 365 24 60 60)))
16841 (ds (* 24 60 60))
16842 (hs (* 60 60))
16843 (fy "%dy %dd %02d:%02d")
16844 (fy1 "%dy %dd")
16845 (fd "%dd %02d:%02d")
16846 (fd1 "%dd")
16847 (fh "%02d:%02d")
16848 y d h m align)
16849 (if havetime
16850 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16852 d (floor (/ diff ds)) diff (mod diff ds)
16853 h (floor (/ diff hs)) diff (mod diff hs)
16854 m (floor (/ diff 60)))
16855 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16857 d (floor (+ (/ diff ds) 0.5))
16858 h 0 m 0))
16859 (if (not to-buffer)
16860 (message "%s" (org-make-tdiff-string y d h m))
16861 (if (org-at-table-p)
16862 (progn
16863 (goto-char match-end)
16864 (setq align t)
16865 (and (looking-at " *|") (goto-char (match-end 0))))
16866 (goto-char match-end))
16867 (when (looking-at
16868 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16869 (replace-match ""))
16870 (when negative (insert " -"))
16871 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16872 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16873 (insert " " (format fh h m))))
16874 (when align (org-table-align))
16875 (message "Time difference inserted")))))
16877 (defun org-make-tdiff-string (y d h m)
16878 (let ((fmt "")
16879 (l nil))
16880 (when (> y 0)
16881 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16882 (push y l))
16883 (when (> d 0)
16884 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16885 (push d l))
16886 (when (> h 0)
16887 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16888 (push h l))
16889 (when (> m 0)
16890 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16891 (push m l))
16892 (apply 'format fmt (nreverse l))))
16894 (defun org-time-string-to-time (s)
16895 "Convert timestamp string S into internal time."
16896 (apply #'encode-time (org-parse-time-string s)))
16898 (defun org-time-string-to-seconds (s)
16899 "Convert a timestamp string S into a number of seconds."
16900 (float-time (org-time-string-to-time s)))
16902 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16904 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16905 "Convert time stamp S to an absolute day number.
16907 If DAYNR in non-nil, and there is a specifier for a cyclic time
16908 stamp, get the closest date to DAYNR. If PREFER is
16909 `past' (respectively `future') return a date past (respectively
16910 after) or equal to DAYNR.
16912 POS is the location of time stamp S, as a buffer position in
16913 BUFFER.
16915 Diary sexp timestamps are matched against DAYNR, when non-nil.
16916 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16917 signaled."
16918 (cond
16919 ((string-match "\\`%%\\((.*)\\)" s)
16920 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16921 ;; only able to match individual dates. If it fails, raise an
16922 ;; error.
16923 (if (and daynr
16924 (org-diary-sexp-entry
16925 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16926 daynr
16927 (signal 'org-diary-sexp-no-match (list s))))
16928 (daynr (org-closest-date s daynr prefer))
16929 (t (time-to-days
16930 (condition-case errdata
16931 (apply #'encode-time (org-parse-time-string s))
16932 (error (error "Bad timestamp `%s'%s\nError was: %s"
16934 (if (not (and buffer pos)) ""
16935 (format-message " at %d in buffer `%s'" pos buffer))
16936 (cdr errdata))))))))
16938 (defun org-days-to-iso-week (days)
16939 "Return the iso week number."
16940 (require 'cal-iso)
16941 (car (calendar-iso-from-absolute days)))
16943 (defun org-small-year-to-year (year)
16944 "Convert 2-digit years into 4-digit years.
16945 YEAR is expanded into one of the 30 next years, if possible, or
16946 into a past one. Any year larger than 99 is returned unchanged."
16947 (if (>= year 100) year
16948 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
16949 (century (/ current 100))
16950 (offset (- year (% current 100))))
16951 (cond ((> offset 30) (+ (* (1- century) 100) year))
16952 ((> offset -70) (+ (* century 100) year))
16953 (t (+ (* (1+ century) 100) year))))))
16955 (defun org-time-from-absolute (d)
16956 "Return the time corresponding to date D.
16957 D may be an absolute day number, or a calendar-type list (month day year)."
16958 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16959 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16961 (defvar org-agenda-current-date)
16962 (defun org-calendar-holiday ()
16963 "List of holidays, for Diary display in Org mode."
16964 (require 'holidays)
16965 (let ((hl (calendar-check-holidays org-agenda-current-date)))
16966 (and hl (mapconcat #'identity hl "; "))))
16968 (defun org-diary-sexp-entry (sexp entry d)
16969 "Process a SEXP diary ENTRY for date D."
16970 (require 'diary-lib)
16971 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
16972 ;; dynamically.
16973 (let* ((sexp `(let ((entry ,entry)
16974 (date ',d))
16975 ,(car (read-from-string sexp))))
16976 (result (if calendar-debug-sexp (eval sexp)
16977 (condition-case nil
16978 (eval sexp)
16979 (error
16980 (beep)
16981 (message "Bad sexp at line %d in %s: %s"
16982 (org-current-line)
16983 (buffer-file-name) sexp)
16984 (sleep-for 2))))))
16985 (cond ((stringp result) (split-string result "; "))
16986 ((and (consp result)
16987 (not (consp (cdr result)))
16988 (stringp (cdr result))) (cdr result))
16989 ((and (consp result)
16990 (stringp (car result))) result)
16991 (result entry))))
16993 (defun org-diary-to-ical-string (frombuf)
16994 "Get iCalendar entries from diary entries in buffer FROMBUF.
16995 This uses the icalendar.el library."
16996 (let* ((tmpdir temporary-file-directory)
16997 (tmpfile (make-temp-name
16998 (expand-file-name "orgics" tmpdir)))
16999 buf rtn b e)
17000 (with-current-buffer frombuf
17001 (icalendar-export-region (point-min) (point-max) tmpfile)
17002 (setq buf (find-buffer-visiting tmpfile))
17003 (set-buffer buf)
17004 (goto-char (point-min))
17005 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17006 (setq b (match-beginning 0)))
17007 (goto-char (point-max))
17008 (when (re-search-backward "^END:VEVENT" nil t)
17009 (setq e (match-end 0)))
17010 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17011 (kill-buffer buf)
17012 (delete-file tmpfile)
17013 rtn))
17015 (defun org-closest-date (start current prefer)
17016 "Return closest date to CURRENT starting from START.
17018 CURRENT and START are both time stamps.
17020 When PREFER is `past', return a date that is either CURRENT or
17021 past. When PREFER is `future', return a date that is either
17022 CURRENT or future.
17024 Only time stamps with a repeater are modified. Any other time
17025 stamp stay unchanged. In any case, return value is an absolute
17026 day number."
17027 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17028 ;; No repeater. Do not shift time stamp.
17029 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17030 (let ((value (string-to-number (match-string 1 start)))
17031 (type (match-string 2 start)))
17032 (if (= 0 value)
17033 ;; Repeater with a 0-value is considered as void.
17034 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17035 (let* ((base (org-date-to-gregorian start))
17036 (target (org-date-to-gregorian current))
17037 (sday (calendar-absolute-from-gregorian base))
17038 (cday (calendar-absolute-from-gregorian target))
17039 n1 n2)
17040 ;; If START is already past CURRENT, just return START.
17041 (if (<= cday sday) sday
17042 ;; Compute closest date before (N1) and closest date past
17043 ;; (N2) CURRENT.
17044 (pcase type
17045 ("h"
17046 (let ((missing-hours
17047 (mod (+ (- (* 24 (- cday sday))
17048 (nth 2 (org-parse-time-string start)))
17049 org-extend-today-until)
17050 value)))
17051 (setf n1 (if (= missing-hours 0) cday
17052 (- cday (1+ (/ missing-hours 24)))))
17053 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17054 ((or "d" "w")
17055 (let ((value (if (equal type "w") (* 7 value) value)))
17056 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17057 (setf n2 (+ n1 value))))
17058 ("m"
17059 (let* ((add-months
17060 (lambda (d n)
17061 ;; Add N months to gregorian date D, i.e.,
17062 ;; a list (MONTH DAY YEAR). Return a valid
17063 ;; gregorian date.
17064 (let ((m (+ (nth 0 d) n)))
17065 (list (mod m 12)
17066 (nth 1 d)
17067 (+ (/ m 12) (nth 2 d))))))
17068 (months ; Complete months to TARGET.
17069 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17070 (- (nth 0 target) (nth 0 base))
17071 ;; If START's day is greater than
17072 ;; TARGET's, remove incomplete month.
17073 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17074 value)
17075 value))
17076 (before (funcall add-months base months)))
17077 (setf n1 (calendar-absolute-from-gregorian before))
17078 (setf n2
17079 (calendar-absolute-from-gregorian
17080 (funcall add-months before value)))))
17082 (let* ((d (nth 1 base))
17083 (m (nth 0 base))
17084 (y (nth 2 base))
17085 (years ; Complete years to TARGET.
17086 (* (/ (- (nth 2 target)
17088 ;; If START's month and day are
17089 ;; greater than TARGET's, remove
17090 ;; incomplete year.
17091 (if (or (> (nth 0 target) m)
17092 (and (= (nth 0 target) m)
17093 (> (nth 1 target) d)))
17096 value)
17097 value))
17098 (before (list m d (+ y years))))
17099 (setf n1 (calendar-absolute-from-gregorian before))
17100 (setf n2 (calendar-absolute-from-gregorian
17101 (list m d (+ (nth 2 before) value)))))))
17102 ;; Handle PREFER parameter, if any.
17103 (cond
17104 ((eq prefer 'past) (if (= cday n2) n2 n1))
17105 ((eq prefer 'future) (if (= cday n1) n1 n2))
17106 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17108 (defun org-date-to-gregorian (d)
17109 "Turn any specification of date D into a Gregorian date for the calendar."
17110 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17111 ((and (listp d) (= (length d) 3)) d)
17112 ((stringp d)
17113 (let ((d (org-parse-time-string d)))
17114 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17115 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17117 (defun org-parse-time-string (s &optional nodefault)
17118 "Parse the standard Org time string.
17120 This should be a lot faster than the normal `parse-time-string'.
17122 If time is not given, defaults to 0:00. However, with optional
17123 NODEFAULT, hour and minute fields will be nil if not given."
17124 (cond ((string-match org-ts-regexp0 s)
17125 (list 0
17126 (when (or (match-beginning 8) (not nodefault))
17127 (string-to-number (or (match-string 8 s) "0")))
17128 (when (or (match-beginning 7) (not nodefault))
17129 (string-to-number (or (match-string 7 s) "0")))
17130 (string-to-number (match-string 4 s))
17131 (string-to-number (match-string 3 s))
17132 (string-to-number (match-string 2 s))
17133 nil nil nil))
17134 ((string-match "^<[^>]+>$" s)
17135 ;; FIXME: `decode-time' needs to be called with ZONE as its
17136 ;; second argument. However, this requires at least Emacs
17137 ;; 25.1. We can do it when we switch to this version as our
17138 ;; minimal requirement.
17139 (decode-time (seconds-to-time (org-matcher-time s))))
17140 (t (error "Not a standard Org time string: %s" s))))
17142 (defun org-timestamp-up (&optional arg)
17143 "Increase the date item at the cursor by one.
17144 If the cursor is on the year, change the year. If it is on the month,
17145 the day or the time, change that.
17146 With prefix ARG, change by that many units."
17147 (interactive "p")
17148 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17150 (defun org-timestamp-down (&optional arg)
17151 "Decrease the date item at the cursor by one.
17152 If the cursor is on the year, change the year. If it is on the month,
17153 the day or the time, change that.
17154 With prefix ARG, change by that many units."
17155 (interactive "p")
17156 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17158 (defun org-timestamp-up-day (&optional arg)
17159 "Increase the date in the time stamp by one day.
17160 With prefix ARG, change that many days."
17161 (interactive "p")
17162 (if (and (not (org-at-timestamp-p 'lax))
17163 (org-at-heading-p))
17164 (org-todo 'up)
17165 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17167 (defun org-timestamp-down-day (&optional arg)
17168 "Decrease the date in the time stamp by one day.
17169 With prefix ARG, change that many days."
17170 (interactive "p")
17171 (if (and (not (org-at-timestamp-p 'lax))
17172 (org-at-heading-p))
17173 (org-todo 'down)
17174 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17176 (defun org-at-timestamp-p (&optional extended)
17177 "Non-nil if point is inside a timestamp.
17179 By default, the function only consider syntactically valid active
17180 timestamps. However, the caller may have a broader definition
17181 for timestamps. As a consequence, optional argument EXTENDED can
17182 be set to the following values
17184 `inactive'
17186 Include also syntactically valid inactive timestamps.
17188 `agenda'
17190 Include timestamps allowed in Agenda, i.e., those in
17191 properties drawers, planning lines and clock lines.
17193 `lax'
17195 Ignore context. The function matches any part of the
17196 document looking like a timestamp. This includes comments,
17197 example blocks...
17199 For backward-compatibility with Org 9.0, every other non-nil
17200 value is equivalent to `inactive'.
17202 When at a timestamp, return the position of the point as a symbol
17203 among `bracket', `after', `year', `month', `hour', `minute',
17204 `day' or a number of character from the last know part of the
17205 time stamp.
17207 When matching, the match groups are the following:
17208 group 1: year
17209 group 2: month
17210 group 3: day number
17211 group 4: day name
17212 group 5: hours, if any
17213 group 6: minutes, if any"
17214 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17215 (pos (point))
17216 (match?
17217 (let ((boundaries (org-in-regexp regexp)))
17218 (save-match-data
17219 (cond ((null boundaries) nil)
17220 ((eq extended 'lax) t)
17222 (or (and (eq extended 'agenda)
17223 (or (org-at-planning-p)
17224 (org-at-property-p)
17225 (and (bound-and-true-p
17226 org-agenda-include-inactive-timestamps)
17227 (org-at-clock-log-p))))
17228 (eq 'timestamp
17229 (save-excursion
17230 (when (= pos (cdr boundaries)) (forward-char -1))
17231 (org-element-type (org-element-context)))))))))))
17232 (cond
17233 ((not match?) nil)
17234 ((= pos (match-beginning 0)) 'bracket)
17235 ;; Distinguish location right before the closing bracket from
17236 ;; right after it.
17237 ((= pos (1- (match-end 0))) 'bracket)
17238 ((= pos (match-end 0)) 'after)
17239 ((org-pos-in-match-range pos 2) 'year)
17240 ((org-pos-in-match-range pos 3) 'month)
17241 ((org-pos-in-match-range pos 7) 'hour)
17242 ((org-pos-in-match-range pos 8) 'minute)
17243 ((or (org-pos-in-match-range pos 4)
17244 (org-pos-in-match-range pos 5)) 'day)
17245 ((and (> pos (or (match-end 8) (match-end 5)))
17246 (< pos (match-end 0)))
17247 (- pos (or (match-end 8) (match-end 5))))
17248 (t 'day))))
17250 (defun org-toggle-timestamp-type ()
17251 "Toggle the type (<active> or [inactive]) of a time stamp."
17252 (interactive)
17253 (when (org-at-timestamp-p 'lax)
17254 (let ((beg (match-beginning 0)) (end (match-end 0))
17255 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17256 (save-excursion
17257 (goto-char beg)
17258 (while (re-search-forward "[][<>]" end t)
17259 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17260 t t)))
17261 (message "Timestamp is now %sactive"
17262 (if (equal (char-after beg) ?<) "" "in")))))
17264 (defun org-at-clock-log-p ()
17265 "Non-nil if point is on a clock log line."
17266 (and (org-match-line org-clock-line-re)
17267 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17269 (defvar org-clock-history) ; defined in org-clock.el
17270 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17271 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17272 "Change the date in the time stamp at point.
17273 The date will be changed by N times WHAT. WHAT can be `day', `month',
17274 `year', `minute', `second'. If WHAT is not given, the cursor position
17275 in the timestamp determines what will be changed.
17276 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17277 (let ((origin (point))
17278 (timestamp? (org-at-timestamp-p 'lax))
17279 origin-cat
17280 with-hm inactive
17281 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17282 extra rem
17283 ts time time0 fixnext clrgx)
17284 (unless timestamp? (user-error "Not at a timestamp"))
17285 (if (and (not what) (eq timestamp? 'bracket))
17286 (org-toggle-timestamp-type)
17287 ;; Point isn't on brackets. Remember the part of the time-stamp
17288 ;; the point was in. Indeed, size of time-stamps may change,
17289 ;; but point must be kept in the same category nonetheless.
17290 (setq origin-cat timestamp?)
17291 (when (and (not what) (not (eq timestamp? 'day))
17292 org-display-custom-times
17293 (get-text-property (point) 'display)
17294 (not (get-text-property (1- (point)) 'display)))
17295 (setq timestamp? 'day))
17296 (setq timestamp? (or what timestamp?)
17297 inactive (= (char-after (match-beginning 0)) ?\[)
17298 ts (match-string 0))
17299 (replace-match "")
17300 (when (string-match
17301 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17303 (setq extra (match-string 1 ts))
17304 (when suppress-tmp-delay
17305 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17306 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17307 (setq with-hm t))
17308 (setq time0 (org-parse-time-string ts))
17309 (when (and updown
17310 (eq timestamp? 'minute)
17311 (not current-prefix-arg))
17312 ;; This looks like s-up and s-down. Change by one rounding step.
17313 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17314 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17315 (setcar (cdr time0) (+ (nth 1 time0)
17316 (if (> n 0) (- rem) (- dm rem))))))
17317 (setq time
17318 (apply #'encode-time
17319 (or (car time0) 0)
17320 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17321 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17322 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17323 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17324 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17325 (nthcdr 6 time0)))
17326 (when (and (memq timestamp? '(hour minute))
17327 extra
17328 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17329 (setq extra (org-modify-ts-extra
17330 extra
17331 (if (eq timestamp? 'hour) 2 5)
17332 n dm)))
17333 (when (integerp timestamp?)
17334 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17335 (when (eq what 'calendar)
17336 (let ((cal-date (org-get-date-from-calendar)))
17337 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17338 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17339 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17340 (setcar time0 (or (car time0) 0))
17341 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17342 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17343 (setq time (apply 'encode-time time0))))
17344 ;; Insert the new time-stamp, and ensure point stays in the same
17345 ;; category as before (i.e. not after the last position in that
17346 ;; category).
17347 (let ((pos (point)))
17348 ;; Stay before inserted string. `save-excursion' is of no use.
17349 (setq org-last-changed-timestamp
17350 (org-insert-time-stamp time with-hm inactive nil nil extra))
17351 (goto-char pos))
17352 (save-match-data
17353 (looking-at org-ts-regexp3)
17354 (goto-char
17355 (pcase origin-cat
17356 ;; `day' category ends before `hour' if any, or at the end
17357 ;; of the day name.
17358 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17359 (`hour (min (match-end 7) origin))
17360 (`minute (min (1- (match-end 8)) origin))
17361 ((pred integerp) (min (1- (match-end 0)) origin))
17362 ;; Point was right after the time-stamp. However, the
17363 ;; time-stamp length might have changed, so refer to
17364 ;; (match-end 0) instead.
17365 (`after (match-end 0))
17366 ;; `year' and `month' have both fixed size: point couldn't
17367 ;; have moved into another part.
17368 (_ origin))))
17369 ;; Update clock if on a CLOCK line.
17370 (org-clock-update-time-maybe)
17371 ;; Maybe adjust the closest clock in `org-clock-history'
17372 (when org-clock-adjust-closest
17373 (if (not (and (org-at-clock-log-p)
17374 (< 1 (length (delq nil (mapcar 'marker-position
17375 org-clock-history))))))
17376 (message "No clock to adjust")
17377 (cond ((save-excursion ; fix previous clock?
17378 (re-search-backward org-ts-regexp0 nil t)
17379 (looking-back (concat org-clock-string " \\[")
17380 (line-beginning-position)))
17381 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17382 ((save-excursion ; fix next clock?
17383 (re-search-backward org-ts-regexp0 nil t)
17384 (looking-at (concat org-ts-regexp0 "\\] =>")))
17385 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17386 (save-window-excursion
17387 ;; Find closest clock to point, adjust the previous/next one in history
17388 (let* ((p (save-excursion (org-back-to-heading t)))
17389 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17390 (clfixnth
17391 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17392 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17393 (if (not clfixpos)
17394 (message "No clock to adjust")
17395 (save-excursion
17396 (org-goto-marker-or-bmk clfixpos)
17397 (org-show-subtree)
17398 (when (re-search-forward clrgx nil t)
17399 (goto-char (match-beginning 1))
17400 (let (org-clock-adjust-closest)
17401 (org-timestamp-change n timestamp? updown))
17402 (message "Clock adjusted in %s for heading: %s"
17403 (file-name-nondirectory (buffer-file-name))
17404 (org-get-heading t t)))))))))
17405 ;; Try to recenter the calendar window, if any.
17406 (when (and org-calendar-follow-timestamp-change
17407 (get-buffer-window "*Calendar*" t)
17408 (memq timestamp? '(day month year)))
17409 (org-recenter-calendar (time-to-days time))))))
17411 (defun org-modify-ts-extra (s pos n dm)
17412 "Change the different parts of the lead-time and repeat fields in timestamp."
17413 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17414 ng h m new rem)
17415 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17416 (cond
17417 ((or (org-pos-in-match-range pos 2)
17418 (org-pos-in-match-range pos 3))
17419 (setq m (string-to-number (match-string 3 s))
17420 h (string-to-number (match-string 2 s)))
17421 (if (org-pos-in-match-range pos 2)
17422 (setq h (+ h n))
17423 (setq n (* dm (with-no-warnings (signum n))))
17424 (unless (= 0 (setq rem (% m dm)))
17425 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17426 (setq m (+ m n)))
17427 (when (< m 0) (setq m (+ m 60) h (1- h)))
17428 (when (> m 59) (setq m (- m 60) h (1+ h)))
17429 (setq h (mod h 24))
17430 (setq ng 1 new (format "-%02d:%02d" h m)))
17431 ((org-pos-in-match-range pos 6)
17432 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17433 ((org-pos-in-match-range pos 5)
17434 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17436 ((org-pos-in-match-range pos 9)
17437 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17438 ((org-pos-in-match-range pos 8)
17439 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17441 (when ng
17442 (setq s (concat
17443 (substring s 0 (match-beginning ng))
17445 (substring s (match-end ng))))))
17448 (defun org-recenter-calendar (d)
17449 "If the calendar is visible, recenter it to date D."
17450 (let ((cwin (get-buffer-window "*Calendar*" t)))
17451 (when cwin
17452 (let ((calendar-move-hook nil))
17453 (with-selected-window cwin
17454 (calendar-goto-date
17455 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17457 (defun org-goto-calendar (&optional arg)
17458 "Go to the Emacs calendar at the current date.
17459 If there is a time stamp in the current line, go to that date.
17460 A prefix ARG can be used to force the current date."
17461 (interactive "P")
17462 (let ((calendar-move-hook nil)
17463 (calendar-view-holidays-initially-flag nil)
17464 (calendar-view-diary-initially-flag nil)
17465 diff)
17466 (when (or (org-at-timestamp-p 'lax)
17467 (org-match-line (concat ".*" org-ts-regexp)))
17468 (let ((d1 (time-to-days (current-time)))
17469 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17470 (setq diff (- d2 d1))))
17471 (calendar)
17472 (calendar-goto-today)
17473 (when (and diff (not arg)) (calendar-forward-day diff))))
17475 (defun org-get-date-from-calendar ()
17476 "Return a list (month day year) of date at point in calendar."
17477 (with-current-buffer "*Calendar*"
17478 (save-match-data
17479 (calendar-cursor-to-date))))
17481 (defun org-date-from-calendar ()
17482 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17483 If there is already a time stamp at the cursor position, update it."
17484 (interactive)
17485 (if (org-at-timestamp-p 'lax)
17486 (org-timestamp-change 0 'calendar)
17487 (let ((cal-date (org-get-date-from-calendar)))
17488 (org-insert-time-stamp
17489 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17491 (defcustom org-effort-durations
17492 `(("min" . 1)
17493 ("h" . 60)
17494 ("d" . ,(* 60 8))
17495 ("w" . ,(* 60 8 5))
17496 ("m" . ,(* 60 8 5 4))
17497 ("y" . ,(* 60 8 5 40)))
17498 "Conversion factor to minutes for an effort modifier.
17500 Each entry has the form (MODIFIER . MINUTES).
17502 In an effort string, a number followed by MODIFIER is multiplied
17503 by the specified number of MINUTES to obtain an effort in
17504 minutes.
17506 For example, if the value of this variable is ((\"hours\" . 60)), then an
17507 effort string \"2hours\" is equivalent to 120 minutes."
17508 :group 'org-agenda
17509 :version "26.1"
17510 :package-version '(Org . "8.3")
17511 :type '(alist :key-type (string :tag "Modifier")
17512 :value-type (number :tag "Minutes")))
17514 (defcustom org-image-actual-width t
17515 "Should we use the actual width of images when inlining them?
17517 When set to t, always use the image width.
17519 When set to a number, use imagemagick (when available) to set
17520 the image's width to this value.
17522 When set to a number in a list, try to get the width from any
17523 #+ATTR.* keyword if it matches a width specification like
17525 #+ATTR_HTML: :width 300px
17527 and fall back on that number if none is found.
17529 When set to nil, try to get the width from an #+ATTR.* keyword
17530 and fall back on the original width if none is found.
17532 This requires Emacs >= 24.1, build with imagemagick support."
17533 :group 'org-appearance
17534 :version "24.4"
17535 :package-version '(Org . "8.0")
17536 :type '(choice
17537 (const :tag "Use the image width" t)
17538 (integer :tag "Use a number of pixels")
17539 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17540 (const :tag "Use #+ATTR* or don't resize" nil)))
17542 (defcustom org-agenda-inhibit-startup nil
17543 "Inhibit startup when preparing agenda buffers.
17544 When this variable is t, the initialization of the Org agenda
17545 buffers is inhibited: e.g. the visibility state is not set, the
17546 tables are not re-aligned, etc."
17547 :type 'boolean
17548 :version "24.3"
17549 :group 'org-agenda)
17551 (defcustom org-agenda-ignore-properties nil
17552 "Avoid updating text properties when building the agenda.
17553 Properties are used to prepare buffers for effort estimates,
17554 appointments, statistics and subtree-local categories.
17555 If you don't use these in the agenda, you can add them to this
17556 list and agenda building will be a bit faster.
17557 The value is a list, with zero or more of the symbols `effort', `appt',
17558 `stats' or `category'."
17559 :type '(set :greedy t
17560 (const effort)
17561 (const appt)
17562 (const stats)
17563 (const category))
17564 :version "26.1"
17565 :package-version '(Org . "8.3")
17566 :group 'org-agenda)
17568 ;;;; Files
17570 (defun org-save-all-org-buffers ()
17571 "Save all Org buffers without user confirmation."
17572 (interactive)
17573 (message "Saving all Org buffers...")
17574 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17575 (when (featurep 'org-id) (org-id-locations-save))
17576 (message "Saving all Org buffers... done"))
17578 (defun org-revert-all-org-buffers ()
17579 "Revert all Org buffers.
17580 Prompt for confirmation when there are unsaved changes.
17581 Be sure you know what you are doing before letting this function
17582 overwrite your changes.
17584 This function is useful in a setup where one tracks Org files
17585 with a version control system, to revert on one machine after pulling
17586 changes from another. I believe the procedure must be like this:
17588 1. M-x org-save-all-org-buffers
17589 2. Pull changes from the other machine, resolve conflicts
17590 3. M-x org-revert-all-org-buffers"
17591 (interactive)
17592 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17593 (user-error "Abort"))
17594 (save-excursion
17595 (save-window-excursion
17596 (dolist (b (buffer-list))
17597 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17598 (with-current-buffer b buffer-file-name))
17599 (pop-to-buffer-same-window b)
17600 (revert-buffer t 'no-confirm)))
17601 (when (and (featurep 'org-id) org-id-track-globally)
17602 (org-id-locations-load)))))
17604 ;;;; Agenda files
17606 ;;;###autoload
17607 (defun org-switchb (&optional arg)
17608 "Switch between Org buffers.
17610 With `\\[universal-argument]' prefix, restrict available buffers to files.
17612 With `\\[universal-argument] \\[universal-argument]' \
17613 prefix, restrict available buffers to agenda files."
17614 (interactive "P")
17615 (let ((blist (org-buffer-list
17616 (cond ((equal arg '(4)) 'files)
17617 ((equal arg '(16)) 'agenda)))))
17618 (pop-to-buffer-same-window
17619 (completing-read "Org buffer: "
17620 (mapcar #'list (mapcar #'buffer-name blist))
17621 nil t))))
17623 (defun org-buffer-list (&optional predicate exclude-tmp)
17624 "Return a list of Org buffers.
17625 PREDICATE can be `export', `files' or `agenda'.
17627 export restrict the list to Export buffers.
17628 files restrict the list to buffers visiting Org files.
17629 agenda restrict the list to buffers visiting agenda files.
17631 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17632 (let* ((bfn nil)
17633 (agenda-files (and (eq predicate 'agenda)
17634 (mapcar 'file-truename (org-agenda-files t))))
17635 (filter
17636 (cond
17637 ((eq predicate 'files)
17638 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17639 ((eq predicate 'export)
17640 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17641 ((eq predicate 'agenda)
17642 (lambda (b)
17643 (with-current-buffer b
17644 (and (derived-mode-p 'org-mode)
17645 (setq bfn (buffer-file-name b))
17646 (member (file-truename bfn) agenda-files)))))
17647 (t (lambda (b) (with-current-buffer b
17648 (or (derived-mode-p 'org-mode)
17649 (string-match "\\*Org .*Export"
17650 (buffer-name b)))))))))
17651 (delq nil
17652 (mapcar
17653 (lambda(b)
17654 (if (and (funcall filter b)
17655 (or (not exclude-tmp)
17656 (not (string-match "tmp" (buffer-name b)))))
17658 nil))
17659 (buffer-list)))))
17661 (defun org-agenda-files (&optional unrestricted archives)
17662 "Get the list of agenda files.
17663 Optional UNRESTRICTED means return the full list even if a restriction
17664 is currently in place.
17665 When ARCHIVES is t, include all archive files that are really being
17666 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17667 `org-agenda-archives-mode' is t."
17668 (let ((files
17669 (cond
17670 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17671 ((stringp org-agenda-files) (org-read-agenda-file-list))
17672 ((listp org-agenda-files) org-agenda-files)
17673 (t (error "Invalid value of `org-agenda-files'")))))
17674 (setq files (apply 'append
17675 (mapcar (lambda (f)
17676 (if (file-directory-p f)
17677 (directory-files
17678 f t org-agenda-file-regexp)
17679 (list f)))
17680 files)))
17681 (when org-agenda-skip-unavailable-files
17682 (setq files (delq nil
17683 (mapcar (function
17684 (lambda (file)
17685 (and (file-readable-p file) file)))
17686 files))))
17687 (when (or (eq archives t)
17688 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17689 (setq files (org-add-archive-files files)))
17690 files))
17692 (defun org-agenda-file-p (&optional file)
17693 "Return non-nil, if FILE is an agenda file.
17694 If FILE is omitted, use the file associated with the current
17695 buffer."
17696 (let ((fname (or file (buffer-file-name))))
17697 (and fname
17698 (member (file-truename fname)
17699 (mapcar #'file-truename (org-agenda-files t))))))
17701 (defun org-edit-agenda-file-list ()
17702 "Edit the list of agenda files.
17703 Depending on setup, this either uses customize to edit the variable
17704 `org-agenda-files', or it visits the file that is holding the list. In the
17705 latter case, the buffer is set up in a way that saving it automatically kills
17706 the buffer and restores the previous window configuration."
17707 (interactive)
17708 (if (stringp org-agenda-files)
17709 (let ((cw (current-window-configuration)))
17710 (find-file org-agenda-files)
17711 (setq-local org-window-configuration cw)
17712 (add-hook 'after-save-hook
17713 (lambda ()
17714 (set-window-configuration
17715 (prog1 org-window-configuration
17716 (kill-buffer (current-buffer))))
17717 (org-install-agenda-files-menu)
17718 (message "New agenda file list installed"))
17719 nil 'local)
17720 (message "%s" (substitute-command-keys
17721 "Edit list and finish with \\[save-buffer]")))
17722 (customize-variable 'org-agenda-files)))
17724 (defun org-store-new-agenda-file-list (list)
17725 "Set new value for the agenda file list and save it correctly."
17726 (if (stringp org-agenda-files)
17727 (let ((fe (org-read-agenda-file-list t)) b u)
17728 (while (setq b (find-buffer-visiting org-agenda-files))
17729 (kill-buffer b))
17730 (with-temp-file org-agenda-files
17731 (insert
17732 (mapconcat
17733 (lambda (f) ;; Keep un-expanded entries.
17734 (if (setq u (assoc f fe))
17735 (cdr u)
17737 list "\n")
17738 "\n")))
17739 (let ((org-mode-hook nil) (org-inhibit-startup t)
17740 (org-insert-mode-line-in-empty-file nil))
17741 (setq org-agenda-files list)
17742 (customize-save-variable 'org-agenda-files org-agenda-files))))
17744 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17745 "Read the list of agenda files from a file.
17746 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17747 filenames, used by `org-store-new-agenda-file-list' to write back
17748 un-expanded file names."
17749 (when (file-directory-p org-agenda-files)
17750 (error "`org-agenda-files' cannot be a single directory"))
17751 (when (stringp org-agenda-files)
17752 (with-temp-buffer
17753 (insert-file-contents org-agenda-files)
17754 (mapcar
17755 (lambda (f)
17756 (let ((e (expand-file-name (substitute-in-file-name f)
17757 org-directory)))
17758 (if pair-with-expansion
17759 (cons e f)
17760 e)))
17761 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17763 ;;;###autoload
17764 (defun org-cycle-agenda-files ()
17765 "Cycle through the files in `org-agenda-files'.
17766 If the current buffer visits an agenda file, find the next one in the list.
17767 If the current buffer does not, find the first agenda file."
17768 (interactive)
17769 (let* ((fs (or (org-agenda-files t)
17770 (user-error "No agenda files")))
17771 (files (copy-sequence fs))
17772 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17773 file)
17774 (when tcf
17775 (while (and (setq file (pop files))
17776 (not (equal (file-truename file) tcf)))))
17777 (find-file (car (or files fs)))
17778 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17780 (defun org-agenda-file-to-front (&optional to-end)
17781 "Move/add the current file to the top of the agenda file list.
17782 If the file is not present in the list, it is added to the front. If it is
17783 present, it is moved there. With optional argument TO-END, add/move to the
17784 end of the list."
17785 (interactive "P")
17786 (let ((org-agenda-skip-unavailable-files nil)
17787 (file-alist (mapcar (lambda (x)
17788 (cons (file-truename x) x))
17789 (org-agenda-files t)))
17790 (ctf (file-truename
17791 (or buffer-file-name
17792 (user-error "Please save the current buffer to a file"))))
17793 x had)
17794 (setq x (assoc ctf file-alist) had x)
17796 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17797 (if to-end
17798 (setq file-alist (append (delq x file-alist) (list x)))
17799 (setq file-alist (cons x (delq x file-alist))))
17800 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17801 (org-install-agenda-files-menu)
17802 (message "File %s to %s of agenda file list"
17803 (if had "moved" "added") (if to-end "end" "front"))))
17805 (defun org-remove-file (&optional file)
17806 "Remove current file from the list of files in variable `org-agenda-files'.
17807 These are the files which are being checked for agenda entries.
17808 Optional argument FILE means use this file instead of the current."
17809 (interactive)
17810 (let* ((org-agenda-skip-unavailable-files nil)
17811 (file (or file buffer-file-name
17812 (user-error "Current buffer does not visit a file")))
17813 (true-file (file-truename file))
17814 (afile (abbreviate-file-name file))
17815 (files (delq nil (mapcar
17816 (lambda (x)
17817 (unless (equal true-file
17818 (file-truename x))
17820 (org-agenda-files t)))))
17821 (if (not (= (length files) (length (org-agenda-files t))))
17822 (progn
17823 (org-store-new-agenda-file-list files)
17824 (org-install-agenda-files-menu)
17825 (message "Removed from Org Agenda list: %s" afile))
17826 (message "File was not in list: %s (not removed)" afile))))
17828 (defun org-file-menu-entry (file)
17829 (vector file (list 'find-file file) t))
17831 (defun org-check-agenda-file (file)
17832 "Make sure FILE exists. If not, ask user what to do."
17833 (unless (file-exists-p file)
17834 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17835 (abbreviate-file-name file))
17836 (let ((r (downcase (read-char-exclusive))))
17837 (cond
17838 ((equal r ?r)
17839 (org-remove-file file)
17840 (throw 'nextfile t))
17841 (t (user-error "Abort"))))))
17843 (defun org-get-agenda-file-buffer (file)
17844 "Get an agenda buffer visiting FILE.
17845 If the buffer needs to be created, add it to the list of buffers
17846 which might be released later."
17847 (let ((buf (org-find-base-buffer-visiting file)))
17848 (if buf
17849 buf ; just return it
17850 ;; Make a new buffer and remember it
17851 (setq buf (find-file-noselect file))
17852 (when buf (push buf org-agenda-new-buffers))
17853 buf)))
17855 (defun org-release-buffers (blist)
17856 "Release all buffers in list, asking the user for confirmation when needed.
17857 When a buffer is unmodified, it is just killed. When modified, it is saved
17858 \(if the user agrees) and then killed."
17859 (let (file)
17860 (dolist (buf blist)
17861 (setq file (buffer-file-name buf))
17862 (when (and (buffer-modified-p buf)
17863 file
17864 (y-or-n-p (format "Save file %s? " file)))
17865 (with-current-buffer buf (save-buffer)))
17866 (kill-buffer buf))))
17868 (defun org-agenda-prepare-buffers (files)
17869 "Create buffers for all agenda files, protect archived trees and comments."
17870 (interactive)
17871 (let ((pa '(:org-archived t))
17872 (pc '(:org-comment t))
17873 (pall '(:org-archived t :org-comment t))
17874 (inhibit-read-only t)
17875 (org-inhibit-startup org-agenda-inhibit-startup)
17876 (rea (org-make-tag-string (list org-archive-tag)))
17877 re pos)
17878 (setq org-tag-alist-for-agenda nil
17879 org-tag-groups-alist-for-agenda nil)
17880 (save-excursion
17881 (save-restriction
17882 (dolist (file files)
17883 (catch 'nextfile
17884 (if (bufferp file)
17885 (set-buffer file)
17886 (org-check-agenda-file file)
17887 (set-buffer (org-get-agenda-file-buffer file)))
17888 (widen)
17889 (org-set-regexps-and-options 'tags-only)
17890 (setq pos (point))
17891 (or (memq 'category org-agenda-ignore-properties)
17892 (org-refresh-category-properties))
17893 (or (memq 'stats org-agenda-ignore-properties)
17894 (org-refresh-stats-properties))
17895 (or (memq 'effort org-agenda-ignore-properties)
17896 (org-refresh-effort-properties))
17897 (or (memq 'appt org-agenda-ignore-properties)
17898 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17899 (setq org-todo-keywords-for-agenda
17900 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17901 (setq org-done-keywords-for-agenda
17902 (append org-done-keywords-for-agenda org-done-keywords))
17903 (setq org-todo-keyword-alist-for-agenda
17904 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17905 (setq org-tag-alist-for-agenda
17906 (org-tag-add-to-alist
17907 org-tag-alist-for-agenda
17908 org-current-tag-alist))
17909 ;; Merge current file's tag groups into global
17910 ;; `org-tag-groups-alist-for-agenda'.
17911 (when org-group-tags
17912 (dolist (alist org-tag-groups-alist)
17913 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17914 (if old
17915 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17916 (push alist org-tag-groups-alist-for-agenda)))))
17917 (org-with-silent-modifications
17918 (save-excursion
17919 (remove-text-properties (point-min) (point-max) pall)
17920 (when org-agenda-skip-archived-trees
17921 (goto-char (point-min))
17922 (while (re-search-forward rea nil t)
17923 (when (org-at-heading-p t)
17924 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17925 (goto-char (point-min))
17926 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17927 (while (re-search-forward re nil t)
17928 (when (save-match-data (org-in-commented-heading-p t))
17929 (add-text-properties
17930 (match-beginning 0) (org-end-of-subtree t) pc)))))
17931 (goto-char pos)))))
17932 (setq org-todo-keywords-for-agenda
17933 (org-uniquify org-todo-keywords-for-agenda))
17934 (setq org-todo-keyword-alist-for-agenda
17935 (org-uniquify org-todo-keyword-alist-for-agenda))))
17938 ;;;; CDLaTeX minor mode
17940 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17941 "Keymap for the minor `org-cdlatex-mode'.")
17943 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
17944 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
17945 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
17946 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
17947 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
17949 (defvar org-cdlatex-texmathp-advice-is-done nil
17950 "Flag remembering if we have applied the advice to texmathp already.")
17952 (define-minor-mode org-cdlatex-mode
17953 "Toggle the minor `org-cdlatex-mode'.
17954 This mode supports entering LaTeX environment and math in LaTeX fragments
17955 in Org mode.
17956 \\{org-cdlatex-mode-map}"
17957 nil " OCDL" nil
17958 (when org-cdlatex-mode
17959 (require 'cdlatex)
17960 (run-hooks 'cdlatex-mode-hook)
17961 (cdlatex-compute-tables))
17962 (unless org-cdlatex-texmathp-advice-is-done
17963 (setq org-cdlatex-texmathp-advice-is-done t)
17964 (defadvice texmathp (around org-math-always-on activate)
17965 "Always return t in Org buffers.
17966 This is because we want to insert math symbols without dollars even outside
17967 the LaTeX math segments. If Org mode thinks that point is actually inside
17968 an embedded LaTeX fragment, let `texmathp' do its job.
17969 `\\[org-cdlatex-mode-map]'"
17970 (interactive)
17971 (let (p)
17972 (cond
17973 ((not (derived-mode-p 'org-mode)) ad-do-it)
17974 ((eq this-command 'cdlatex-math-symbol)
17975 (setq ad-return-value t
17976 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17978 (let ((p (org-inside-LaTeX-fragment-p)))
17979 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17980 (setq ad-return-value t
17981 texmathp-why '("Org mode embedded math" . 0))
17982 (when p ad-do-it)))))))))
17984 (defun turn-on-org-cdlatex ()
17985 "Unconditionally turn on `org-cdlatex-mode'."
17986 (org-cdlatex-mode 1))
17988 (defun org-try-cdlatex-tab ()
17989 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17990 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17991 - inside a LaTeX fragment, or
17992 - after the first word in a line, where an abbreviation expansion could
17993 insert a LaTeX environment."
17994 (when org-cdlatex-mode
17995 (cond
17996 ;; Before any word on the line: No expansion possible.
17997 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17998 ;; Just after first word on the line: Expand it. Make sure it
17999 ;; cannot happen on headlines, though.
18000 ((save-excursion
18001 (skip-chars-backward "a-zA-Z0-9*")
18002 (skip-chars-backward " \t")
18003 (and (bolp) (not (org-at-heading-p))))
18004 (cdlatex-tab) t)
18005 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18007 (defun org-cdlatex-underscore-caret (&optional _arg)
18008 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18009 Revert to the normal definition outside of these fragments."
18010 (interactive "P")
18011 (if (org-inside-LaTeX-fragment-p)
18012 (call-interactively 'cdlatex-sub-superscript)
18013 (let (org-cdlatex-mode)
18014 (call-interactively (key-binding (vector last-input-event))))))
18016 (defun org-cdlatex-math-modify (&optional _arg)
18017 "Execute `cdlatex-math-modify' in LaTeX fragments.
18018 Revert to the normal definition outside of these fragments."
18019 (interactive "P")
18020 (if (org-inside-LaTeX-fragment-p)
18021 (call-interactively 'cdlatex-math-modify)
18022 (let (org-cdlatex-mode)
18023 (call-interactively (key-binding (vector last-input-event))))))
18025 (defun org-cdlatex-environment-indent (&optional environment item)
18026 "Execute `cdlatex-environment' and indent the inserted environment.
18028 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18030 The inserted environment is indented to current indentation
18031 unless point is at the beginning of the line, in which the
18032 environment remains unintended."
18033 (interactive)
18034 ;; cdlatex-environment always return nil. Therefore, capture output
18035 ;; first and determine if an environment was selected.
18036 (let* ((beg (point-marker))
18037 (end (copy-marker (point) t))
18038 (inserted (progn
18039 (ignore-errors (cdlatex-environment environment item))
18040 (< beg end)))
18041 ;; Figure out how many lines to move forward after the
18042 ;; environment has been inserted.
18043 (lines (when inserted
18044 (save-excursion
18045 (- (cl-loop while (< beg (point))
18046 with x = 0
18047 do (forward-line -1)
18048 (cl-incf x)
18049 finally return x)
18050 (if (progn (goto-char beg)
18051 (and (progn (skip-chars-forward " \t") (eolp))
18052 (progn (skip-chars-backward " \t") (bolp))))
18053 1 0)))))
18054 (env (org-trim (delete-and-extract-region beg end))))
18055 (when inserted
18056 ;; Get indentation of next line unless at column 0.
18057 (let ((ind (if (bolp) 0
18058 (save-excursion
18059 (org-return-indent)
18060 (prog1 (org-get-indentation)
18061 (when (progn (skip-chars-forward " \t") (eolp))
18062 (delete-region beg (point)))))))
18063 (bol (progn (skip-chars-backward " \t") (bolp))))
18064 ;; Insert a newline before environment unless at column zero
18065 ;; to "escape" the current line. Insert a newline if
18066 ;; something is one the same line as \end{ENVIRONMENT}.
18067 (insert
18068 (concat (unless bol "\n") env
18069 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18070 (unless (zerop ind)
18071 (save-excursion
18072 (goto-char beg)
18073 (while (< (point) end)
18074 (unless (eolp) (indent-line-to ind))
18075 (forward-line))))
18076 (goto-char beg)
18077 (forward-line lines)
18078 (indent-line-to ind)))
18079 (set-marker beg nil)
18080 (set-marker end nil)))
18083 ;;;; LaTeX fragments
18085 (defun org-inside-LaTeX-fragment-p ()
18086 "Test if point is inside a LaTeX fragment.
18087 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18088 sequence appearing also before point.
18089 Even though the matchers for math are configurable, this function assumes
18090 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18091 delimiters are skipped when they have been removed by customization.
18092 The return value is nil, or a cons cell with the delimiter and the
18093 position of this delimiter.
18095 This function does a reasonably good job, but can locally be fooled by
18096 for example currency specifications. For example it will assume being in
18097 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18098 fragments that are properly closed, but during editing, we have to live
18099 with the uncertainty caused by missing closing delimiters. This function
18100 looks only before point, not after."
18101 (catch 'exit
18102 (let ((pos (point))
18103 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18104 (lim (save-excursion (org-backward-paragraph) (point)))
18105 dd-on str (start 0) m re)
18106 (goto-char pos)
18107 (when dodollar
18108 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18109 re (nth 1 (assoc "$" org-latex-regexps)))
18110 (while (string-match re str start)
18111 (cond
18112 ((= (match-end 0) (length str))
18113 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18114 ((= (match-end 0) (- (length str) 5))
18115 (throw 'exit nil))
18116 (t (setq start (match-end 0))))))
18117 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18118 (goto-char pos)
18119 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18120 (and (match-beginning 2) (throw 'exit nil))
18121 ;; count $$
18122 (while (re-search-backward "\\$\\$" lim t)
18123 (setq dd-on (not dd-on)))
18124 (goto-char pos)
18125 (when dd-on (cons "$$" m))))))
18127 (defun org-inside-latex-macro-p ()
18128 "Is point inside a LaTeX macro or its arguments?"
18129 (save-match-data
18130 (org-in-regexp
18131 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18133 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18134 "Build an overlay between BEG and END using IMAGE file.
18135 Argument IMAGETYPE is the extension of the displayed image,
18136 as a string. It defaults to \"png\"."
18137 (let ((ov (make-overlay beg end))
18138 (imagetype (or (intern imagetype) 'png)))
18139 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18140 (overlay-put ov 'evaporate t)
18141 (overlay-put ov
18142 'modification-hooks
18143 (list (lambda (o _flag _beg _end &optional _l)
18144 (delete-overlay o))))
18145 (overlay-put ov
18146 'display
18147 (list 'image :type imagetype :file image :ascent 'center))))
18149 (defun org--list-latex-overlays (&optional beg end)
18150 "List all Org LaTeX overlays in current buffer.
18151 Limit to overlays between BEG and END when those are provided."
18152 (cl-remove-if-not
18153 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18154 (overlays-in (or beg (point-min)) (or end (point-max)))))
18156 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18157 "Remove all overlays with LaTeX fragment images in current buffer.
18158 When optional arguments BEG and END are non-nil, remove all
18159 overlays between them instead. Return a non-nil value when some
18160 overlays were removed, nil otherwise."
18161 (let ((overlays (org--list-latex-overlays beg end)))
18162 (mapc #'delete-overlay overlays)
18163 overlays))
18165 (defun org-toggle-latex-fragment (&optional arg)
18166 "Preview the LaTeX fragment at point, or all locally or globally.
18168 If the cursor is on a LaTeX fragment, create the image and overlay
18169 it over the source code, if there is none. Remove it otherwise.
18170 If there is no fragment at point, display all fragments in the
18171 current section.
18173 With prefix ARG, preview or clear image for all fragments in the
18174 current subtree or in the whole buffer when used before the first
18175 headline. With a prefix ARG `\\[universal-argument] \
18176 \\[universal-argument]' preview or clear images
18177 for all fragments in the buffer."
18178 (interactive "P")
18179 (when (display-graphic-p)
18180 (catch 'exit
18181 (save-excursion
18182 (let (beg end msg)
18183 (cond
18184 ((or (equal arg '(16))
18185 (and (equal arg '(4))
18186 (org-with-limited-levels (org-before-first-heading-p))))
18187 (if (org-remove-latex-fragment-image-overlays)
18188 (progn (message "LaTeX fragments images removed from buffer")
18189 (throw 'exit nil))
18190 (setq msg "Creating images for buffer...")))
18191 ((equal arg '(4))
18192 (org-with-limited-levels (org-back-to-heading t))
18193 (setq beg (point))
18194 (setq end (progn (org-end-of-subtree t) (point)))
18195 (if (org-remove-latex-fragment-image-overlays beg end)
18196 (progn
18197 (message "LaTeX fragment images removed from subtree")
18198 (throw 'exit nil))
18199 (setq msg "Creating images for subtree...")))
18200 ((let ((datum (org-element-context)))
18201 (when (memq (org-element-type datum)
18202 '(latex-environment latex-fragment))
18203 (setq beg (org-element-property :begin datum))
18204 (setq end (org-element-property :end datum))
18205 (if (org-remove-latex-fragment-image-overlays beg end)
18206 (progn (message "LaTeX fragment image removed")
18207 (throw 'exit nil))
18208 (setq msg "Creating image...")))))
18210 (org-with-limited-levels
18211 (setq beg (if (org-at-heading-p) (line-beginning-position)
18212 (outline-previous-heading)
18213 (point)))
18214 (setq end (progn (outline-next-heading) (point)))
18215 (if (org-remove-latex-fragment-image-overlays beg end)
18216 (progn
18217 (message "LaTeX fragment images removed from section")
18218 (throw 'exit nil))
18219 (setq msg "Creating images for section...")))))
18220 (let ((file (buffer-file-name (buffer-base-buffer))))
18221 (org-format-latex
18222 (concat org-preview-latex-image-directory "org-ltximg")
18223 beg end
18224 ;; Emacs cannot overlay images from remote hosts. Create
18225 ;; it in `temporary-file-directory' instead.
18226 (if (or (not file) (file-remote-p file))
18227 temporary-file-directory
18228 default-directory)
18229 'overlays msg 'forbuffer org-preview-latex-default-process))
18230 (message (concat msg "done")))))))
18232 (defun org-format-latex
18233 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18234 "Replace LaTeX fragments with links to an image.
18236 The function takes care of creating the replacement image.
18238 Only consider fragments between BEG and END when those are
18239 provided.
18241 When optional argument OVERLAYS is non-nil, display the image on
18242 top of the fragment instead of replacing it.
18244 PROCESSING-TYPE is the conversion method to use, as a symbol.
18246 Some of the options can be changed using the variable
18247 `org-format-latex-options', which see."
18248 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18249 (unless (eq processing-type 'verbatim)
18250 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18251 (cnt 0)
18252 checkdir-flag)
18253 (goto-char (or beg (point-min)))
18254 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18255 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18256 (overlay-recenter (or end (point-max))))
18257 (while (re-search-forward math-regexp end t)
18258 (unless (and overlays
18259 (eq (get-char-property (point) 'org-overlay-type)
18260 'org-latex-overlay))
18261 (let* ((context (org-element-context))
18262 (type (org-element-type context)))
18263 (when (memq type '(latex-environment latex-fragment))
18264 (let ((block-type (eq type 'latex-environment))
18265 (value (org-element-property :value context))
18266 (beg (org-element-property :begin context))
18267 (end (save-excursion
18268 (goto-char (org-element-property :end context))
18269 (skip-chars-backward " \r\t\n")
18270 (point))))
18271 (cond
18272 ((eq processing-type 'mathjax)
18273 ;; Prepare for MathJax processing.
18274 (if (not (string-match "\\`\\$\\$?" value))
18275 (goto-char end)
18276 (delete-region beg end)
18277 (if (string= (match-string 0 value) "$$")
18278 (insert "\\[" (substring value 2 -2) "\\]")
18279 (insert "\\(" (substring value 1 -1) "\\)"))))
18280 ((assq processing-type org-preview-latex-process-alist)
18281 ;; Process to an image.
18282 (cl-incf cnt)
18283 (goto-char beg)
18284 (let* ((processing-info
18285 (cdr (assq processing-type org-preview-latex-process-alist)))
18286 (face (face-at-point))
18287 ;; Get the colors from the face at point.
18289 (let ((color (plist-get org-format-latex-options
18290 :foreground)))
18291 (if (and forbuffer (eq color 'auto))
18292 (face-attribute face :foreground nil 'default)
18293 color)))
18295 (let ((color (plist-get org-format-latex-options
18296 :background)))
18297 (if (and forbuffer (eq color 'auto))
18298 (face-attribute face :background nil 'default)
18299 color)))
18300 (hash (sha1 (prin1-to-string
18301 (list org-format-latex-header
18302 org-latex-default-packages-alist
18303 org-latex-packages-alist
18304 org-format-latex-options
18305 forbuffer value fg bg))))
18306 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18307 (absprefix (expand-file-name prefix dir))
18308 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18309 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18310 (sep (and block-type "\n\n"))
18311 (link (concat sep "[[file:" linkfile "]]" sep))
18312 (options
18313 (org-combine-plists
18314 org-format-latex-options
18315 `(:foreground ,fg :background ,bg))))
18316 (when msg (message msg cnt))
18317 (unless checkdir-flag ; Ensure the directory exists.
18318 (setq checkdir-flag t)
18319 (let ((todir (file-name-directory absprefix)))
18320 (unless (file-directory-p todir)
18321 (make-directory todir t))))
18322 (unless (file-exists-p movefile)
18323 (org-create-formula-image
18324 value movefile options forbuffer processing-type))
18325 (if overlays
18326 (progn
18327 (dolist (o (overlays-in beg end))
18328 (when (eq (overlay-get o 'org-overlay-type)
18329 'org-latex-overlay)
18330 (delete-overlay o)))
18331 (org--format-latex-make-overlay beg end movefile imagetype)
18332 (goto-char end))
18333 (delete-region beg end)
18334 (insert
18335 (org-add-props link
18336 (list 'org-latex-src
18337 (replace-regexp-in-string "\"" "" value)
18338 'org-latex-src-embed-type
18339 (if block-type 'paragraph 'character)))))))
18340 ((eq processing-type 'mathml)
18341 ;; Process to MathML.
18342 (unless (org-format-latex-mathml-available-p)
18343 (user-error "LaTeX to MathML converter not configured"))
18344 (cl-incf cnt)
18345 (when msg (message msg cnt))
18346 (goto-char beg)
18347 (delete-region beg end)
18348 (insert (org-format-latex-as-mathml
18349 value block-type prefix dir)))
18351 (error "Unknown conversion process %s for LaTeX fragments"
18352 processing-type)))))))))))
18354 (defun org-create-math-formula (latex-frag &optional mathml-file)
18355 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18356 Use `org-latex-to-mathml-convert-command'. If the conversion is
18357 sucessful, return the portion between \"<math...> </math>\"
18358 elements otherwise return nil. When MATHML-FILE is specified,
18359 write the results in to that file. When invoked as an
18360 interactive command, prompt for LATEX-FRAG, with initial value
18361 set to the current active region and echo the results for user
18362 inspection."
18363 (interactive (list (let ((frag (when (org-region-active-p)
18364 (buffer-substring-no-properties
18365 (region-beginning) (region-end)))))
18366 (read-string "LaTeX Fragment: " frag nil frag))))
18367 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18368 (let* ((tmp-in-file
18369 (let ((file (file-relative-name
18370 (make-temp-name (expand-file-name "ltxmathml-in")))))
18371 (write-region latex-frag nil file)
18372 file))
18373 (tmp-out-file (file-relative-name
18374 (make-temp-name (expand-file-name "ltxmathml-out"))))
18375 (cmd (format-spec
18376 org-latex-to-mathml-convert-command
18377 `((?j . ,(and org-latex-to-mathml-jar-file
18378 (shell-quote-argument
18379 (expand-file-name
18380 org-latex-to-mathml-jar-file))))
18381 (?I . ,(shell-quote-argument tmp-in-file))
18382 (?i . ,latex-frag)
18383 (?o . ,(shell-quote-argument tmp-out-file)))))
18384 mathml shell-command-output)
18385 (when (called-interactively-p 'any)
18386 (unless (org-format-latex-mathml-available-p)
18387 (user-error "LaTeX to MathML converter not configured")))
18388 (message "Running %s" cmd)
18389 (setq shell-command-output (shell-command-to-string cmd))
18390 (setq mathml
18391 (when (file-readable-p tmp-out-file)
18392 (with-current-buffer (find-file-noselect tmp-out-file t)
18393 (goto-char (point-min))
18394 (when (re-search-forward
18395 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18396 (regexp-quote
18397 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18398 nil t)
18399 (prog1 (match-string 0) (kill-buffer))))))
18400 (cond
18401 (mathml
18402 (setq mathml
18403 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18404 (when mathml-file
18405 (write-region mathml nil mathml-file))
18406 (when (called-interactively-p 'any)
18407 (message mathml)))
18408 ((message "LaTeX to MathML conversion failed")
18409 (message shell-command-output)))
18410 (delete-file tmp-in-file)
18411 (when (file-exists-p tmp-out-file)
18412 (delete-file tmp-out-file))
18413 mathml))
18415 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18416 prefix &optional dir)
18417 "Use `org-create-math-formula' but check local cache first."
18418 (let* ((absprefix (expand-file-name prefix dir))
18419 (print-length nil) (print-level nil)
18420 (formula-id (concat
18421 "formula-"
18422 (sha1
18423 (prin1-to-string
18424 (list latex-frag
18425 org-latex-to-mathml-convert-command)))))
18426 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18427 (formula-cache-dir (file-name-directory formula-cache)))
18429 (unless (file-directory-p formula-cache-dir)
18430 (make-directory formula-cache-dir t))
18432 (unless (file-exists-p formula-cache)
18433 (org-create-math-formula latex-frag formula-cache))
18435 (if (file-exists-p formula-cache)
18436 ;; Successful conversion. Return the link to MathML file.
18437 (org-add-props
18438 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18439 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18440 'org-latex-src-embed-type (if latex-frag-type
18441 'paragraph 'character)))
18442 ;; Failed conversion. Return the LaTeX fragment verbatim
18443 latex-frag)))
18445 (defun org--get-display-dpi ()
18446 "Get the DPI of the display.
18447 The function assumes that the display has the same pixel width in
18448 the horizontal and vertical directions."
18449 (if (display-graphic-p)
18450 (round (/ (display-pixel-height)
18451 (/ (display-mm-height) 25.4)))
18452 (error "Attempt to calculate the dpi of a non-graphic display")))
18454 (defun org-create-formula-image
18455 (string tofile options buffer &optional processing-type)
18456 "Create an image from LaTeX source using external processes.
18458 The LaTeX STRING is saved to a temporary LaTeX file, then
18459 converted to an image file by process PROCESSING-TYPE defined in
18460 `org-preview-latex-process-alist'. A nil value defaults to
18461 `org-preview-latex-default-process'.
18463 The generated image file is eventually moved to TOFILE.
18465 The OPTIONS argument controls the size, foreground color and
18466 background color of the generated image.
18468 When BUFFER non-nil, this function is used for LaTeX previewing.
18469 Otherwise, it is used to deal with LaTeX snippets showed in
18470 a HTML file."
18471 (let* ((processing-type (or processing-type
18472 org-preview-latex-default-process))
18473 (processing-info
18474 (cdr (assq processing-type org-preview-latex-process-alist)))
18475 (programs (plist-get processing-info :programs))
18476 (error-message (or (plist-get processing-info :message) ""))
18477 (use-xcolor (plist-get processing-info :use-xcolor))
18478 (image-input-type (plist-get processing-info :image-input-type))
18479 (image-output-type (plist-get processing-info :image-output-type))
18480 (post-clean (or (plist-get processing-info :post-clean)
18481 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18482 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18483 (latex-header
18484 (or (plist-get processing-info :latex-header)
18485 (org-latex-make-preamble
18486 (org-export-get-environment (org-export-get-backend 'latex))
18487 org-format-latex-header
18488 'snippet)))
18489 (latex-compiler (plist-get processing-info :latex-compiler))
18490 (image-converter (plist-get processing-info :image-converter))
18491 (tmpdir temporary-file-directory)
18492 (texfilebase (make-temp-name
18493 (expand-file-name "orgtex" tmpdir)))
18494 (texfile (concat texfilebase ".tex"))
18495 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18496 '(1.0 . 1.0)))
18497 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18498 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18499 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18500 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18501 "Black"))
18502 (bg (or (plist-get options (if buffer :background :html-background))
18503 "Transparent"))
18504 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18505 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18506 (dolist (program programs)
18507 (org-check-external-command program error-message))
18508 (if use-xcolor
18509 (progn (if (eq fg 'default)
18510 (setq fg (org-latex-color :foreground))
18511 (setq fg (org-latex-color-format fg)))
18512 (if (eq bg 'default)
18513 (setq bg (org-latex-color :background))
18514 (setq bg (org-latex-color-format
18515 (if (string= bg "Transparent") "white" bg))))
18516 (with-temp-file texfile
18517 (insert latex-header)
18518 (insert "\n\\begin{document}\n"
18519 "\\definecolor{fg}{rgb}{" fg "}\n"
18520 "\\definecolor{bg}{rgb}{" bg "}\n"
18521 "\n\\pagecolor{bg}\n"
18522 "\n{\\color{fg}\n"
18523 string
18524 "\n}\n"
18525 "\n\\end{document}\n")))
18526 (if (eq fg 'default)
18527 (setq fg (org-dvipng-color :foreground))
18528 (unless (string= fg "Transparent")
18529 (setq fg (org-dvipng-color-format fg))))
18530 (if (eq bg 'default)
18531 (setq bg (org-dvipng-color :background))
18532 (unless (string= bg "Transparent")
18533 (setq bg (org-dvipng-color-format bg))))
18534 (with-temp-file texfile
18535 (insert latex-header)
18536 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18538 (let* ((err-msg (format "Please adjust `%s' part of \
18539 `org-preview-latex-process-alist'."
18540 processing-type))
18541 (image-input-file
18542 (org-compile-file
18543 texfile latex-compiler image-input-type err-msg log-buf))
18544 (image-output-file
18545 (org-compile-file
18546 image-input-file image-converter image-output-type err-msg log-buf
18547 `((?F . ,(shell-quote-argument fg))
18548 (?B . ,(shell-quote-argument bg))
18549 (?D . ,(shell-quote-argument (format "%s" dpi)))
18550 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18551 (copy-file image-output-file tofile 'replace)
18552 (dolist (e post-clean)
18553 (when (file-exists-p (concat texfilebase e))
18554 (delete-file (concat texfilebase e))))
18555 image-output-file)))
18557 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18558 "Fill a LaTeX header template TPL.
18559 In the template, the following place holders will be recognized:
18561 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18562 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18563 [PACKAGES] \\usepackage statements for PKG
18564 [NO-PACKAGES] do not include PKG
18565 [EXTRA] the string EXTRA
18566 [NO-EXTRA] do not include EXTRA
18568 For backward compatibility, if both the positive and the negative place
18569 holder is missing, the positive one (without the \"NO-\") will be
18570 assumed to be present at the end of the template.
18571 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18572 EXTRA is a string.
18573 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18574 (let (rpl (end ""))
18575 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18576 (setq rpl (if (or (match-end 1) (not def-pkg))
18577 "" (org-latex-packages-to-string def-pkg snippets-p t))
18578 tpl (replace-match rpl t t tpl))
18579 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18581 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18582 (setq rpl (if (or (match-end 1) (not pkg))
18583 "" (org-latex-packages-to-string pkg snippets-p t))
18584 tpl (replace-match rpl t t tpl))
18585 (when pkg (setq end
18586 (concat end "\n"
18587 (org-latex-packages-to-string pkg snippets-p)))))
18589 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18590 (setq rpl (if (or (match-end 1) (not extra))
18591 "" (concat extra "\n"))
18592 tpl (replace-match rpl t t tpl))
18593 (when (and extra (string-match "\\S-" extra))
18594 (setq end (concat end "\n" extra))))
18596 (if (string-match "\\S-" end)
18597 (concat tpl "\n" end)
18598 tpl)))
18600 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18601 "Turn an alist of packages into a string with the \\usepackage macros."
18602 (setq pkg (mapconcat (lambda(p)
18603 (cond
18604 ((stringp p) p)
18605 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18606 (format "%% Package %s omitted" (cadr p)))
18607 ((equal "" (car p))
18608 (format "\\usepackage{%s}" (cadr p)))
18610 (format "\\usepackage[%s]{%s}"
18611 (car p) (cadr p)))))
18613 "\n"))
18614 (if newline (concat pkg "\n") pkg))
18616 (defun org-dvipng-color (attr)
18617 "Return a RGB color specification for dvipng."
18618 (org-dvipng-color-format (face-attribute 'default attr nil)))
18620 (defun org-dvipng-color-format (color-name)
18621 "Convert COLOR-NAME to a RGB color value for dvipng."
18622 (apply #'format "rgb %s %s %s"
18623 (mapcar 'org-normalize-color
18624 (color-values color-name))))
18626 (defun org-latex-color (attr)
18627 "Return a RGB color for the LaTeX color package."
18628 (org-latex-color-format (face-attribute 'default attr nil)))
18630 (defun org-latex-color-format (color-name)
18631 "Convert COLOR-NAME to a RGB color value."
18632 (apply #'format "%s,%s,%s"
18633 (mapcar 'org-normalize-color
18634 (color-values color-name))))
18636 (defun org-normalize-color (value)
18637 "Return string to be used as color value for an RGB component."
18638 (format "%g" (/ value 65535.0)))
18641 ;; Image display
18643 (defvar-local org-inline-image-overlays nil)
18645 (defun org-toggle-inline-images (&optional include-linked)
18646 "Toggle the display of inline images.
18647 INCLUDE-LINKED is passed to `org-display-inline-images'."
18648 (interactive "P")
18649 (if org-inline-image-overlays
18650 (progn
18651 (org-remove-inline-images)
18652 (when (called-interactively-p 'interactive)
18653 (message "Inline image display turned off")))
18654 (org-display-inline-images include-linked)
18655 (when (called-interactively-p 'interactive)
18656 (message (if org-inline-image-overlays
18657 (format "%d images displayed inline"
18658 (length org-inline-image-overlays))
18659 "No images to display inline")))))
18661 (defun org-redisplay-inline-images ()
18662 "Refresh the display of inline images."
18663 (interactive)
18664 (if (not org-inline-image-overlays)
18665 (org-toggle-inline-images)
18666 (org-toggle-inline-images)
18667 (org-toggle-inline-images)))
18669 (defun org-display-inline-images (&optional include-linked refresh beg end)
18670 "Display inline images.
18672 An inline image is a link which follows either of these
18673 conventions:
18675 1. Its path is a file with an extension matching return value
18676 from `image-file-name-regexp' and it has no contents.
18678 2. Its description consists in a single link of the previous
18679 type.
18681 When optional argument INCLUDE-LINKED is non-nil, also links with
18682 a text description part will be inlined. This can be nice for
18683 a quick look at those images, but it does not reflect what
18684 exported files will look like.
18686 When optional argument REFRESH is non-nil, refresh existing
18687 images between BEG and END. This will create new image displays
18688 only if necessary. BEG and END default to the buffer
18689 boundaries."
18690 (interactive "P")
18691 (when (display-graphic-p)
18692 (unless refresh
18693 (org-remove-inline-images)
18694 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18695 (org-with-wide-buffer
18696 (goto-char (or beg (point-min)))
18697 (let* ((case-fold-search t)
18698 (file-extension-re (image-file-name-regexp))
18699 (link-abbrevs (mapcar #'car
18700 (append org-link-abbrev-alist-local
18701 org-link-abbrev-alist)))
18702 ;; Check absolute, relative file names and explicit
18703 ;; "file:" links. Also check link abbreviations since
18704 ;; some might expand to "file" links.
18705 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18706 (if (not link-abbrevs) ""
18707 (format "\\|\\(?:%s:\\)"
18708 (regexp-opt link-abbrevs))))))
18709 (while (re-search-forward file-types-re end t)
18710 (let ((link (save-match-data (org-element-context))))
18711 ;; Check if we're at an inline image, i.e., an image file
18712 ;; link without a description (unless INCLUDE-LINKED is
18713 ;; non-nil).
18714 (when (and (equal "file" (org-element-property :type link))
18715 (or include-linked
18716 (null (org-element-contents link)))
18717 (string-match-p file-extension-re
18718 (org-element-property :path link)))
18719 (let ((file (expand-file-name
18720 (org-link-unescape
18721 (org-element-property :path link)))))
18722 (when (file-exists-p file)
18723 (let ((width
18724 ;; Apply `org-image-actual-width' specifications.
18725 (cond
18726 ((not (image-type-available-p 'imagemagick)) nil)
18727 ((eq org-image-actual-width t) nil)
18728 ((listp org-image-actual-width)
18730 ;; First try to find a width among
18731 ;; attributes associated to the paragraph
18732 ;; containing link.
18733 (let ((paragraph
18734 (let ((e link))
18735 (while (and (setq e (org-element-property
18736 :parent e))
18737 (not (eq (org-element-type e)
18738 'paragraph))))
18739 e)))
18740 (when paragraph
18741 (save-excursion
18742 (goto-char (org-element-property :begin paragraph))
18743 (when
18744 (re-search-forward
18745 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18746 (org-element-property
18747 :post-affiliated paragraph)
18749 (string-to-number (match-string 1))))))
18750 ;; Otherwise, fall-back to provided number.
18751 (car org-image-actual-width)))
18752 ((numberp org-image-actual-width)
18753 org-image-actual-width)))
18754 (old (get-char-property-and-overlay
18755 (org-element-property :begin link)
18756 'org-image-overlay)))
18757 (if (and (car-safe old) refresh)
18758 (image-refresh (overlay-get (cdr old) 'display))
18759 (let ((image (create-image file
18760 (and width 'imagemagick)
18762 :width width)))
18763 (when image
18764 (let ((ov (make-overlay
18765 (org-element-property :begin link)
18766 (progn
18767 (goto-char
18768 (org-element-property :end link))
18769 (skip-chars-backward " \t")
18770 (point)))))
18771 (overlay-put ov 'display image)
18772 (overlay-put ov 'face 'default)
18773 (overlay-put ov 'org-image-overlay t)
18774 (overlay-put
18775 ov 'modification-hooks
18776 (list 'org-display-inline-remove-overlay))
18777 (push ov org-inline-image-overlays)))))))))))))))
18779 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18780 "Remove inline-display overlay if a corresponding region is modified."
18781 (let ((inhibit-modification-hooks t))
18782 (when (and ov after)
18783 (delete ov org-inline-image-overlays)
18784 (delete-overlay ov))))
18786 (defun org-remove-inline-images ()
18787 "Remove inline display of images."
18788 (interactive)
18789 (mapc #'delete-overlay org-inline-image-overlays)
18790 (setq org-inline-image-overlays nil))
18793 ;;; Key bindings
18795 (defun org-remap (map &rest commands)
18796 "In MAP, remap the functions given in COMMANDS.
18797 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18798 (let (new old)
18799 (while commands
18800 (setq old (pop commands) new (pop commands))
18801 (org-defkey map (vector 'remap old) new))))
18803 ;;;; Outline functions that can be remapped in Org
18804 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18805 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18806 (define-key org-mode-map [remap outline-forward-same-level]
18807 #'org-forward-heading-same-level)
18808 (define-key org-mode-map [remap outline-backward-same-level]
18809 #'org-backward-heading-same-level)
18810 (define-key org-mode-map [remap outline-show-branches]
18811 #'org-kill-note-or-show-branches)
18812 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18813 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18814 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18815 (define-key org-mode-map [remap outline-next-visible-heading]
18816 #'org-next-visible-heading)
18817 (define-key org-mode-map [remap outline-previous-visible-heading]
18818 #'org-previous-visible-heading)
18819 (define-key org-mode-map [remap show-children] #'org-show-children)
18821 ;;;; Make `C-c C-x' a prefix key
18822 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18824 ;;;; TAB key with modifiers
18825 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18826 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18827 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18828 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18829 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18831 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18832 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18833 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18835 ;;;; RET key with modifiers
18836 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18837 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18838 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18839 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18840 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18842 ;;;; Cursor keys with modifiers
18843 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18844 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18845 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18846 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18847 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18848 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18849 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18851 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18852 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18853 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18854 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18855 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18856 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18857 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18858 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18859 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18860 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18862 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18863 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18864 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18865 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18867 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18868 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18869 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18870 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18872 ;;;; Babel keys
18873 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18874 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18875 (define-key org-babel-map key def))
18877 ;;;; Extra keys for TTY access.
18879 ;; We only set them when really needed because otherwise the
18880 ;; menus don't show the simple keys
18882 (when (or org-use-extra-keys (not window-system))
18883 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18884 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
18885 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18886 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18887 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18888 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18889 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18890 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18891 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18892 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18893 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18894 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18895 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18896 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18897 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18898 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18899 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18900 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18901 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18902 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18903 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18905 ;;;; Narrow map
18906 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18907 (org-defkey narrow-map "b" #'org-narrow-to-block)
18908 (org-defkey narrow-map "e" #'org-narrow-to-element)
18910 ;;;; Remap usual Emacs bindings
18911 (org-remap org-mode-map
18912 'self-insert-command 'org-self-insert-command
18913 'delete-char 'org-delete-char
18914 'delete-backward-char 'org-delete-backward-char
18915 'kill-line 'org-kill-line
18916 'open-line 'org-open-line
18917 'yank 'org-yank
18918 'comment-dwim 'org-comment-dwim
18919 'move-beginning-of-line 'org-beginning-of-line
18920 'move-end-of-line 'org-end-of-line
18921 'forward-paragraph 'org-forward-paragraph
18922 'backward-paragraph 'org-backward-paragraph
18923 'backward-sentence 'org-backward-sentence
18924 'forward-sentence 'org-forward-sentence
18925 'fill-paragraph 'org-fill-paragraph
18926 'delete-indentation 'org-delete-indentation
18927 'transpose-words 'org-transpose-words)
18929 ;;;; All the other keys
18930 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18931 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18932 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18933 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18934 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18935 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18936 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18937 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18938 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18939 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18940 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18941 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18942 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18943 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18944 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18945 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18946 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18947 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18948 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
18949 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
18950 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
18951 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
18952 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
18953 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
18954 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
18955 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
18956 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
18957 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
18958 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
18959 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
18960 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
18961 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
18962 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
18963 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
18964 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
18965 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
18966 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
18967 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
18968 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
18969 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
18970 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
18971 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
18972 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
18973 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
18974 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
18975 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
18976 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
18977 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
18978 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
18979 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
18980 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
18981 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
18982 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
18983 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
18984 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
18985 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
18986 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
18987 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
18988 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
18989 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
18990 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
18991 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
18992 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
18993 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
18994 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
18995 (org-defkey org-mode-map (kbd "RET") #'org-return)
18996 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
18997 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
18998 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
18999 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19000 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19001 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19002 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19003 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19004 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19005 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19006 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19007 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19008 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19009 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19010 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19011 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19012 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19013 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19014 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19015 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19016 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19017 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19018 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19020 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19021 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19022 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19024 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19025 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19026 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19027 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19028 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19029 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19030 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19031 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19032 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19033 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19034 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19035 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19036 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19037 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19038 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19039 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19040 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19041 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19042 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19043 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19044 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19045 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19046 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19047 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19048 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19049 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19050 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19051 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19053 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19055 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19057 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19058 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19060 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19063 ;;; Speed commands
19065 (defconst org-speed-commands-default
19067 ("Outline Navigation")
19068 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19069 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19070 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19071 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19072 ("F" . org-next-block)
19073 ("B" . org-previous-block)
19074 ("u" . (org-speed-move-safe 'outline-up-heading))
19075 ("j" . org-goto)
19076 ("g" . (org-refile t))
19077 ("Outline Visibility")
19078 ("c" . org-cycle)
19079 ("C" . org-shifttab)
19080 (" " . org-display-outline-path)
19081 ("s" . org-narrow-to-subtree)
19082 ("=" . org-columns)
19083 ("Outline Structure Editing")
19084 ("U" . org-metaup)
19085 ("D" . org-metadown)
19086 ("r" . org-metaright)
19087 ("l" . org-metaleft)
19088 ("R" . org-shiftmetaright)
19089 ("L" . org-shiftmetaleft)
19090 ("i" . (progn (forward-char 1) (call-interactively
19091 'org-insert-heading-respect-content)))
19092 ("^" . org-sort)
19093 ("w" . org-refile)
19094 ("a" . org-archive-subtree-default-with-confirmation)
19095 ("@" . org-mark-subtree)
19096 ("#" . org-toggle-comment)
19097 ("Clock Commands")
19098 ("I" . org-clock-in)
19099 ("O" . org-clock-out)
19100 ("Meta Data Editing")
19101 ("t" . org-todo)
19102 ("," . (org-priority))
19103 ("0" . (org-priority ?\ ))
19104 ("1" . (org-priority ?A))
19105 ("2" . (org-priority ?B))
19106 ("3" . (org-priority ?C))
19107 (":" . org-set-tags-command)
19108 ("e" . org-set-effort)
19109 ("E" . org-inc-effort)
19110 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19111 (org-entry-put (point) "APPT_WARNTIME" m)))
19112 ("Agenda Views etc")
19113 ("v" . org-agenda)
19114 ("/" . org-sparse-tree)
19115 ("Misc")
19116 ("o" . org-open-at-point)
19117 ("?" . org-speed-command-help)
19118 ("<" . (org-agenda-set-restriction-lock 'subtree))
19119 (">" . (org-agenda-remove-restriction-lock))
19121 "The default speed commands.")
19123 (defun org-print-speed-command (e)
19124 (if (> (length (car e)) 1)
19125 (progn
19126 (princ "\n")
19127 (princ (car e))
19128 (princ "\n")
19129 (princ (make-string (length (car e)) ?-))
19130 (princ "\n"))
19131 (princ (car e))
19132 (princ " ")
19133 (if (symbolp (cdr e))
19134 (princ (symbol-name (cdr e)))
19135 (prin1 (cdr e)))
19136 (princ "\n")))
19138 (defun org-speed-command-help ()
19139 "Show the available speed commands."
19140 (interactive)
19141 (if (not org-use-speed-commands)
19142 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19143 (with-output-to-temp-buffer "*Help*"
19144 (princ "User-defined Speed commands\n===========================\n")
19145 (mapc #'org-print-speed-command org-speed-commands-user)
19146 (princ "\n")
19147 (princ "Built-in Speed commands\n=======================\n")
19148 (mapc #'org-print-speed-command org-speed-commands-default))
19149 (with-current-buffer "*Help*"
19150 (setq truncate-lines t))))
19152 (defun org-speed-move-safe (cmd)
19153 "Execute CMD, but make sure that the cursor always ends up in a headline.
19154 If not, return to the original position and throw an error."
19155 (interactive)
19156 (let ((pos (point)))
19157 (call-interactively cmd)
19158 (unless (and (bolp) (org-at-heading-p))
19159 (goto-char pos)
19160 (error "Boundary reached while executing %s" cmd))))
19162 (defvar org-self-insert-command-undo-counter 0)
19164 (defvar org-table-auto-blank-field) ; defined in org-table.el
19165 (defvar org-speed-command nil)
19167 (defun org-speed-command-activate (keys)
19168 "Hook for activating single-letter speed commands.
19169 `org-speed-commands-default' specifies a minimal command set.
19170 Use `org-speed-commands-user' for further customization."
19171 (when (or (and (bolp) (looking-at org-outline-regexp))
19172 (and (functionp org-use-speed-commands)
19173 (funcall org-use-speed-commands)))
19174 (cdr (assoc keys (append org-speed-commands-user
19175 org-speed-commands-default)))))
19177 (defun org-babel-speed-command-activate (keys)
19178 "Hook for activating single-letter code block commands."
19179 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19180 (cdr (assoc keys org-babel-key-bindings))))
19182 (defcustom org-speed-command-hook
19183 '(org-speed-command-activate org-babel-speed-command-activate)
19184 "Hook for activating speed commands at strategic locations.
19185 Hook functions are called in sequence until a valid handler is
19186 found.
19188 Each hook takes a single argument, a user-pressed command key
19189 which is also a `self-insert-command' from the global map.
19191 Within the hook, examine the cursor position and the command key
19192 and return nil or a valid handler as appropriate. Handler could
19193 be one of an interactive command, a function, or a form.
19195 Set `org-use-speed-commands' to non-nil value to enable this
19196 hook. The default setting is `org-speed-command-activate'."
19197 :group 'org-structure
19198 :version "24.1"
19199 :type 'hook)
19201 (defun org-self-insert-command (N)
19202 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19203 If the cursor is in a table looking at whitespace, the whitespace is
19204 overwritten, and the table is not marked as requiring realignment."
19205 (interactive "p")
19206 (org-check-before-invisible-edit 'insert)
19207 (cond
19208 ((and org-use-speed-commands
19209 (let ((kv (this-command-keys-vector)))
19210 (setq org-speed-command
19211 (run-hook-with-args-until-success
19212 'org-speed-command-hook
19213 (make-string 1 (aref kv (1- (length kv))))))))
19214 (cond
19215 ((commandp org-speed-command)
19216 (setq this-command org-speed-command)
19217 (call-interactively org-speed-command))
19218 ((functionp org-speed-command)
19219 (funcall org-speed-command))
19220 ((and org-speed-command (listp org-speed-command))
19221 (eval org-speed-command))
19222 (t (let (org-use-speed-commands)
19223 (call-interactively 'org-self-insert-command)))))
19224 ((and
19225 (= N 1)
19226 (not (org-region-active-p))
19227 (org-at-table-p)
19228 (progn
19229 ;; Check if we blank the field, and if that triggers align.
19230 (and (featurep 'org-table)
19231 org-table-auto-blank-field
19232 (memq last-command
19233 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19234 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19235 ;; Got extra space, this field does not determine
19236 ;; column width.
19237 (let (org-table-may-need-update) (org-table-blank-field))
19238 ;; No extra space, this field may determine column
19239 ;; width.
19240 (org-table-blank-field)))
19242 (looking-at "[^|\n]* |"))
19243 ;; There is room for insertion without re-aligning the table.
19244 (self-insert-command N)
19245 (org-table-with-shrunk-field
19246 (save-excursion
19247 (skip-chars-forward "^|")
19248 ;; Do not delete last space, which is
19249 ;; `org-table-separator-space', but the regular space before
19250 ;; it.
19251 (delete-region (- (point) 2) (1- (point))))))
19253 (setq org-table-may-need-update t)
19254 (self-insert-command N)
19255 (org-fix-tags-on-the-fly)
19256 (when org-self-insert-cluster-for-undo
19257 (if (not (eq last-command 'org-self-insert-command))
19258 (setq org-self-insert-command-undo-counter 1)
19259 (if (>= org-self-insert-command-undo-counter 20)
19260 (setq org-self-insert-command-undo-counter 1)
19261 (and (> org-self-insert-command-undo-counter 0)
19262 buffer-undo-list (listp buffer-undo-list)
19263 (not (cadr buffer-undo-list)) ; remove nil entry
19264 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19265 (setq org-self-insert-command-undo-counter
19266 (1+ org-self-insert-command-undo-counter))))))))
19268 (defun org-check-before-invisible-edit (kind)
19269 "Check is editing if kind KIND would be dangerous with invisible text around.
19270 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19271 ;; First, try to get out of here as quickly as possible, to reduce overhead
19272 (when (and org-catch-invisible-edits
19273 (or (not (boundp 'visible-mode)) (not visible-mode))
19274 (or (get-char-property (point) 'invisible)
19275 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19276 ;; OK, we need to take a closer look. Do not consider
19277 ;; invisibility obtained through text properties (e.g., link
19278 ;; fontification), as it cannot be toggled.
19279 (let* ((invisible-at-point
19280 (pcase (get-char-property-and-overlay (point) 'invisible)
19281 (`(,_ . ,(and (pred overlayp) o)) o)))
19282 ;; Assume that point cannot land in the middle of an
19283 ;; overlay, or between two overlays.
19284 (invisible-before-point
19285 (and (not invisible-at-point)
19286 (not (bobp))
19287 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19288 (`(,_ . ,(and (pred overlayp) o)) o))))
19289 (border-and-ok-direction
19291 ;; Check if we are acting predictably before invisible
19292 ;; text.
19293 (and invisible-at-point
19294 (memq kind '(insert delete-backward)))
19295 ;; Check if we are acting predictably after invisible text
19296 ;; This works not well, and I have turned it off. It seems
19297 ;; better to always show and stop after invisible text.
19298 ;; (and (not invisible-at-point) invisible-before-point
19299 ;; (memq kind '(insert delete)))
19301 (when (or invisible-at-point invisible-before-point)
19302 (when (eq org-catch-invisible-edits 'error)
19303 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19304 (if (and org-custom-properties-overlays
19305 (y-or-n-p "Display invisible properties in this buffer? "))
19306 (org-toggle-custom-properties-visibility)
19307 ;; Make the area visible
19308 (save-excursion
19309 (when invisible-before-point
19310 (goto-char
19311 (previous-single-char-property-change (point) 'invisible)))
19312 ;; Remove whatever overlay is currently making yet-to-be
19313 ;; edited text invisible. Also remove nested invisibility
19314 ;; related overlays.
19315 (delete-overlay (or invisible-at-point invisible-before-point))
19316 (let ((origin (if invisible-at-point (point) (1- (point)))))
19317 (while (pcase (get-char-property-and-overlay origin 'invisible)
19318 (`(,_ . ,(and (pred overlayp) o))
19319 (delete-overlay o)
19320 t)))))
19321 (cond
19322 ((eq org-catch-invisible-edits 'show)
19323 ;; That's it, we do the edit after showing
19324 (message
19325 "Unfolding invisible region around point before editing")
19326 (sit-for 1))
19327 ((and (eq org-catch-invisible-edits 'smart)
19328 border-and-ok-direction)
19329 (message "Unfolding invisible region around point before editing"))
19331 ;; Don't do the edit, make the user repeat it in full visibility
19332 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19334 (defun org-fix-tags-on-the-fly ()
19335 "Align tags in headline at point.
19336 Unlike to `org-align-tags', this function does nothing if point
19337 is not currently on a headline."
19338 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19339 (org-at-heading-p))
19340 (org-align-tags)))
19342 (defun org-delete-backward-char (N)
19343 "Like `delete-backward-char', insert whitespace at field end in tables.
19344 When deleting backwards, in tables this function will insert whitespace in
19345 front of the next \"|\" separator, to keep the table aligned. The table will
19346 still be marked for re-alignment if the field did fill the entire column,
19347 because, in this case the deletion might narrow the column."
19348 (interactive "p")
19349 (save-match-data
19350 (org-check-before-invisible-edit 'delete-backward)
19351 (if (and (= N 1)
19352 (not overwrite-mode)
19353 (not (org-region-active-p))
19354 (not (eq (char-before) ?|))
19355 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19356 (looking-at-p ".*?|")
19357 (org-at-table-p))
19358 (progn (forward-char -1) (org-delete-char 1))
19359 (backward-delete-char N)
19360 (org-fix-tags-on-the-fly))))
19362 (defun org-delete-char (N)
19363 "Like `delete-char', but insert whitespace at field end in tables.
19364 When deleting characters, in tables this function will insert whitespace in
19365 front of the next \"|\" separator, to keep the table aligned. The table will
19366 still be marked for re-alignment if the field did fill the entire column,
19367 because, in this case the deletion might narrow the column."
19368 (interactive "p")
19369 (save-match-data
19370 (org-check-before-invisible-edit 'delete)
19371 (cond
19372 ((or (/= N 1)
19373 (eq (char-after) ?|)
19374 (save-excursion (skip-chars-backward " \t") (bolp))
19375 (not (org-at-table-p)))
19376 (delete-char N)
19377 (org-fix-tags-on-the-fly))
19378 ((looking-at ".\\(.*?\\)|")
19379 (let* ((update? org-table-may-need-update)
19380 (noalign (looking-at-p ".*? |")))
19381 (delete-char 1)
19382 (org-table-with-shrunk-field
19383 (save-excursion
19384 ;; Last space is `org-table-separator-space', so insert
19385 ;; a regular one before it instead.
19386 (goto-char (- (match-end 0) 2))
19387 (insert " ")))
19388 ;; If there were two spaces at the end, this field does not
19389 ;; determine the width of the column.
19390 (when noalign (setq org-table-may-need-update update?))))
19392 (delete-char N)))))
19394 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19395 (put 'org-self-insert-command 'delete-selection
19396 (lambda ()
19397 (not (run-hook-with-args-until-success
19398 'self-insert-uses-region-functions))))
19399 (put 'orgtbl-self-insert-command 'delete-selection
19400 (lambda ()
19401 (not (run-hook-with-args-until-success
19402 'self-insert-uses-region-functions))))
19403 (put 'org-delete-char 'delete-selection 'supersede)
19404 (put 'org-delete-backward-char 'delete-selection 'supersede)
19405 (put 'org-yank 'delete-selection 'yank)
19407 ;; Make `flyspell-mode' delay after some commands
19408 (put 'org-self-insert-command 'flyspell-delayed t)
19409 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19410 (put 'org-delete-char 'flyspell-delayed t)
19411 (put 'org-delete-backward-char 'flyspell-delayed t)
19413 ;; Make pabbrev-mode expand after Org mode commands
19414 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19415 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19417 (defun org-transpose-words ()
19418 "Transpose words for Org.
19419 This uses the `org-mode-transpose-word-syntax-table' syntax
19420 table, which interprets characters in `org-emphasis-alist' as
19421 word constituents."
19422 (interactive)
19423 (with-syntax-table org-mode-transpose-word-syntax-table
19424 (call-interactively 'transpose-words)))
19426 (defvar org-ctrl-c-ctrl-c-hook nil
19427 "Hook for functions attaching themselves to `C-c C-c'.
19429 This can be used to add additional functionality to the C-c C-c
19430 key which executes context-dependent commands. This hook is run
19431 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19432 run after the last test.
19434 Each function will be called with no arguments. The function
19435 must check if the context is appropriate for it to act. If yes,
19436 it should do its thing and then return a non-nil value. If the
19437 context is wrong, just do nothing and return nil.")
19439 (defvar org-ctrl-c-ctrl-c-final-hook nil
19440 "Hook for functions attaching themselves to `C-c C-c'.
19442 This can be used to add additional functionality to the C-c C-c
19443 key which executes context-dependent commands. This hook is run
19444 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19445 before the first test.
19447 Each function will be called with no arguments. The function
19448 must check if the context is appropriate for it to act. If yes,
19449 it should do its thing and then return a non-nil value. If the
19450 context is wrong, just do nothing and return nil.")
19452 (defvar org-tab-first-hook nil
19453 "Hook for functions to attach themselves to TAB.
19454 See `org-ctrl-c-ctrl-c-hook' for more information.
19455 This hook runs as the first action when TAB is pressed, even before
19456 `org-cycle' messes around with the `outline-regexp' to cater for
19457 inline tasks and plain list item folding.
19458 If any function in this hook returns t, any other actions that
19459 would have been caused by TAB (such as table field motion or visibility
19460 cycling) will not occur.")
19462 (defvar org-tab-after-check-for-table-hook nil
19463 "Hook for functions to attach themselves to TAB.
19464 See `org-ctrl-c-ctrl-c-hook' for more information.
19465 This hook runs after it has been established that the cursor is not in a
19466 table, but before checking if the cursor is in a headline or if global cycling
19467 should be done.
19468 If any function in this hook returns t, not other actions like visibility
19469 cycling will be done.")
19471 (defvar org-tab-after-check-for-cycling-hook nil
19472 "Hook for functions to attach themselves to TAB.
19473 See `org-ctrl-c-ctrl-c-hook' for more information.
19474 This hook runs after it has been established that not table field motion and
19475 not visibility should be done because of current context. This is probably
19476 the place where a package like yasnippets can hook in.")
19478 (defvar org-tab-before-tab-emulation-hook nil
19479 "Hook for functions to attach themselves to TAB.
19480 See `org-ctrl-c-ctrl-c-hook' for more information.
19481 This hook runs after every other options for TAB have been exhausted, but
19482 before indentation and \t insertion takes place.")
19484 (defvar org-metaleft-hook nil
19485 "Hook for functions attaching themselves to `M-left'.
19486 See `org-ctrl-c-ctrl-c-hook' for more information.")
19487 (defvar org-metaright-hook nil
19488 "Hook for functions attaching themselves to `M-right'.
19489 See `org-ctrl-c-ctrl-c-hook' for more information.")
19490 (defvar org-metaup-hook nil
19491 "Hook for functions attaching themselves to `M-up'.
19492 See `org-ctrl-c-ctrl-c-hook' for more information.")
19493 (defvar org-metadown-hook nil
19494 "Hook for functions attaching themselves to `M-down'.
19495 See `org-ctrl-c-ctrl-c-hook' for more information.")
19496 (defvar org-shiftmetaleft-hook nil
19497 "Hook for functions attaching themselves to `M-S-left'.
19498 See `org-ctrl-c-ctrl-c-hook' for more information.")
19499 (defvar org-shiftmetaright-hook nil
19500 "Hook for functions attaching themselves to `M-S-right'.
19501 See `org-ctrl-c-ctrl-c-hook' for more information.")
19502 (defvar org-shiftmetaup-hook nil
19503 "Hook for functions attaching themselves to `M-S-up'.
19504 See `org-ctrl-c-ctrl-c-hook' for more information.")
19505 (defvar org-shiftmetadown-hook nil
19506 "Hook for functions attaching themselves to `M-S-down'.
19507 See `org-ctrl-c-ctrl-c-hook' for more information.")
19508 (defvar org-metareturn-hook nil
19509 "Hook for functions attaching themselves to `M-RET'.
19510 See `org-ctrl-c-ctrl-c-hook' for more information.")
19511 (defvar org-shiftup-hook nil
19512 "Hook for functions attaching themselves to `S-up'.
19513 See `org-ctrl-c-ctrl-c-hook' for more information.")
19514 (defvar org-shiftup-final-hook nil
19515 "Hook for functions attaching themselves to `S-up'.
19516 This one runs after all other options except shift-select have been excluded.
19517 See `org-ctrl-c-ctrl-c-hook' for more information.")
19518 (defvar org-shiftdown-hook nil
19519 "Hook for functions attaching themselves to `S-down'.
19520 See `org-ctrl-c-ctrl-c-hook' for more information.")
19521 (defvar org-shiftdown-final-hook nil
19522 "Hook for functions attaching themselves to `S-down'.
19523 This one runs after all other options except shift-select have been excluded.
19524 See `org-ctrl-c-ctrl-c-hook' for more information.")
19525 (defvar org-shiftleft-hook nil
19526 "Hook for functions attaching themselves to `S-left'.
19527 See `org-ctrl-c-ctrl-c-hook' for more information.")
19528 (defvar org-shiftleft-final-hook nil
19529 "Hook for functions attaching themselves to `S-left'.
19530 This one runs after all other options except shift-select have been excluded.
19531 See `org-ctrl-c-ctrl-c-hook' for more information.")
19532 (defvar org-shiftright-hook nil
19533 "Hook for functions attaching themselves to `S-right'.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.")
19535 (defvar org-shiftright-final-hook nil
19536 "Hook for functions attaching themselves to `S-right'.
19537 This one runs after all other options except shift-select have been excluded.
19538 See `org-ctrl-c-ctrl-c-hook' for more information.")
19540 (defun org-modifier-cursor-error ()
19541 "Throw an error, a modified cursor command was applied in wrong context."
19542 (user-error "This command is active in special context like tables, headlines or items"))
19544 (defun org-shiftselect-error ()
19545 "Throw an error because Shift-Cursor command was applied in wrong context."
19546 (if (and (boundp 'shift-select-mode) shift-select-mode)
19547 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19548 (user-error "This command works only in special context like headlines or timestamps")))
19550 (defun org-call-for-shift-select (cmd)
19551 (let ((this-command-keys-shift-translated t))
19552 (call-interactively cmd)))
19554 (defun org-shifttab (&optional arg)
19555 "Global visibility cycling or move to previous table field.
19556 Call `org-table-previous-field' within a table.
19557 When ARG is nil, cycle globally through visibility states.
19558 When ARG is a numeric prefix, show contents of this level."
19559 (interactive "P")
19560 (cond
19561 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19562 ((integerp arg)
19563 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19564 (message "Content view to level: %d" arg)
19565 (org-content (prefix-numeric-value arg2))
19566 (org-cycle-show-empty-lines t)
19567 (setq org-cycle-global-status 'overview)))
19568 (t (call-interactively 'org-global-cycle))))
19570 (defun org-shiftmetaleft ()
19571 "Promote subtree or delete table column.
19572 Calls `org-promote-subtree', `org-outdent-item-tree', or
19573 `org-table-delete-column', depending on context. See the
19574 individual commands for more information."
19575 (interactive)
19576 (cond
19577 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19578 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19579 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19580 ((if (not (org-region-active-p)) (org-at-item-p)
19581 (save-excursion (goto-char (region-beginning))
19582 (org-at-item-p)))
19583 (call-interactively 'org-outdent-item-tree))
19584 (t (org-modifier-cursor-error))))
19586 (defun org-shiftmetaright ()
19587 "Demote subtree or insert table column.
19588 Calls `org-demote-subtree', `org-indent-item-tree', or
19589 `org-table-insert-column', depending on context. See the
19590 individual commands for more information."
19591 (interactive)
19592 (cond
19593 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19594 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19595 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19596 ((if (not (org-region-active-p)) (org-at-item-p)
19597 (save-excursion (goto-char (region-beginning))
19598 (org-at-item-p)))
19599 (call-interactively 'org-indent-item-tree))
19600 (t (org-modifier-cursor-error))))
19602 (defun org-shiftmetaup (&optional _arg)
19603 "Drag the line at point up.
19604 In a table, kill the current row.
19605 On a clock timestamp, update the value of the timestamp like `S-<up>'
19606 but also adjust the previous clocked item in the clock history.
19607 Everywhere else, drag the line at point up."
19608 (interactive "P")
19609 (cond
19610 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19611 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19612 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19613 (call-interactively 'org-timestamp-up)))
19614 (t (call-interactively 'org-drag-line-backward))))
19616 (defun org-shiftmetadown (&optional _arg)
19617 "Drag the line at point down.
19618 In a table, insert an empty row at the current line.
19619 On a clock timestamp, update the value of the timestamp like `S-<down>'
19620 but also adjust the previous clocked item in the clock history.
19621 Everywhere else, drag the line at point down."
19622 (interactive "P")
19623 (cond
19624 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19625 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19626 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19627 (call-interactively 'org-timestamp-down)))
19628 (t (call-interactively 'org-drag-line-forward))))
19630 (defsubst org-hidden-tree-error ()
19631 (user-error
19632 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19634 (defun org-metaleft (&optional _arg)
19635 "Promote heading, list item at point or move table column left.
19637 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19638 depending on context. With no specific context, calls the Emacs
19639 default `backward-word'. See the individual commands for more
19640 information.
19642 This function runs the hook `org-metaleft-hook' as a first step,
19643 and returns at first non-nil value."
19644 (interactive "P")
19645 (cond
19646 ((run-hook-with-args-until-success 'org-metaleft-hook))
19647 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19648 ((org-with-limited-levels
19649 (or (org-at-heading-p)
19650 (and (org-region-active-p)
19651 (save-excursion
19652 (goto-char (region-beginning))
19653 (org-at-heading-p)))))
19654 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19655 (call-interactively 'org-do-promote))
19656 ;; At an inline task.
19657 ((org-at-heading-p)
19658 (call-interactively 'org-inlinetask-promote))
19659 ((or (org-at-item-p)
19660 (and (org-region-active-p)
19661 (save-excursion
19662 (goto-char (region-beginning))
19663 (org-at-item-p))))
19664 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19665 (call-interactively 'org-outdent-item))
19666 (t (call-interactively 'backward-word))))
19668 (defun org-metaright (&optional _arg)
19669 "Demote heading, list item at point or move table column right.
19671 In front of a drawer or a block keyword, indent it correctly.
19673 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19674 `org-indent-drawer' or `org-indent-block' depending on context.
19675 With no specific context, calls the Emacs default `forward-word'.
19676 See the individual commands for more information.
19678 This function runs the hook `org-metaright-hook' as a first step,
19679 and returns at first non-nil value."
19680 (interactive "P")
19681 (cond
19682 ((run-hook-with-args-until-success 'org-metaright-hook))
19683 ((org-at-table-p) (call-interactively 'org-table-move-column))
19684 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19685 ((org-at-block-p) (call-interactively 'org-indent-block))
19686 ((org-with-limited-levels
19687 (or (org-at-heading-p)
19688 (and (org-region-active-p)
19689 (save-excursion
19690 (goto-char (region-beginning))
19691 (org-at-heading-p)))))
19692 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19693 (call-interactively 'org-do-demote))
19694 ;; At an inline task.
19695 ((org-at-heading-p)
19696 (call-interactively 'org-inlinetask-demote))
19697 ((or (org-at-item-p)
19698 (and (org-region-active-p)
19699 (save-excursion
19700 (goto-char (region-beginning))
19701 (org-at-item-p))))
19702 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19703 (call-interactively 'org-indent-item))
19704 (t (call-interactively 'forward-word))))
19706 (defun org-check-for-hidden (what)
19707 "Check if there are hidden headlines/items in the current visual line.
19708 WHAT can be either `headlines' or `items'. If the current line is
19709 an outline or item heading and it has a folded subtree below it,
19710 this function returns t, nil otherwise."
19711 (let ((re (cond
19712 ((eq what 'headlines) org-outline-regexp-bol)
19713 ((eq what 'items) (org-item-beginning-re))
19714 (t (error "This should not happen"))))
19715 beg end)
19716 (save-excursion
19717 (catch 'exit
19718 (unless (org-region-active-p)
19719 (setq beg (point-at-bol))
19720 (beginning-of-line 2)
19721 (while (and (not (eobp)) ;; this is like `next-line'
19722 (get-char-property (1- (point)) 'invisible))
19723 (beginning-of-line 2))
19724 (setq end (point))
19725 (goto-char beg)
19726 (goto-char (point-at-eol))
19727 (setq end (max end (point)))
19728 (while (re-search-forward re end t)
19729 (when (get-char-property (match-beginning 0) 'invisible)
19730 (throw 'exit t))))
19731 nil))))
19733 (defun org-metaup (&optional _arg)
19734 "Move subtree up or move table row up.
19735 Calls `org-move-subtree-up' or `org-table-move-row' or
19736 `org-move-item-up', depending on context. See the individual commands
19737 for more information."
19738 (interactive "P")
19739 (cond
19740 ((run-hook-with-args-until-success 'org-metaup-hook))
19741 ((org-region-active-p)
19742 (let* ((a (min (region-beginning) (region-end)))
19743 (b (1- (max (region-beginning) (region-end))))
19744 (c (save-excursion (goto-char a)
19745 (move-beginning-of-line 0)))
19746 (d (save-excursion (goto-char a)
19747 (move-end-of-line 0) (point))))
19748 (transpose-regions a b c d)
19749 (goto-char c)))
19750 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19751 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19752 ((org-at-item-p) (call-interactively 'org-move-item-up))
19753 (t (org-drag-element-backward))))
19755 (defun org-metadown (&optional _arg)
19756 "Move subtree down or move table row down.
19757 Calls `org-move-subtree-down' or `org-table-move-row' or
19758 `org-move-item-down', depending on context. See the individual
19759 commands for more information."
19760 (interactive "P")
19761 (cond
19762 ((run-hook-with-args-until-success 'org-metadown-hook))
19763 ((org-region-active-p)
19764 (let* ((a (min (region-beginning) (region-end)))
19765 (b (max (region-beginning) (region-end)))
19766 (c (save-excursion (goto-char b)
19767 (move-beginning-of-line 1)))
19768 (d (save-excursion (goto-char b)
19769 (move-end-of-line 1) (1+ (point)))))
19770 (transpose-regions a b c d)
19771 (goto-char d)))
19772 ((org-at-table-p) (call-interactively 'org-table-move-row))
19773 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19774 ((org-at-item-p) (call-interactively 'org-move-item-down))
19775 (t (org-drag-element-forward))))
19777 (defun org-shiftup (&optional arg)
19778 "Increase item in timestamp or increase priority of current headline.
19779 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19780 depending on context. See the individual commands for more information."
19781 (interactive "P")
19782 (cond
19783 ((run-hook-with-args-until-success 'org-shiftup-hook))
19784 ((and org-support-shift-select (org-region-active-p))
19785 (org-call-for-shift-select 'previous-line))
19786 ((org-at-timestamp-p 'lax)
19787 (call-interactively (if org-edit-timestamp-down-means-later
19788 'org-timestamp-down 'org-timestamp-up)))
19789 ((and (not (eq org-support-shift-select 'always))
19790 org-enable-priority-commands
19791 (org-at-heading-p))
19792 (call-interactively 'org-priority-up))
19793 ((and (not org-support-shift-select) (org-at-item-p))
19794 (call-interactively 'org-previous-item))
19795 ((org-clocktable-try-shift 'up arg))
19796 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19797 (org-support-shift-select
19798 (org-call-for-shift-select 'previous-line))
19799 (t (org-shiftselect-error))))
19801 (defun org-shiftdown (&optional arg)
19802 "Decrease item in timestamp or decrease priority of current headline.
19803 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19804 depending on context. See the individual commands for more information."
19805 (interactive "P")
19806 (cond
19807 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19808 ((and org-support-shift-select (org-region-active-p))
19809 (org-call-for-shift-select 'next-line))
19810 ((org-at-timestamp-p 'lax)
19811 (call-interactively (if org-edit-timestamp-down-means-later
19812 'org-timestamp-up 'org-timestamp-down)))
19813 ((and (not (eq org-support-shift-select 'always))
19814 org-enable-priority-commands
19815 (org-at-heading-p))
19816 (call-interactively 'org-priority-down))
19817 ((and (not org-support-shift-select) (org-at-item-p))
19818 (call-interactively 'org-next-item))
19819 ((org-clocktable-try-shift 'down arg))
19820 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19821 (org-support-shift-select
19822 (org-call-for-shift-select 'next-line))
19823 (t (org-shiftselect-error))))
19825 (defun org-shiftright (&optional arg)
19826 "Cycle the thing at point or in the current line, depending on context.
19827 Depending on context, this does one of the following:
19829 - switch a timestamp at point one day into the future
19830 - on a headline, switch to the next TODO keyword.
19831 - on an item, switch entire list to the next bullet type
19832 - on a property line, switch to the next allowed value
19833 - on a clocktable definition line, move time block into the future"
19834 (interactive "P")
19835 (cond
19836 ((run-hook-with-args-until-success 'org-shiftright-hook))
19837 ((and org-support-shift-select (org-region-active-p))
19838 (org-call-for-shift-select 'forward-char))
19839 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19840 ((and (not (eq org-support-shift-select 'always))
19841 (org-at-heading-p))
19842 (let ((org-inhibit-logging
19843 (not org-treat-S-cursor-todo-selection-as-state-change))
19844 (org-inhibit-blocking
19845 (not org-treat-S-cursor-todo-selection-as-state-change)))
19846 (org-call-with-arg 'org-todo 'right)))
19847 ((or (and org-support-shift-select
19848 (not (eq org-support-shift-select 'always))
19849 (org-at-item-bullet-p))
19850 (and (not org-support-shift-select) (org-at-item-p)))
19851 (org-call-with-arg 'org-cycle-list-bullet nil))
19852 ((and (not (eq org-support-shift-select 'always))
19853 (org-at-property-p))
19854 (call-interactively 'org-property-next-allowed-value))
19855 ((org-clocktable-try-shift 'right arg))
19856 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19857 (org-support-shift-select
19858 (org-call-for-shift-select 'forward-char))
19859 (t (org-shiftselect-error))))
19861 (defun org-shiftleft (&optional arg)
19862 "Cycle the thing at point or in the current line, depending on context.
19863 Depending on context, this does one of the following:
19865 - switch a timestamp at point one day into the past
19866 - on a headline, switch to the previous TODO keyword.
19867 - on an item, switch entire list to the previous bullet type
19868 - on a property line, switch to the previous allowed value
19869 - on a clocktable definition line, move time block into the past"
19870 (interactive "P")
19871 (cond
19872 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19873 ((and org-support-shift-select (org-region-active-p))
19874 (org-call-for-shift-select 'backward-char))
19875 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19876 ((and (not (eq org-support-shift-select 'always))
19877 (org-at-heading-p))
19878 (let ((org-inhibit-logging
19879 (not org-treat-S-cursor-todo-selection-as-state-change))
19880 (org-inhibit-blocking
19881 (not org-treat-S-cursor-todo-selection-as-state-change)))
19882 (org-call-with-arg 'org-todo 'left)))
19883 ((or (and org-support-shift-select
19884 (not (eq org-support-shift-select 'always))
19885 (org-at-item-bullet-p))
19886 (and (not org-support-shift-select) (org-at-item-p)))
19887 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19888 ((and (not (eq org-support-shift-select 'always))
19889 (org-at-property-p))
19890 (call-interactively 'org-property-previous-allowed-value))
19891 ((org-clocktable-try-shift 'left arg))
19892 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19893 (org-support-shift-select
19894 (org-call-for-shift-select 'backward-char))
19895 (t (org-shiftselect-error))))
19897 (defun org-shiftcontrolright ()
19898 "Switch to next TODO set."
19899 (interactive)
19900 (cond
19901 ((and org-support-shift-select (org-region-active-p))
19902 (org-call-for-shift-select 'forward-word))
19903 ((and (not (eq org-support-shift-select 'always))
19904 (org-at-heading-p))
19905 (org-call-with-arg 'org-todo 'nextset))
19906 (org-support-shift-select
19907 (org-call-for-shift-select 'forward-word))
19908 (t (org-shiftselect-error))))
19910 (defun org-shiftcontrolleft ()
19911 "Switch to previous TODO set."
19912 (interactive)
19913 (cond
19914 ((and org-support-shift-select (org-region-active-p))
19915 (org-call-for-shift-select 'backward-word))
19916 ((and (not (eq org-support-shift-select 'always))
19917 (org-at-heading-p))
19918 (org-call-with-arg 'org-todo 'previousset))
19919 (org-support-shift-select
19920 (org-call-for-shift-select 'backward-word))
19921 (t (org-shiftselect-error))))
19923 (defun org-shiftcontrolup (&optional n)
19924 "Change timestamps synchronously up in CLOCK log lines.
19925 Optional argument N tells to change by that many units."
19926 (interactive "P")
19927 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19928 (let (org-support-shift-select)
19929 (org-clock-timestamps-up n))
19930 (user-error "Not at a clock log")))
19932 (defun org-shiftcontroldown (&optional n)
19933 "Change timestamps synchronously down in CLOCK log lines.
19934 Optional argument N tells to change by that many units."
19935 (interactive "P")
19936 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19937 (let (org-support-shift-select)
19938 (org-clock-timestamps-down n))
19939 (user-error "Not at a clock log")))
19941 (defun org-increase-number-at-point (&optional inc)
19942 "Increment the number at point.
19943 With an optional prefix numeric argument INC, increment using
19944 this numeric value."
19945 (interactive "p")
19946 (if (not (number-at-point))
19947 (user-error "Not on a number")
19948 (unless inc (setq inc 1))
19949 (let ((pos (point))
19950 (beg (skip-chars-backward "-+^/*0-9eE."))
19951 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
19952 (setq nap (buffer-substring-no-properties
19953 (+ pos beg) (+ pos beg end)))
19954 (delete-region (+ pos beg) (+ pos beg end))
19955 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
19956 (when (org-at-table-p)
19957 (org-table-align)
19958 (org-table-end-of-field 1))))
19960 (defun org-decrease-number-at-point (&optional inc)
19961 "Decrement the number at point.
19962 With an optional prefix numeric argument INC, decrement using
19963 this numeric value."
19964 (interactive "p")
19965 (org-increase-number-at-point (- (or inc 1))))
19967 (defun org-ctrl-c-ret ()
19968 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19969 (interactive)
19970 (cond
19971 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19972 (t (call-interactively 'org-insert-heading))))
19974 (defun org-find-visible ()
19975 (let ((s (point)))
19976 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19977 (get-char-property s 'invisible)))
19979 (defun org-find-invisible ()
19980 (let ((s (point)))
19981 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19982 (not (get-char-property s 'invisible))))
19985 (defun org-copy-visible (beg end)
19986 "Copy the visible parts of the region."
19987 (interactive "r")
19988 (let ((result ""))
19989 (while (/= beg end)
19990 (when (get-char-property beg 'invisible)
19991 (setq beg (next-single-char-property-change beg 'invisible nil end)))
19992 (let ((next (next-single-char-property-change beg 'invisible nil end)))
19993 (setq result (concat result (buffer-substring beg next)))
19994 (setq beg next)))
19995 (kill-new result)))
19997 (defun org-copy-special ()
19998 "Copy region in table or copy current subtree.
19999 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20000 context. See the individual commands for more information."
20001 (interactive)
20002 (call-interactively
20003 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20005 (defun org-cut-special ()
20006 "Cut region in table or cut current subtree.
20007 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20008 context. See the individual commands for more information."
20009 (interactive)
20010 (call-interactively
20011 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20013 (defun org-paste-special (arg)
20014 "Paste rectangular region into table, or past subtree relative to level.
20015 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20016 See the individual commands for more information."
20017 (interactive "P")
20018 (if (org-at-table-p)
20019 (org-table-paste-rectangle)
20020 (org-paste-subtree arg)))
20022 (defun org-edit-special (&optional arg)
20023 "Call a special editor for the element at point.
20024 When at a table, call the formula editor with `org-table-edit-formulas'.
20025 When in a source code block, call `org-edit-src-code'.
20026 When in a fixed-width region, call `org-edit-fixed-width-region'.
20027 When in an export block, call `org-edit-export-block'.
20028 When in a LaTeX environment, call `org-edit-latex-environment'.
20029 When at an #+INCLUDE keyword, visit the included file.
20030 When at a footnote reference, call `org-edit-footnote-reference'
20031 On a link, call `ffap' to visit the link at point.
20032 Otherwise, return a user error."
20033 (interactive "P")
20034 (let ((element (org-element-at-point)))
20035 (barf-if-buffer-read-only)
20036 (pcase (org-element-type element)
20037 (`src-block
20038 (if (not arg) (org-edit-src-code)
20039 (let* ((info (org-babel-get-src-block-info))
20040 (lang (nth 0 info))
20041 (params (nth 2 info))
20042 (session (cdr (assq :session params))))
20043 (if (not session) (org-edit-src-code)
20044 ;; At a src-block with a session and function called with
20045 ;; an ARG: switch to the buffer related to the inferior
20046 ;; process.
20047 (switch-to-buffer
20048 (funcall (intern (concat "org-babel-prep-session:" lang))
20049 session params))))))
20050 (`keyword
20051 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20052 (org-open-link-from-string
20053 (format "[[%s]]"
20054 (expand-file-name
20055 (let ((value (org-element-property :value element)))
20056 (cond ((org-file-url-p value)
20057 (user-error "The file is specified as a URL, cannot be edited"))
20058 ((not (org-string-nw-p value))
20059 (user-error "No file to edit"))
20060 ((string-match "\\`\"\\(.*?\\)\"" value)
20061 (match-string 1 value))
20062 ((string-match "\\`[^ \t\"]\\S-*" value)
20063 (match-string 0 value))
20064 (t (user-error "No valid file specified")))))))
20065 (user-error "No special environment to edit here")))
20066 (`table
20067 (if (eq (org-element-property :type element) 'table.el)
20068 (org-edit-table.el)
20069 (call-interactively 'org-table-edit-formulas)))
20070 ;; Only Org tables contain `table-row' type elements.
20071 (`table-row (call-interactively 'org-table-edit-formulas))
20072 (`example-block (org-edit-src-code))
20073 (`export-block (org-edit-export-block))
20074 (`fixed-width (org-edit-fixed-width-region))
20075 (`latex-environment (org-edit-latex-environment))
20077 ;; No notable element at point. Though, we may be at a link or
20078 ;; a footnote reference, which are objects. Thus, scan deeper.
20079 (let ((context (org-element-context element)))
20080 (pcase (org-element-type context)
20081 (`footnote-reference (org-edit-footnote-reference))
20082 (`inline-src-block (org-edit-inline-src-code))
20083 (`link (call-interactively #'ffap))
20084 (_ (user-error "No special environment to edit here"))))))))
20086 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20087 (defun org-ctrl-c-ctrl-c (&optional arg)
20088 "Set tags in headline, or update according to changed information at point.
20090 This command does many different things, depending on context:
20092 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20093 this is what we do.
20095 - If the cursor is on a statistics cookie, update it.
20097 - If the cursor is in a headline, prompt for tags and insert them
20098 into the current line, aligned to `org-tags-column'. When called
20099 with prefix arg, realign all tags in the current buffer.
20101 - If the cursor is in one of the special #+KEYWORD lines, this
20102 triggers scanning the buffer for these lines and updating the
20103 information.
20105 - If the cursor is inside a table, realign the table. This command
20106 works even if the automatic table editor has been turned off.
20108 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20109 the entire table.
20111 - If the cursor is at a footnote reference or definition, jump to
20112 the corresponding definition or references, respectively.
20114 - If the cursor is a the beginning of a dynamic block, update it.
20116 - If the current buffer is a capture buffer, close note and file it.
20118 - If the cursor is on a <<<target>>>, update radio targets and
20119 corresponding links in this buffer.
20121 - If the cursor is on a numbered item in a plain list, renumber the
20122 ordered list.
20124 - If the cursor is on a checkbox, toggle it.
20126 - If the cursor is on a code block, evaluate it. The variable
20127 `org-confirm-babel-evaluate' can be used to control prompting
20128 before code block evaluation, by default every code block
20129 evaluation requires confirmation. Code block evaluation can be
20130 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20131 (interactive "P")
20132 (cond
20133 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20134 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20135 (org-remove-occur-highlights)
20136 (message "Temporary highlights/overlays removed from current buffer"))
20137 ((and (local-variable-p 'org-finish-function)
20138 (fboundp org-finish-function))
20139 (funcall org-finish-function))
20140 ((org-babel-hash-at-point))
20141 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20143 (let* ((context
20144 (org-element-lineage
20145 (org-element-context)
20146 ;; Limit to supported contexts.
20147 '(babel-call clock dynamic-block footnote-definition
20148 footnote-reference inline-babel-call inline-src-block
20149 inlinetask item keyword node-property paragraph
20150 plain-list planning property-drawer radio-target
20151 src-block statistics-cookie table table-cell table-row
20152 timestamp)
20154 (type (org-element-type context)))
20155 ;; For convenience: at the first line of a paragraph on the same
20156 ;; line as an item, apply function on that item instead.
20157 (when (eq type 'paragraph)
20158 (let ((parent (org-element-property :parent context)))
20159 (when (and (eq (org-element-type parent) 'item)
20160 (= (line-beginning-position)
20161 (org-element-property :begin parent)))
20162 (setq context parent)
20163 (setq type 'item))))
20164 ;; Act according to type of element or object at point.
20166 ;; Do nothing on a blank line, except if it is contained in
20167 ;; a src block. Hence, we first check if point is in such
20168 ;; a block and then if it is at a blank line.
20169 (pcase type
20170 ((or `inline-src-block `src-block)
20171 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20172 (org-babel-eval-wipe-error-buffer)
20173 (org-babel-execute-src-block
20174 current-prefix-arg (org-babel-get-src-block-info nil context))))
20175 ((guard (org-match-line "[ \t]*$"))
20176 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20177 (user-error
20178 (substitute-command-keys
20179 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20180 ((or `babel-call `inline-babel-call)
20181 (let ((info (org-babel-lob-get-info context)))
20182 (when info (org-babel-execute-src-block nil info))))
20183 (`clock (org-clock-update-time-maybe))
20184 (`dynamic-block
20185 (save-excursion
20186 (goto-char (org-element-property :post-affiliated context))
20187 (org-update-dblock)))
20188 (`footnote-definition
20189 (goto-char (org-element-property :post-affiliated context))
20190 (call-interactively 'org-footnote-action))
20191 (`footnote-reference (call-interactively #'org-footnote-action))
20192 ((or `headline `inlinetask)
20193 (save-excursion (goto-char (org-element-property :begin context))
20194 (call-interactively #'org-set-tags-command)))
20195 (`item
20196 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20197 ;; unconditionally, whereas `C-u' will toggle its presence.
20198 ;; Without a universal argument, if the item has a checkbox,
20199 ;; toggle it. Otherwise repair the list.
20200 (let* ((box (org-element-property :checkbox context))
20201 (struct (org-element-property :structure context))
20202 (old-struct (copy-tree struct))
20203 (parents (org-list-parents-alist struct))
20204 (prevs (org-list-prevs-alist struct))
20205 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20206 (org-list-set-checkbox
20207 (org-element-property :begin context) struct
20208 (cond ((equal arg '(16)) "[-]")
20209 ((and (not box) (equal arg '(4))) "[ ]")
20210 ((or (not box) (equal arg '(4))) nil)
20211 ((eq box 'on) "[ ]")
20212 (t "[X]")))
20213 ;; Mimic `org-list-write-struct' but with grabbing a return
20214 ;; value from `org-list-struct-fix-box'.
20215 (org-list-struct-fix-ind struct parents 2)
20216 (org-list-struct-fix-item-end struct)
20217 (org-list-struct-fix-bul struct prevs)
20218 (org-list-struct-fix-ind struct parents)
20219 (let ((block-item
20220 (org-list-struct-fix-box struct parents prevs orderedp)))
20221 (if (and box (equal struct old-struct))
20222 (if (equal arg '(16))
20223 (message "Checkboxes already reset")
20224 (user-error "Cannot toggle this checkbox: %s"
20225 (if (eq box 'on)
20226 "all subitems checked"
20227 "unchecked subitems")))
20228 (org-list-struct-apply-struct struct old-struct)
20229 (org-update-checkbox-count-maybe))
20230 (when block-item
20231 (message "Checkboxes were removed due to empty box at line %d"
20232 (org-current-line block-item))))))
20233 (`keyword
20234 (let ((org-inhibit-startup-visibility-stuff t)
20235 (org-startup-align-all-tables nil))
20236 (when (boundp 'org-table-coordinate-overlays)
20237 (mapc #'delete-overlay org-table-coordinate-overlays)
20238 (setq org-table-coordinate-overlays nil))
20239 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20240 (message "Local setup has been refreshed"))
20241 (`plain-list
20242 ;; At a plain list, with a double C-u argument, set
20243 ;; checkboxes of each item to "[-]", whereas a single one
20244 ;; will toggle their presence according to the state of the
20245 ;; first item in the list. Without an argument, repair the
20246 ;; list.
20247 (let* ((begin (org-element-property :contents-begin context))
20248 (struct (org-element-property :structure context))
20249 (old-struct (copy-tree struct))
20250 (first-box (save-excursion
20251 (goto-char begin)
20252 (looking-at org-list-full-item-re)
20253 (match-string-no-properties 3)))
20254 (new-box (cond ((equal arg '(16)) "[-]")
20255 ((equal arg '(4)) (unless first-box "[ ]"))
20256 ((equal first-box "[X]") "[ ]")
20257 (t "[X]"))))
20258 (cond
20259 (arg
20260 (dolist (pos
20261 (org-list-get-all-items
20262 begin struct (org-list-prevs-alist struct)))
20263 (org-list-set-checkbox pos struct new-box)))
20264 ((and first-box (eq (point) begin))
20265 ;; For convenience, when point is at bol on the first
20266 ;; item of the list and no argument is provided, simply
20267 ;; toggle checkbox of that item, if any.
20268 (org-list-set-checkbox begin struct new-box)))
20269 (org-list-write-struct
20270 struct (org-list-parents-alist struct) old-struct)
20271 (org-update-checkbox-count-maybe)))
20272 ((or `property-drawer `node-property)
20273 (call-interactively #'org-property-action))
20274 (`radio-target
20275 (call-interactively #'org-update-radio-target-regexp))
20276 (`statistics-cookie
20277 (call-interactively #'org-update-statistics-cookies))
20278 ((or `table `table-cell `table-row)
20279 ;; At a table, recalculate every field and align it. Also
20280 ;; send the table if necessary. If the table has
20281 ;; a `table.el' type, just give up. At a table row or cell,
20282 ;; maybe recalculate line but always align table.
20283 (if (eq (org-element-property :type context) 'table.el)
20284 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20285 Use `\\[org-edit-special]' to edit table.el tables"))
20286 (if (or (eq type 'table)
20287 ;; Check if point is at a TBLFM line.
20288 (and (eq type 'table-row)
20289 (= (point) (org-element-property :end context))))
20290 (save-excursion
20291 (if (org-at-TBLFM-p)
20292 (progn (require 'org-table)
20293 (org-table-calc-current-TBLFM))
20294 (goto-char (org-element-property :contents-begin context))
20295 (org-call-with-arg 'org-table-recalculate (or arg t))
20296 (orgtbl-send-table 'maybe)))
20297 (org-table-maybe-eval-formula)
20298 (cond (arg (call-interactively #'org-table-recalculate))
20299 ((org-table-maybe-recalculate-line))
20300 (t (org-table-align))))))
20301 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20302 (org-timestamp-change 0 'day))
20303 ((and `nil (guard (org-at-heading-p)))
20304 ;; When point is on an unsupported object type, we can miss
20305 ;; the fact that it also is at a heading. Handle it here.
20306 (call-interactively #'org-set-tags-command))
20307 ((guard
20308 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20310 (user-error
20311 (substitute-command-keys
20312 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20314 (defun org-mode-restart ()
20315 (interactive)
20316 (let ((indent-status (bound-and-true-p org-indent-mode)))
20317 (funcall major-mode)
20318 (hack-local-variables)
20319 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20320 (org-indent-mode -1))
20321 (org-reset-file-cache))
20322 (message "%s restarted" major-mode))
20324 (defun org-kill-note-or-show-branches ()
20325 "Abort storing current note, or call `outline-show-branches'."
20326 (interactive)
20327 (if (not org-finish-function)
20328 (save-excursion
20329 (save-restriction
20330 (org-narrow-to-subtree)
20331 (org-flag-subtree t)
20332 (call-interactively 'outline-show-branches)
20333 (org-hide-archived-subtrees (point-min) (point-max))))
20334 (let ((org-note-abort t))
20335 (funcall org-finish-function))))
20337 (defun org-delete-indentation (&optional arg)
20338 "Join current line to previous and fix whitespace at join.
20340 If previous line is a headline add to headline title. Otherwise
20341 the function calls `delete-indentation'.
20343 With a non-nil optional argument, join it to the following one."
20344 (interactive "*P")
20345 (if (save-excursion
20346 (beginning-of-line (if arg 1 0))
20347 (let ((case-fold-search nil))
20348 (looking-at org-complex-heading-regexp)))
20349 ;; At headline.
20350 (let ((tags-column (when (match-beginning 5)
20351 (save-excursion (goto-char (match-beginning 5))
20352 (current-column))))
20353 (string (concat " " (progn (when arg (forward-line 1))
20354 (org-trim (delete-and-extract-region
20355 (line-beginning-position)
20356 (line-end-position)))))))
20357 (unless (bobp) (delete-region (point) (1- (point))))
20358 (goto-char (or (match-end 4)
20359 (match-beginning 5)
20360 (match-end 0)))
20361 (skip-chars-backward " \t")
20362 (save-excursion (insert string))
20363 ;; Adjust alignment of tags.
20364 (cond
20365 ((not tags-column)) ;no tags
20366 (org-auto-align-tags (org-align-tags))
20367 (t (org--align-tags-here tags-column)))) ;preserve tags column
20368 (delete-indentation arg)))
20370 (defun org-open-line (n)
20371 "Insert a new row in tables, call `open-line' elsewhere.
20372 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20373 As a special case, when a document starts with a table, allow to
20374 call `open-line' on the very first character."
20375 (interactive "*p")
20376 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20377 (org-table-insert-row)
20378 (open-line n)))
20380 (defun org-return (&optional indent)
20381 "Goto next table row or insert a newline.
20383 Calls `org-table-next-row' or `newline', depending on context.
20385 When optional INDENT argument is non-nil, call
20386 `newline-and-indent' instead of `newline'.
20388 When `org-return-follows-link' is non-nil and point is on
20389 a timestamp or a link, call `org-open-at-point'. However, it
20390 will not happen if point is in a table or on a \"dead\"
20391 object (e.g., within a comment). In these case, you need to use
20392 `org-open-at-point' directly."
20393 (interactive)
20394 (let ((context (if org-return-follows-link (org-element-context)
20395 (org-element-at-point))))
20396 (cond
20397 ;; In a table, call `org-table-next-row'. However, before first
20398 ;; column or after last one, split the table.
20399 ((or (and (eq (org-element-type context) 'table)
20400 (>= (point) (org-element-property :contents-begin context))
20401 (< (point) (org-element-property :contents-end context)))
20402 (org-element-lineage context '(table-row table-cell) t))
20403 (if (or (looking-at-p "[ \t]*$")
20404 (save-excursion (skip-chars-backward " \t") (bolp)))
20405 (insert "\n")
20406 (org-table-justify-field-maybe)
20407 (call-interactively #'org-table-next-row)))
20408 ;; On a link or a timestamp, call `org-open-at-point' if
20409 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20410 ;; locations, e.g., in a comment, as `org-open-at-point'.
20411 ((and org-return-follows-link
20412 (or (and (eq 'link (org-element-type context))
20413 ;; Ensure point is not on the white spaces after
20414 ;; the link.
20415 (let ((origin (point)))
20416 (org-with-point-at (org-element-property :end context)
20417 (skip-chars-backward " \t")
20418 (> (point) origin))))
20419 (org-in-regexp org-ts-regexp-both nil t)
20420 (org-in-regexp org-tsr-regexp-both nil t)
20421 (org-in-regexp org-any-link-re nil t)))
20422 (call-interactively #'org-open-at-point))
20423 ;; Insert newline in heading, but preserve tags.
20424 ((and (not (bolp))
20425 (save-excursion (beginning-of-line)
20426 (let ((case-fold-search nil))
20427 (looking-at org-complex-heading-regexp))))
20428 ;; At headline. Split line. However, if point is on keyword,
20429 ;; priority cookie or tags, do not break any of them: add
20430 ;; a newline after the headline instead.
20431 (let ((tags-column (and (match-beginning 5)
20432 (save-excursion (goto-char (match-beginning 5))
20433 (current-column))))
20434 (string
20435 (when (and (match-end 4) (org-point-in-group (point) 4))
20436 (delete-and-extract-region (point) (match-end 4)))))
20437 ;; Adjust tag alignment.
20438 (cond
20439 ((not (and tags-column string)))
20440 (org-auto-align-tags (org-align-tags))
20441 (t (org--align-tags-here tags-column))) ;preserve tags column
20442 (end-of-line)
20443 (org-show-entry)
20444 (if indent (newline-and-indent) (newline))
20445 (when string (save-excursion (insert (org-trim string))))))
20446 ;; In a list, make sure indenting keeps trailing text within.
20447 ((and indent
20448 (not (eolp))
20449 (org-element-lineage context '(item)))
20450 (let ((trailing-data
20451 (delete-and-extract-region (point) (line-end-position))))
20452 (newline-and-indent)
20453 (save-excursion (insert trailing-data))))
20455 ;; Do not auto-fill when point is in an Org property drawer.
20456 (let ((auto-fill-function (and (not (org-at-property-p))
20457 auto-fill-function)))
20458 (if indent
20459 (newline-and-indent)
20460 (newline)))))))
20462 (defun org-return-indent ()
20463 "Goto next table row or insert a newline and indent.
20464 Calls `org-table-next-row' or `newline-and-indent', depending on
20465 context. See the individual commands for more information."
20466 (interactive)
20467 (org-return t))
20469 (defun org-ctrl-c-tab (&optional _arg)
20470 "Toggle columns width in a table, or show children.
20471 Call `org-table-toggle-column-width' if point is in a table.
20472 Otherwise, call `org-show-children'."
20473 (interactive "p")
20474 (call-interactively
20475 (if (org-at-table-p) #'org-table-toggle-column-width
20476 #'org-show-children)))
20478 (defun org-ctrl-c-star ()
20479 "Compute table, or change heading status of lines.
20480 Calls `org-table-recalculate' or `org-toggle-heading',
20481 depending on context."
20482 (interactive)
20483 (cond
20484 ((org-at-table-p)
20485 (call-interactively 'org-table-recalculate))
20487 ;; Convert all lines in region to list items
20488 (call-interactively 'org-toggle-heading))))
20490 (defun org-ctrl-c-minus ()
20491 "Insert separator line in table or modify bullet status of line.
20492 Also turns a plain line or a region of lines into list items.
20493 Calls `org-table-insert-hline', `org-toggle-item', or
20494 `org-cycle-list-bullet', depending on context."
20495 (interactive)
20496 (cond
20497 ((org-at-table-p)
20498 (call-interactively 'org-table-insert-hline))
20499 ((org-region-active-p)
20500 (call-interactively 'org-toggle-item))
20501 ((org-in-item-p)
20502 (call-interactively 'org-cycle-list-bullet))
20504 (call-interactively 'org-toggle-item))))
20506 (defun org-toggle-heading (&optional nstars)
20507 "Convert headings to normal text, or items or text to headings.
20508 If there is no active region, only convert the current line.
20510 With a `\\[universal-argument]' prefix, convert the whole list at
20511 point into heading.
20513 In a region:
20515 - If the first non blank line is a headline, remove the stars
20516 from all headlines in the region.
20518 - If it is a normal line, turn each and every normal line (i.e.,
20519 not an heading or an item) in the region into headings. If you
20520 want to convert only the first line of this region, use one
20521 universal prefix argument.
20523 - If it is a plain list item, turn all plain list items into headings.
20525 When converting a line into a heading, the number of stars is chosen
20526 such that the lines become children of the current entry. However,
20527 when a numeric prefix argument is given, its value determines the
20528 number of stars to add."
20529 (interactive "P")
20530 (let ((skip-blanks
20531 (function
20532 ;; Return beginning of first non-blank line, starting from
20533 ;; line at POS.
20534 (lambda (pos)
20535 (save-excursion
20536 (goto-char pos)
20537 (while (org-at-comment-p) (forward-line))
20538 (skip-chars-forward " \r\t\n")
20539 (point-at-bol)))))
20540 beg end toggled)
20541 ;; Determine boundaries of changes. If a universal prefix has
20542 ;; been given, put the list in a region. If region ends at a bol,
20543 ;; do not consider the last line to be in the region.
20545 (when (and current-prefix-arg (org-at-item-p))
20546 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20547 (org-mark-element))
20549 (if (org-region-active-p)
20550 (setq beg (funcall skip-blanks (region-beginning))
20551 end (copy-marker (save-excursion
20552 (goto-char (region-end))
20553 (if (bolp) (point) (point-at-eol)))))
20554 (setq beg (funcall skip-blanks (point-at-bol))
20555 end (copy-marker (point-at-eol))))
20556 ;; Ensure inline tasks don't count as headings.
20557 (org-with-limited-levels
20558 (save-excursion
20559 (goto-char beg)
20560 (cond
20561 ;; Case 1. Started at an heading: de-star headings.
20562 ((org-at-heading-p)
20563 (while (< (point) end)
20564 (when (org-at-heading-p t)
20565 (looking-at org-outline-regexp) (replace-match "")
20566 (setq toggled t))
20567 (forward-line)))
20568 ;; Case 2. Started at an item: change items into headlines.
20569 ;; One star will be added by `org-list-to-subtree'.
20570 ((org-at-item-p)
20571 (while (< (point) end)
20572 (when (org-at-item-p)
20573 ;; Pay attention to cases when region ends before list.
20574 (let* ((struct (org-list-struct))
20575 (list-end
20576 (min (org-list-get-bottom-point struct) (1+ end))))
20577 (save-restriction
20578 (narrow-to-region (point) list-end)
20579 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20580 (setq toggled t))
20581 (forward-line)))
20582 ;; Case 3. Started at normal text: make every line an heading,
20583 ;; skipping headlines and items.
20584 (t (let* ((stars
20585 (make-string
20586 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20587 (add-stars
20588 (cond (nstars "") ; stars from prefix only
20589 ((equal stars "") "*") ; before first heading
20590 (org-odd-levels-only "**") ; inside heading, odd
20591 (t "*"))) ; inside heading, oddeven
20592 (rpl (concat stars add-stars " "))
20593 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20594 (while (< (point) (if (equal nstars '(4)) lend end))
20595 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20596 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20597 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20598 (forward-line)))))))
20599 (unless toggled (message "Cannot toggle heading from here"))))
20601 (defun org-meta-return (&optional arg)
20602 "Insert a new heading or wrap a region in a table.
20603 Calls `org-insert-heading', `org-insert-item' or
20604 `org-table-wrap-region', depending on context. When called with
20605 an argument, unconditionally call `org-insert-heading'."
20606 (interactive "P")
20607 (org-check-before-invisible-edit 'insert)
20608 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20609 (call-interactively (cond (arg #'org-insert-heading)
20610 ((org-at-table-p) #'org-table-wrap-region)
20611 ((org-in-item-p) #'org-insert-item)
20612 (t #'org-insert-heading)))))
20614 ;;; Menu entries
20616 (defsubst org-in-subtree-not-table-p ()
20617 "Are we in a subtree and not in a table?"
20618 (and (not (org-before-first-heading-p))
20619 (not (org-at-table-p))))
20621 ;; Define the Org mode menus
20622 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20623 '("Tbl"
20624 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20625 ["Next Field" org-cycle (org-at-table-p)]
20626 ["Previous Field" org-shifttab (org-at-table-p)]
20627 ["Next Row" org-return (org-at-table-p)]
20628 "--"
20629 ["Blank Field" org-table-blank-field (org-at-table-p)]
20630 ["Edit Field" org-table-edit-field (org-at-table-p)]
20631 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20632 "--"
20633 ("Column"
20634 ["Move Column Left" org-metaleft (org-at-table-p)]
20635 ["Move Column Right" org-metaright (org-at-table-p)]
20636 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20637 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20638 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20639 ("Row"
20640 ["Move Row Up" org-metaup (org-at-table-p)]
20641 ["Move Row Down" org-metadown (org-at-table-p)]
20642 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20643 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20644 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20645 "--"
20646 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20647 ("Rectangle"
20648 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20649 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20650 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20651 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20652 "--"
20653 ("Calculate"
20654 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20655 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20656 ["Edit Formulas" org-edit-special (org-at-table-p)]
20657 "--"
20658 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20659 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20660 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20661 "--"
20662 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20663 "--"
20664 ["Sum Column/Rectangle" org-table-sum
20665 (or (org-at-table-p) (org-region-active-p))]
20666 ["Which Column?" org-table-current-column (org-at-table-p)])
20667 ["Debug Formulas"
20668 org-table-toggle-formula-debugger
20669 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20670 ["Show Col/Row Numbers"
20671 org-table-toggle-coordinate-overlays
20672 :style toggle
20673 :selected (bound-and-true-p org-table-overlay-coordinates)]
20674 "--"
20675 ["Create" org-table-create (not (org-at-table-p))]
20676 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20677 ["Import from File" org-table-import (not (org-at-table-p))]
20678 ["Export to File" org-table-export (org-at-table-p)]
20679 "--"
20680 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20681 "--"
20682 ("Plot"
20683 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20684 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20686 (easy-menu-define org-org-menu org-mode-map "Org menu"
20687 '("Org"
20688 ("Show/Hide"
20689 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20690 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20691 ["Sparse Tree..." org-sparse-tree t]
20692 ["Reveal Context" org-reveal t]
20693 ["Show All" org-show-all t]
20694 "--"
20695 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20696 "--"
20697 ["New Heading" org-insert-heading t]
20698 ("Navigate Headings"
20699 ["Up" outline-up-heading t]
20700 ["Next" outline-next-visible-heading t]
20701 ["Previous" outline-previous-visible-heading t]
20702 ["Next Same Level" outline-forward-same-level t]
20703 ["Previous Same Level" outline-backward-same-level t]
20704 "--"
20705 ["Jump" org-goto t])
20706 ("Edit Structure"
20707 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20708 "--"
20709 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20710 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20711 "--"
20712 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20713 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20714 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20715 "--"
20716 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20717 "--"
20718 ["Copy visible text" org-copy-visible t]
20719 "--"
20720 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20721 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20722 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20723 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20724 "--"
20725 ["Sort Region/Children" org-sort t]
20726 "--"
20727 ["Convert to odd levels" org-convert-to-odd-levels t]
20728 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20729 ("Editing"
20730 ["Emphasis..." org-emphasize t]
20731 ["Edit Source Example" org-edit-special t]
20732 "--"
20733 ["Footnote new/jump" org-footnote-action t]
20734 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20735 ("Archive"
20736 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20737 "--"
20738 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20739 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20740 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20742 "--"
20743 ("Hyperlinks"
20744 ["Store Link (Global)" org-store-link t]
20745 ["Find existing link to here" org-occur-link-in-agenda-files t]
20746 ["Insert Link" org-insert-link t]
20747 ["Follow Link" org-open-at-point t]
20748 "--"
20749 ["Next link" org-next-link t]
20750 ["Previous link" org-previous-link t]
20751 "--"
20752 ["Descriptive Links"
20753 org-toggle-link-display
20754 :style radio
20755 :selected org-descriptive-links
20757 ["Literal Links"
20758 org-toggle-link-display
20759 :style radio
20760 :selected (not org-descriptive-links)])
20761 "--"
20762 ("TODO Lists"
20763 ["TODO/DONE/-" org-todo t]
20764 ("Select keyword"
20765 ["Next keyword" org-shiftright (org-at-heading-p)]
20766 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20767 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20768 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20769 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20770 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20771 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20772 "--"
20773 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20774 :selected org-enforce-todo-dependencies :style toggle :active t]
20775 "Settings for tree at point"
20776 ["Do Children sequentially" org-toggle-ordered-property :style radio
20777 :selected (org-entry-get nil "ORDERED")
20778 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20779 ["Do Children parallel" org-toggle-ordered-property :style radio
20780 :selected (not (org-entry-get nil "ORDERED"))
20781 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20782 "--"
20783 ["Set Priority" org-priority t]
20784 ["Priority Up" org-shiftup t]
20785 ["Priority Down" org-shiftdown t]
20786 "--"
20787 ["Get news from all feeds" org-feed-update-all t]
20788 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20789 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20790 ("TAGS and Properties"
20791 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20792 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20793 "--"
20794 ["Set property" org-set-property (not (org-before-first-heading-p))]
20795 ["Column view of properties" org-columns t]
20796 ["Insert Column View DBlock" org-columns-insert-dblock t])
20797 ("Dates and Scheduling"
20798 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20799 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20800 ("Change Date"
20801 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20802 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20803 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20804 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20805 ["Compute Time Range" org-evaluate-time-range t]
20806 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20807 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20808 "--"
20809 ["Custom time format" org-toggle-time-stamp-overlays
20810 :style radio :selected org-display-custom-times]
20811 "--"
20812 ["Goto Calendar" org-goto-calendar t]
20813 ["Date from Calendar" org-date-from-calendar t]
20814 "--"
20815 ["Start/Restart Timer" org-timer-start t]
20816 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20817 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20818 ["Insert Timer String" org-timer t]
20819 ["Insert Timer Item" org-timer-item t])
20820 ("Logging work"
20821 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20822 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20823 ["Clock out" org-clock-out t]
20824 ["Clock cancel" org-clock-cancel t]
20825 "--"
20826 ["Mark as default task" org-clock-mark-default-task t]
20827 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20828 ["Goto running clock" org-clock-goto t]
20829 "--"
20830 ["Display times" org-clock-display t]
20831 ["Create clock table" org-clock-report t]
20832 "--"
20833 ["Record DONE time"
20834 (progn (setq org-log-done (not org-log-done))
20835 (message "Switching to %s will %s record a timestamp"
20836 (car org-done-keywords)
20837 (if org-log-done "automatically" "not")))
20838 :style toggle :selected org-log-done])
20839 "--"
20840 ["Agenda Command..." org-agenda t]
20841 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20842 ("File List for Agenda")
20843 ("Special views current file"
20844 ["TODO Tree" org-show-todo-tree t]
20845 ["Check Deadlines" org-check-deadlines t]
20846 ["Tags/Property tree" org-match-sparse-tree t])
20847 "--"
20848 ["Export/Publish..." org-export-dispatch t]
20849 ("LaTeX"
20850 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20851 :style toggle :selected org-cdlatex-mode]
20852 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20853 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20854 ["Modify math symbol" org-cdlatex-math-modify
20855 (org-inside-LaTeX-fragment-p)]
20856 ["Insert citation" org-reftex-citation t])
20857 "--"
20858 ("MobileOrg"
20859 ["Push Files and Views" org-mobile-push t]
20860 ["Get Captured and Flagged" org-mobile-pull t]
20861 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20862 "--"
20863 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20864 "--"
20865 ("Documentation"
20866 ["Show Version" org-version t]
20867 ["Info Documentation" org-info t])
20868 ("Customize"
20869 ["Browse Org Group" org-customize t]
20870 "--"
20871 ["Expand This Menu" org-create-customize-menu
20872 (fboundp 'customize-menu-create)])
20873 ["Send bug report" org-submit-bug-report t]
20874 "--"
20875 ("Refresh/Reload"
20876 ["Refresh setup current buffer" org-mode-restart t]
20877 ["Reload Org (after update)" org-reload t]
20878 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20881 (defun org-info (&optional node)
20882 "Read documentation for Org in the info system.
20883 With optional NODE, go directly to that node."
20884 (interactive)
20885 (info (format "(org)%s" (or node ""))))
20887 ;;;###autoload
20888 (defun org-submit-bug-report ()
20889 "Submit a bug report on Org via mail.
20891 Don't hesitate to report any problems or inaccurate documentation.
20893 If you don't have setup sending mail from (X)Emacs, please copy the
20894 output buffer into your mail program, as it gives us important
20895 information about your Org version and configuration."
20896 (interactive)
20897 (require 'reporter)
20898 (defvar reporter-prompt-for-summary-p)
20899 (org-load-modules-maybe)
20900 (org-require-autoloaded-modules)
20901 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20902 (reporter-submit-bug-report
20903 "emacs-orgmode@gnu.org"
20904 (org-version nil 'full)
20905 (let (list)
20906 (save-window-excursion
20907 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20908 (delete-other-windows)
20909 (erase-buffer)
20910 (insert "You are about to submit a bug report to the Org mailing list.
20912 We would like to add your full Org and Outline configuration to the
20913 bug report. This greatly simplifies the work of the maintainer and
20914 other experts on the mailing list.
20916 HOWEVER, some variables you have customized may contain private
20917 information. The names of customers, colleagues, or friends, might
20918 appear in the form of file names, tags, todo states, or search strings.
20919 If you answer yes to the prompt, you might want to check and remove
20920 such private information before sending the email.")
20921 (add-text-properties (point-min) (point-max) '(face org-warning))
20922 (when (yes-or-no-p "Include your Org configuration ")
20923 (mapatoms
20924 (lambda (v)
20925 (and (boundp v)
20926 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20927 (or (and (symbol-value v)
20928 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20929 (and
20930 (get v 'custom-type) (get v 'standard-value)
20931 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20932 (push v list)))))
20933 (kill-buffer (get-buffer "*Warn about privacy*"))
20934 list))
20935 nil nil
20936 "Remember to cover the basics, that is, what you expected to happen and
20937 what in fact did happen. You don't know how to make a good report? See
20939 https://orgmode.org/manual/Feedback.html#Feedback
20941 Your bug report will be posted to the Org mailing list.
20942 ------------------------------------------------------------------------")
20943 (save-excursion
20944 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20945 (replace-match "\\1Bug: \\3 [\\2]")))))
20948 (defun org-install-agenda-files-menu ()
20949 (let ((bl (buffer-list)))
20950 (save-excursion
20951 (while bl
20952 (set-buffer (pop bl))
20953 (when (derived-mode-p 'org-mode) (setq bl nil)))
20954 (when (derived-mode-p 'org-mode)
20955 (easy-menu-change
20956 '("Org") "File List for Agenda"
20957 (append
20958 (list
20959 ["Edit File List" (org-edit-agenda-file-list) t]
20960 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20961 ["Remove Current File from List" org-remove-file t]
20962 ["Cycle through agenda files" org-cycle-agenda-files t]
20963 ["Occur in all agenda files" org-occur-in-agenda-files t]
20964 "--")
20965 (mapcar 'org-file-menu-entry
20966 ;; Prevent initialization from failing.
20967 (ignore-errors (org-agenda-files t)))))))))
20969 ;;;; Documentation
20971 (defun org-require-autoloaded-modules ()
20972 (interactive)
20973 (mapc #'require
20974 '(org-agenda org-archive org-attach org-clock org-colview org-id
20975 org-table org-timer)))
20977 ;;;###autoload
20978 (defun org-reload (&optional uncompiled)
20979 "Reload all Org Lisp files.
20980 With prefix arg UNCOMPILED, load the uncompiled versions."
20981 (interactive "P")
20982 (require 'loadhist)
20983 (let* ((org-dir (org-find-library-dir "org"))
20984 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20985 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20986 (remove-re (format "\\`%s\\'"
20987 (regexp-opt '("org" "org-loaddefs" "org-version"))))
20988 (feats (delete-dups
20989 (mapcar 'file-name-sans-extension
20990 (mapcar 'file-name-nondirectory
20991 (delq nil
20992 (mapcar 'feature-file
20993 features))))))
20994 (lfeat (append
20995 (sort
20996 (setq feats
20997 (delq nil (mapcar
20998 (lambda (f)
20999 (if (and (string-match feature-re f)
21000 (not (string-match remove-re f)))
21001 f nil))
21002 feats)))
21003 'string-lessp)
21004 (list "org-version" "org")))
21005 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21006 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21007 load-uncore load-misses)
21008 (setq load-misses
21009 (delq 't
21010 (mapcar (lambda (f)
21011 (or (org-load-noerror-mustsuffix (concat org-dir f))
21012 (and (string= org-dir contrib-dir)
21013 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21014 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21015 (add-to-list 'load-uncore f 'append)
21018 lfeat)))
21019 (when load-uncore
21020 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21021 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21022 (if load-misses
21023 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21024 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21025 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21027 ;;;###autoload
21028 (defun org-customize ()
21029 "Call the customize function with org as argument."
21030 (interactive)
21031 (org-load-modules-maybe)
21032 (org-require-autoloaded-modules)
21033 (customize-browse 'org))
21035 (defun org-create-customize-menu ()
21036 "Create a full customization menu for Org mode, insert it into the menu."
21037 (interactive)
21038 (org-load-modules-maybe)
21039 (org-require-autoloaded-modules)
21040 (if (fboundp 'customize-menu-create)
21041 (progn
21042 (easy-menu-change
21043 '("Org") "Customize"
21044 `(["Browse Org group" org-customize t]
21045 "--"
21046 ,(customize-menu-create 'org)
21047 ["Set" Custom-set t]
21048 ["Save" Custom-save t]
21049 ["Reset to Current" Custom-reset-current t]
21050 ["Reset to Saved" Custom-reset-saved t]
21051 ["Reset to Standard Settings" Custom-reset-standard t]))
21052 (message "\"Org\"-menu now contains full customization menu"))
21053 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21055 ;;;; Miscellaneous stuff
21057 ;;; Generally useful functions
21059 (defun org-link-display-format (s)
21060 "Replace links in string S with their description.
21061 If there is no description, use the link target."
21062 (save-match-data
21063 (replace-regexp-in-string
21064 org-bracket-link-analytic-regexp
21065 (lambda (m)
21066 (if (match-end 5) (match-string 5 m)
21067 (concat (match-string 1 m) (match-string 3 m))))
21068 s nil t)))
21070 (defun org-toggle-link-display ()
21071 "Toggle the literal or descriptive display of links."
21072 (interactive)
21073 (if org-descriptive-links
21074 (progn (org-remove-from-invisibility-spec '(org-link))
21075 (org-restart-font-lock)
21076 (setq org-descriptive-links nil))
21077 (progn (add-to-invisibility-spec '(org-link))
21078 (org-restart-font-lock)
21079 (setq org-descriptive-links t))))
21081 (defun org-in-clocktable-p ()
21082 "Check if the cursor is in a clocktable."
21083 (let ((pos (point)) start)
21084 (save-excursion
21085 (end-of-line 1)
21086 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21087 (setq start (match-beginning 0))
21088 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21089 (>= (match-end 0) pos)
21090 start))))
21092 (defun org-in-verbatim-emphasis ()
21093 (save-match-data
21094 (and (org-in-regexp org-verbatim-re 2)
21095 (>= (point) (match-beginning 3))
21096 (<= (point) (match-end 4)))))
21098 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21099 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21100 (if (and marker (marker-buffer marker)
21101 (buffer-live-p (marker-buffer marker)))
21102 (progn
21103 (pop-to-buffer-same-window (marker-buffer marker))
21104 (when (or (> marker (point-max)) (< marker (point-min)))
21105 (widen))
21106 (goto-char marker)
21107 (org-show-context 'org-goto))
21108 (if bookmark
21109 (bookmark-jump bookmark)
21110 (error "Cannot find location"))))
21112 (defun org-quote-csv-field (s)
21113 "Quote field for inclusion in CSV material."
21114 (if (string-match "[\",]" s)
21115 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21118 (defun org-force-self-insert (N)
21119 "Needed to enforce self-insert under remapping."
21120 (interactive "p")
21121 (self-insert-command N))
21123 (defun org-fill-template (template alist)
21124 "Find each %key of ALIST in TEMPLATE and replace it."
21125 (let ((case-fold-search nil))
21126 (dolist (entry (sort (copy-sequence alist)
21127 (lambda (a b) (< (length (car a)) (length (car b))))))
21128 (setq template
21129 (replace-regexp-in-string
21130 (concat "%" (regexp-quote (car entry)))
21131 (or (cdr entry) "") template t t)))
21132 template))
21134 (defun org-quote-vert (s)
21135 "Replace \"|\" with \"\\vert\"."
21136 (while (string-match "|" s)
21137 (setq s (replace-match "\\vert" t t s)))
21140 (defun org-uuidgen-p (s)
21141 "Is S an ID created by UUIDGEN?"
21142 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21144 (defun org-in-src-block-p (&optional inside)
21145 "Whether point is in a code source block.
21146 When INSIDE is non-nil, don't consider we are within a src block
21147 when point is at #+BEGIN_SRC or #+END_SRC."
21148 (let ((case-fold-search t))
21149 (or (and (eq (get-char-property (point) 'src-block) t))
21150 (and (not inside)
21151 (save-match-data
21152 (save-excursion
21153 (beginning-of-line)
21154 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21156 (defun org-context ()
21157 "Return a list of contexts of the current cursor position.
21158 If several contexts apply, all are returned.
21159 Each context entry is a list with a symbol naming the context, and
21160 two positions indicating start and end of the context. Possible
21161 contexts are:
21163 :headline anywhere in a headline
21164 :headline-stars on the leading stars in a headline
21165 :todo-keyword on a TODO keyword (including DONE) in a headline
21166 :tags on the TAGS in a headline
21167 :priority on the priority cookie in a headline
21168 :item on the first line of a plain list item
21169 :item-bullet on the bullet/number of a plain list item
21170 :checkbox on the checkbox in a plain list item
21171 :table in an Org table
21172 :table-special on a special filed in a table
21173 :table-table in a table.el table
21174 :clocktable in a clocktable
21175 :src-block in a source block
21176 :link on a hyperlink
21177 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21178 :target on a <<target>>
21179 :radio-target on a <<<radio-target>>>
21180 :latex-fragment on a LaTeX fragment
21181 :latex-preview on a LaTeX fragment with overlaid preview image
21183 This function expects the position to be visible because it uses font-lock
21184 faces as a help to recognize the following contexts: :table-special, :link,
21185 and :keyword."
21186 (let* ((f (get-text-property (point) 'face))
21187 (faces (if (listp f) f (list f)))
21188 (case-fold-search t)
21189 (p (point)) clist o)
21190 ;; First the large context
21191 (cond
21192 ((org-at-heading-p t)
21193 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21194 (when (progn
21195 (beginning-of-line 1)
21196 (looking-at org-todo-line-tags-regexp))
21197 (push (org-point-in-group p 1 :headline-stars) clist)
21198 (push (org-point-in-group p 2 :todo-keyword) clist)
21199 (push (org-point-in-group p 4 :tags) clist))
21200 (goto-char p)
21201 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21202 (when (looking-at "\\[#[A-Z0-9]\\]")
21203 (push (org-point-in-group p 0 :priority) clist)))
21205 ((org-at-item-p)
21206 (push (org-point-in-group p 2 :item-bullet) clist)
21207 (push (list :item (point-at-bol)
21208 (save-excursion (org-end-of-item) (point)))
21209 clist)
21210 (and (org-at-item-checkbox-p)
21211 (push (org-point-in-group p 0 :checkbox) clist)))
21213 ((org-at-table-p)
21214 (push (list :table (org-table-begin) (org-table-end)) clist)
21215 (when (memq 'org-formula faces)
21216 (push (list :table-special
21217 (previous-single-property-change p 'face)
21218 (next-single-property-change p 'face)) clist)))
21219 ((org-at-table-p 'any)
21220 (push (list :table-table) clist)))
21221 (goto-char p)
21223 (let ((case-fold-search t))
21224 ;; New the "medium" contexts: clocktables, source blocks
21225 (cond ((org-in-clocktable-p)
21226 (push (list :clocktable
21227 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21228 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21229 (match-beginning 1))
21230 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21231 (match-end 0))) clist))
21232 ((org-in-src-block-p)
21233 (push (list :src-block
21234 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21235 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21236 (match-beginning 1))
21237 (and (search-forward "#+END_SRC" nil t)
21238 (match-beginning 0))) clist))))
21239 (goto-char p)
21241 ;; Now the small context
21242 (cond
21243 ((org-at-timestamp-p)
21244 (push (org-point-in-group p 0 :timestamp) clist))
21245 ((memq 'org-link faces)
21246 (push (list :link
21247 (previous-single-property-change p 'face)
21248 (next-single-property-change p 'face)) clist))
21249 ((memq 'org-special-keyword faces)
21250 (push (list :keyword
21251 (previous-single-property-change p 'face)
21252 (next-single-property-change p 'face)) clist))
21253 ((org-at-target-p)
21254 (push (org-point-in-group p 0 :target) clist)
21255 (goto-char (1- (match-beginning 0)))
21256 (when (looking-at org-radio-target-regexp)
21257 (push (org-point-in-group p 0 :radio-target) clist))
21258 (goto-char p))
21259 ((setq o (cl-some
21260 (lambda (o)
21261 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21263 (overlays-at (point))))
21264 (push (list :latex-fragment
21265 (overlay-start o) (overlay-end o)) clist)
21266 (push (list :latex-preview
21267 (overlay-start o) (overlay-end o)) clist))
21268 ((org-inside-LaTeX-fragment-p)
21269 ;; FIXME: positions wrong.
21270 (push (list :latex-fragment (point) (point)) clist)))
21272 (setq clist (nreverse (delq nil clist)))
21273 clist))
21275 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21276 "Non-nil when point is between matches of START-RE and END-RE.
21278 Also return a non-nil value when point is on one of the matches.
21280 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21281 buffer positions. Default values are the positions of headlines
21282 surrounding the point.
21284 The functions returns a cons cell whose car (resp. cdr) is the
21285 position before START-RE (resp. after END-RE)."
21286 (save-match-data
21287 (let ((pos (point))
21288 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21289 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21290 beg end)
21291 (save-excursion
21292 ;; Point is on a block when on START-RE or if START-RE can be
21293 ;; found before it...
21294 (and (or (org-in-regexp start-re)
21295 (re-search-backward start-re limit-up t))
21296 (setq beg (match-beginning 0))
21297 ;; ... and END-RE after it...
21298 (goto-char (match-end 0))
21299 (re-search-forward end-re limit-down t)
21300 (> (setq end (match-end 0)) pos)
21301 ;; ... without another START-RE in-between.
21302 (goto-char (match-beginning 0))
21303 (not (re-search-backward start-re (1+ beg) t))
21304 ;; Return value.
21305 (cons beg end))))))
21307 (defun org-in-block-p (names)
21308 "Non-nil when point belongs to a block whose name belongs to NAMES.
21310 NAMES is a list of strings containing names of blocks.
21312 Return first block name matched, or nil. Beware that in case of
21313 nested blocks, the returned name may not belong to the closest
21314 block from point."
21315 (save-match-data
21316 (catch 'exit
21317 (let ((case-fold-search t)
21318 (lim-up (save-excursion (outline-previous-heading)))
21319 (lim-down (save-excursion (outline-next-heading))))
21320 (dolist (name names)
21321 (let ((n (regexp-quote name)))
21322 (when (org-between-regexps-p
21323 (concat "^[ \t]*#\\+begin_" n)
21324 (concat "^[ \t]*#\\+end_" n)
21325 lim-up lim-down)
21326 (throw 'exit n)))))
21327 nil)))
21329 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21330 "Call `multi-occur' with buffers for all agenda files."
21331 (interactive "sOrg-files matching: ")
21332 (let* ((files (org-agenda-files))
21333 (tnames (mapcar #'file-truename files))
21334 (extra org-agenda-text-search-extra-files))
21335 (when (eq (car extra) 'agenda-archives)
21336 (setq extra (cdr extra))
21337 (setq files (org-add-archive-files files)))
21338 (dolist (f extra)
21339 (unless (member (file-truename f) tnames)
21340 (unless (member f files) (setq files (append files (list f))))
21341 (setq tnames (append tnames (list (file-truename f))))))
21342 (multi-occur
21343 (mapcar (lambda (x)
21344 (with-current-buffer
21345 ;; FIXME: Why not just (find-file-noselect x)?
21346 ;; Is it to avoid the "revert buffer" prompt?
21347 (or (get-file-buffer x) (find-file-noselect x))
21348 (widen)
21349 (current-buffer)))
21350 files)
21351 regexp)))
21353 (add-hook 'occur-mode-find-occurrence-hook
21354 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21356 (defun org-occur-link-in-agenda-files ()
21357 "Create a link and search for it in the agendas.
21358 The link is not stored in `org-stored-links', it is just created
21359 for the search purpose."
21360 (interactive)
21361 (let ((link (condition-case nil
21362 (org-store-link nil)
21363 (error "Unable to create a link to here"))))
21364 (org-occur-in-agenda-files (regexp-quote link))))
21366 (defun org-back-over-empty-lines ()
21367 "Move backwards over whitespace, to the beginning of the first empty line.
21368 Returns the number of empty lines passed."
21369 (let ((pos (point)))
21370 (if (cdr (assq 'heading org-blank-before-new-entry))
21371 (skip-chars-backward " \t\n\r")
21372 (unless (eobp)
21373 (forward-line -1)))
21374 (beginning-of-line 2)
21375 (goto-char (min (point) pos))
21376 (count-lines (point) pos)))
21378 (defun org-switch-to-buffer-other-window (&rest args)
21379 "Switch to buffer in a second window on the current frame.
21380 In particular, do not allow pop-up frames.
21381 Returns the newly created buffer."
21382 (org-no-popups
21383 (apply 'switch-to-buffer-other-window args)))
21385 (defun org-replace-escapes (string table)
21386 "Replace %-escapes in STRING with values in TABLE.
21387 TABLE is an association list with keys like \"%a\" and string values.
21388 The sequences in STRING may contain normal field width and padding information,
21389 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21390 so values can contain further %-escapes if they are define later in TABLE."
21391 (let ((tbl (copy-alist table))
21392 (case-fold-search nil)
21393 (pchg 0)
21394 re rpl)
21395 (dolist (e tbl)
21396 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21397 (when (and (cdr e) (string-match re (cdr e)))
21398 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21399 (safe "SREF"))
21400 (add-text-properties 0 3 (list 'sref sref) safe)
21401 (setcdr e (replace-match safe t t (cdr e)))))
21402 (while (string-match re string)
21403 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21404 (cdr e)))
21405 (setq string (replace-match rpl t t string))))
21406 (while (setq pchg (next-property-change pchg string))
21407 (let ((sref (get-text-property pchg 'sref string)))
21408 (when (and sref (string-match "SREF" string pchg))
21409 (setq string (replace-match sref t t string)))))
21410 string))
21412 ;;; TODO: Only called once, from ox-odt which should probably use
21413 ;;; org-export-inline-image-p or something.
21414 (defun org-file-image-p (file)
21415 "Return non-nil if FILE is an image."
21416 (save-match-data
21417 (string-match (image-file-name-regexp) file)))
21419 (defun org-get-cursor-date (&optional with-time)
21420 "Return the date at cursor in as a time.
21421 This works in the calendar and in the agenda, anywhere else it just
21422 returns the current time.
21423 If WITH-TIME is non-nil, returns the time of the event at point (in
21424 the agenda) or the current time of the day."
21425 (let (date day defd tp hod mod)
21426 (when with-time
21427 (setq tp (get-text-property (point) 'time))
21428 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21429 (setq hod (string-to-number (match-string 1 tp))
21430 mod (string-to-number (match-string 2 tp))))
21431 (or tp (let ((now (decode-time)))
21432 (setq hod (nth 2 now)
21433 mod (nth 1 now)))))
21434 (cond
21435 ((eq major-mode 'calendar-mode)
21436 (setq date (calendar-cursor-to-date)
21437 defd (encode-time 0 (or mod 0) (or hod 0)
21438 (nth 1 date) (nth 0 date) (nth 2 date))))
21439 ((eq major-mode 'org-agenda-mode)
21440 (setq day (get-text-property (point) 'day))
21441 (when day
21442 (setq date (calendar-gregorian-from-absolute day)
21443 defd (encode-time 0 (or mod 0) (or hod 0)
21444 (nth 1 date) (nth 0 date) (nth 2 date))))))
21445 (or defd (current-time))))
21447 (defun org-mark-subtree (&optional up)
21448 "Mark the current subtree.
21449 This puts point at the start of the current subtree, and mark at
21450 the end. If a numeric prefix UP is given, move up into the
21451 hierarchy of headlines by UP levels before marking the subtree."
21452 (interactive "P")
21453 (org-with-limited-levels
21454 (cond ((org-at-heading-p) (beginning-of-line))
21455 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21456 (t (outline-previous-visible-heading 1))))
21457 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21458 (if (called-interactively-p 'any)
21459 (call-interactively 'org-mark-element)
21460 (org-mark-element)))
21462 ;;; Indentation
21464 (defvar org-element-greater-elements)
21465 (defun org--get-expected-indentation (element contentsp)
21466 "Expected indentation column for current line, according to ELEMENT.
21467 ELEMENT is an element containing point. CONTENTSP is non-nil
21468 when indentation is to be computed according to contents of
21469 ELEMENT."
21470 (let ((type (org-element-type element))
21471 (start (org-element-property :begin element))
21472 (post-affiliated (org-element-property :post-affiliated element)))
21473 (org-with-wide-buffer
21474 (cond
21475 (contentsp
21476 (cl-case type
21477 ((diary-sexp footnote-definition) 0)
21478 ((headline inlinetask nil)
21479 (if (not org-adapt-indentation) 0
21480 (let ((level (org-current-level)))
21481 (if level (1+ level) 0))))
21482 ((item plain-list) (org-list-item-body-column post-affiliated))
21484 (goto-char start)
21485 (org-get-indentation))))
21486 ((memq type '(headline inlinetask nil))
21487 (if (org-match-line "[ \t]*$")
21488 (org--get-expected-indentation element t)
21490 ((memq type '(diary-sexp footnote-definition)) 0)
21491 ;; First paragraph of a footnote definition or an item.
21492 ;; Indent like parent.
21493 ((< (line-beginning-position) start)
21494 (org--get-expected-indentation
21495 (org-element-property :parent element) t))
21496 ;; At first line: indent according to previous sibling, if any,
21497 ;; ignoring footnote definitions and inline tasks, or parent's
21498 ;; contents.
21499 ((= (line-beginning-position) start)
21500 (catch 'exit
21501 (while t
21502 (if (= (point-min) start) (throw 'exit 0)
21503 (goto-char (1- start))
21504 (let* ((previous (org-element-at-point))
21505 (parent previous))
21506 (while (and parent (<= (org-element-property :end parent) start))
21507 (setq previous parent
21508 parent (org-element-property :parent parent)))
21509 (cond
21510 ((not previous) (throw 'exit 0))
21511 ((> (org-element-property :end previous) start)
21512 (throw 'exit (org--get-expected-indentation previous t)))
21513 ((memq (org-element-type previous)
21514 '(footnote-definition inlinetask))
21515 (setq start (org-element-property :begin previous)))
21516 (t (goto-char (org-element-property :begin previous))
21517 (throw 'exit
21518 (if (bolp) (org-get-indentation)
21519 ;; At first paragraph in an item or
21520 ;; a footnote definition.
21521 (org--get-expected-indentation
21522 (org-element-property :parent previous) t))))))))))
21523 ;; Otherwise, move to the first non-blank line above.
21525 (beginning-of-line)
21526 (let ((pos (point)))
21527 (skip-chars-backward " \r\t\n")
21528 (cond
21529 ;; Two blank lines end a footnote definition or a plain
21530 ;; list. When we indent an empty line after them, the
21531 ;; containing list or footnote definition is over, so it
21532 ;; qualifies as a previous sibling. Therefore, we indent
21533 ;; like its first line.
21534 ((and (memq type '(footnote-definition plain-list))
21535 (> (count-lines (point) pos) 2))
21536 (goto-char start)
21537 (org-get-indentation))
21538 ;; Line above is the first one of a paragraph at the
21539 ;; beginning of an item or a footnote definition. Indent
21540 ;; like parent.
21541 ((< (line-beginning-position) start)
21542 (org--get-expected-indentation
21543 (org-element-property :parent element) t))
21544 ;; Line above is the beginning of an element, i.e., point
21545 ;; was originally on the blank lines between element's start
21546 ;; and contents.
21547 ((= (line-beginning-position) post-affiliated)
21548 (org--get-expected-indentation element t))
21549 ;; POS is after contents in a greater element. Indent like
21550 ;; the beginning of the element.
21551 ((and (memq type org-element-greater-elements)
21552 (let ((cend (org-element-property :contents-end element)))
21553 (and cend (<= cend pos))))
21554 ;; As a special case, if point is at the end of a footnote
21555 ;; definition or an item, indent like the very last element
21556 ;; within. If that last element is an item, indent like
21557 ;; its contents.
21558 (if (memq type '(footnote-definition item plain-list))
21559 (let ((last (org-element-at-point)))
21560 (goto-char pos)
21561 (org--get-expected-indentation
21562 last (eq (org-element-type last) 'item)))
21563 (goto-char start)
21564 (org-get-indentation)))
21565 ;; In any other case, indent like the current line.
21566 (t (org-get-indentation)))))))))
21568 (defun org--align-node-property ()
21569 "Align node property at point.
21570 Alignment is done according to `org-property-format', which see."
21571 (when (save-excursion
21572 (beginning-of-line)
21573 (looking-at org-property-re))
21574 (replace-match
21575 (concat (match-string 4)
21576 (org-trim
21577 (format org-property-format (match-string 1) (match-string 3))))
21578 t t)))
21580 (defun org-indent-line ()
21581 "Indent line depending on context.
21583 Indentation is done according to the following rules:
21585 - Footnote definitions, diary sexps, headlines and inline tasks
21586 have to start at column 0.
21588 - On the very first line of an element, consider, in order, the
21589 next rules until one matches:
21591 1. If there's a sibling element before, ignoring footnote
21592 definitions and inline tasks, indent like its first line.
21594 2. If element has a parent, indent like its contents. More
21595 precisely, if parent is an item, indent after the
21596 description part, if any, or the bullet (see
21597 `org-list-description-max-indent'). Else, indent like
21598 parent's first line.
21600 3. Otherwise, indent relatively to current level, if
21601 `org-adapt-indentation' is non-nil, or to left margin.
21603 - On a blank line at the end of an element, indent according to
21604 the type of the element. More precisely
21606 1. If element is a plain list, an item, or a footnote
21607 definition, indent like the very last element within.
21609 2. If element is a paragraph, indent like its last non blank
21610 line.
21612 3. Otherwise, indent like its very first line.
21614 - In the code part of a source block, use language major mode
21615 to indent current line if `org-src-tab-acts-natively' is
21616 non-nil. If it is nil, do nothing.
21618 - Otherwise, indent like the first non-blank line above.
21620 The function doesn't indent an item as it could break the whole
21621 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21622 `\\[org-shiftmetaright]'.
21624 Also align node properties according to `org-property-format'."
21625 (interactive)
21626 (cond
21627 ((org-at-heading-p) 'noindent)
21629 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21630 (type (org-element-type element)))
21631 (cond ((and (memq type '(plain-list item))
21632 (= (line-beginning-position)
21633 (org-element-property :post-affiliated element)))
21634 'noindent)
21635 ((and (eq type 'latex-environment)
21636 (>= (point) (org-element-property :post-affiliated element))
21637 (< (point) (org-with-wide-buffer
21638 (goto-char (org-element-property :end element))
21639 (skip-chars-backward " \r\t\n")
21640 (line-beginning-position 2))))
21641 'noindent)
21642 ((and (eq type 'src-block)
21643 org-src-tab-acts-natively
21644 (> (line-beginning-position)
21645 (org-element-property :post-affiliated element))
21646 (< (line-beginning-position)
21647 (org-with-wide-buffer
21648 (goto-char (org-element-property :end element))
21649 (skip-chars-backward " \r\t\n")
21650 (line-beginning-position))))
21651 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21653 (let ((column (org--get-expected-indentation element nil)))
21654 ;; Preserve current column.
21655 (if (<= (current-column) (current-indentation))
21656 (indent-line-to column)
21657 (save-excursion (indent-line-to column))))
21658 ;; Align node property. Also preserve current column.
21659 (when (eq type 'node-property)
21660 (let ((column (current-column)))
21661 (org--align-node-property)
21662 (org-move-to-column column)))))))))
21664 (defun org-indent-region (start end)
21665 "Indent each non-blank line in the region.
21666 Called from a program, START and END specify the region to
21667 indent. The function will not indent contents of example blocks,
21668 verse blocks and export blocks as leading white spaces are
21669 assumed to be significant there."
21670 (interactive "r")
21671 (save-excursion
21672 (goto-char start)
21673 (skip-chars-forward " \r\t\n")
21674 (unless (eobp) (beginning-of-line))
21675 (let ((indent-to
21676 (lambda (ind pos)
21677 ;; Set IND as indentation for all lines between point and
21678 ;; POS. Blank lines are ignored. Leave point after POS
21679 ;; once done.
21680 (let ((limit (copy-marker pos)))
21681 (while (< (point) limit)
21682 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21683 (forward-line))
21684 (set-marker limit nil))))
21685 (end (copy-marker end)))
21686 (while (< (point) end)
21687 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21688 (let* ((element (org-element-at-point))
21689 (type (org-element-type element))
21690 (element-end (copy-marker (org-element-property :end element)))
21691 (ind (org--get-expected-indentation element nil)))
21692 (cond
21693 ;; Element indented as a single block. Example blocks
21694 ;; preserving indentation are a special case since the
21695 ;; "contents" must not be indented whereas the block
21696 ;; boundaries can.
21697 ((or (memq type '(export-block latex-environment))
21698 (and (eq type 'example-block)
21699 (not
21700 (or org-src-preserve-indentation
21701 (org-element-property :preserve-indent element)))))
21702 (let ((offset (- ind (org-get-indentation))))
21703 (unless (zerop offset)
21704 (indent-rigidly (org-element-property :begin element)
21705 (org-element-property :end element)
21706 offset)))
21707 (goto-char element-end))
21708 ;; Elements indented line wise. Be sure to exclude
21709 ;; example blocks (preserving indentation) and source
21710 ;; blocks from this category as they are treated
21711 ;; specially later.
21712 ((or (memq type '(paragraph table table-row))
21713 (not (or (org-element-property :contents-begin element)
21714 (memq type '(example-block src-block)))))
21715 (when (eq type 'node-property)
21716 (org--align-node-property)
21717 (beginning-of-line))
21718 (funcall indent-to ind (min element-end end)))
21719 ;; Elements consisting of three parts: before the
21720 ;; contents, the contents, and after the contents. The
21721 ;; contents are treated specially, according to the
21722 ;; element type, or not indented at all. Other parts are
21723 ;; indented as a single block.
21725 (let* ((post (copy-marker
21726 (org-element-property :post-affiliated element)))
21727 (cbeg
21728 (copy-marker
21729 (cond
21730 ((not (org-element-property :contents-begin element))
21731 ;; Fake contents for source blocks.
21732 (org-with-wide-buffer
21733 (goto-char post)
21734 (line-beginning-position 2)))
21735 ((memq type '(footnote-definition item plain-list))
21736 ;; Contents in these elements could start on
21737 ;; the same line as the beginning of the
21738 ;; element. Make sure we start indenting
21739 ;; from the second line.
21740 (org-with-wide-buffer
21741 (goto-char post)
21742 (end-of-line)
21743 (skip-chars-forward " \r\t\n")
21744 (if (eobp) (point) (line-beginning-position))))
21745 (t (org-element-property :contents-begin element)))))
21746 (cend (copy-marker
21747 (or (org-element-property :contents-end element)
21748 ;; Fake contents for source blocks.
21749 (org-with-wide-buffer
21750 (goto-char element-end)
21751 (skip-chars-backward " \r\t\n")
21752 (line-beginning-position)))
21753 t)))
21754 ;; Do not change items indentation individually as it
21755 ;; might break the list as a whole. On the other
21756 ;; hand, when at a plain list, indent it as a whole.
21757 (cond ((eq type 'plain-list)
21758 (let ((offset (- ind (org-get-indentation))))
21759 (unless (zerop offset)
21760 (indent-rigidly (org-element-property :begin element)
21761 (org-element-property :end element)
21762 offset))
21763 (goto-char cbeg)))
21764 ((eq type 'item) (goto-char cbeg))
21765 (t (funcall indent-to ind (min cbeg end))))
21766 (when (< (point) end)
21767 (cl-case type
21768 ((example-block verse-block))
21769 (src-block
21770 ;; In a source block, indent source code
21771 ;; according to language major mode, but only if
21772 ;; `org-src-tab-acts-natively' is non-nil.
21773 (when (and (< (point) end) org-src-tab-acts-natively)
21774 (ignore-errors
21775 (org-babel-do-in-edit-buffer
21776 (indent-region (point-min) (point-max))))))
21777 (t (org-indent-region (point) (min cend end))))
21778 (goto-char (min cend end))
21779 (when (< (point) end)
21780 (funcall indent-to ind (min element-end end))))
21781 (set-marker post nil)
21782 (set-marker cbeg nil)
21783 (set-marker cend nil))))
21784 (set-marker element-end nil))))
21785 (set-marker end nil))))
21787 (defun org-indent-drawer ()
21788 "Indent the drawer at point."
21789 (interactive)
21790 (unless (save-excursion
21791 (beginning-of-line)
21792 (looking-at-p org-drawer-regexp))
21793 (user-error "Not at a drawer"))
21794 (let ((element (org-element-at-point)))
21795 (unless (memq (org-element-type element) '(drawer property-drawer))
21796 (user-error "Not at a drawer"))
21797 (org-with-wide-buffer
21798 (org-indent-region (org-element-property :begin element)
21799 (org-element-property :end element))))
21800 (message "Drawer at point indented"))
21802 (defun org-indent-block ()
21803 "Indent the block at point."
21804 (interactive)
21805 (unless (save-excursion
21806 (beginning-of-line)
21807 (let ((case-fold-search t))
21808 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21809 (user-error "Not at a block"))
21810 (let ((element (org-element-at-point)))
21811 (unless (memq (org-element-type element)
21812 '(comment-block center-block dynamic-block example-block
21813 export-block quote-block special-block
21814 src-block verse-block))
21815 (user-error "Not at a block"))
21816 (org-with-wide-buffer
21817 (org-indent-region (org-element-property :begin element)
21818 (org-element-property :end element))))
21819 (message "Block at point indented"))
21822 ;;; Filling
21824 ;; We use our own fill-paragraph and auto-fill functions.
21826 ;; `org-fill-paragraph' relies on adaptive filling and context
21827 ;; checking. Appropriate `fill-prefix' is computed with
21828 ;; `org-adaptive-fill-function'.
21830 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21831 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21832 ;; `org-adaptive-fill-function' value. Internally,
21833 ;; `org-comment-line-break-function' breaks the line.
21835 ;; `org-setup-filling' installs filling and auto-filling related
21836 ;; variables during `org-mode' initialization.
21838 (defun org-setup-filling ()
21839 (require 'org-element)
21840 ;; Prevent auto-fill from inserting unwanted new items.
21841 (when (boundp 'fill-nobreak-predicate)
21842 (setq-local
21843 fill-nobreak-predicate
21844 (org-uniquify
21845 (append fill-nobreak-predicate
21846 '(org-fill-line-break-nobreak-p
21847 org-fill-n-macro-as-item-nobreak-p
21848 org-fill-paragraph-with-timestamp-nobreak-p)))))
21849 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21850 (setq-local paragraph-start paragraph-ending)
21851 (setq-local paragraph-separate paragraph-ending))
21852 (setq-local fill-paragraph-function 'org-fill-paragraph)
21853 (setq-local auto-fill-inhibit-regexp nil)
21854 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21855 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21856 (setq-local comment-line-break-function 'org-comment-line-break-function))
21858 (defun org-fill-line-break-nobreak-p ()
21859 "Non-nil when a new line at point would create an Org line break."
21860 (save-excursion
21861 (skip-chars-backward "[ \t]")
21862 (skip-chars-backward "\\\\")
21863 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21865 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21866 "Non-nil when a new line at point would split a timestamp."
21867 (and (org-at-timestamp-p 'lax)
21868 (not (looking-at org-ts-regexp-both))))
21870 (defun org-fill-n-macro-as-item-nobreak-p ()
21871 "Non-nil when a new line at point would create a new list."
21872 ;; During export, a "n" macro followed by a dot or a closing
21873 ;; parenthesis can end up being parsed as a new list item.
21874 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21876 (defvar orgtbl-line-start-regexp) ; From org-table.el
21877 (defun org-adaptive-fill-function ()
21878 "Compute a fill prefix for the current line.
21879 Return fill prefix, as a string, or nil if current line isn't
21880 meant to be filled. For convenience, if `adaptive-fill-regexp'
21881 matches in paragraphs or comments, use it."
21882 (org-with-wide-buffer
21883 (unless (org-at-heading-p)
21884 (let* ((p (line-beginning-position))
21885 (element (save-excursion
21886 (beginning-of-line)
21887 (org-element-at-point)))
21888 (type (org-element-type element))
21889 (post-affiliated (org-element-property :post-affiliated element)))
21890 (unless (< p post-affiliated)
21891 (cl-case type
21892 (comment
21893 (save-excursion
21894 (beginning-of-line)
21895 (looking-at "[ \t]*")
21896 (concat (match-string 0) "# ")))
21897 (footnote-definition "")
21898 ((item plain-list)
21899 (make-string (org-list-item-body-column post-affiliated) ?\s))
21900 (paragraph
21901 ;; Fill prefix is usually the same as the current line,
21902 ;; unless the paragraph is at the beginning of an item.
21903 (let ((parent (org-element-property :parent element)))
21904 (save-excursion
21905 (beginning-of-line)
21906 (cond ((eq (org-element-type parent) 'item)
21907 (make-string (org-list-item-body-column
21908 (org-element-property :begin parent))
21909 ?\s))
21910 ((and adaptive-fill-regexp
21911 ;; Locally disable
21912 ;; `adaptive-fill-function' to let
21913 ;; `fill-context-prefix' handle
21914 ;; `adaptive-fill-regexp' variable.
21915 (let (adaptive-fill-function)
21916 (fill-context-prefix
21917 post-affiliated
21918 (org-element-property :end element)))))
21919 ((looking-at "[ \t]+") (match-string 0))
21920 (t "")))))
21921 (comment-block
21922 ;; Only fill contents if P is within block boundaries.
21923 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21924 (forward-line)
21925 (point)))
21926 (cend (save-excursion
21927 (goto-char (org-element-property :end element))
21928 (skip-chars-backward " \r\t\n")
21929 (line-beginning-position))))
21930 (when (and (>= p cbeg) (< p cend))
21931 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21932 (match-string 0)
21933 ""))))))))))
21935 (defun org-fill-element (&optional justify)
21936 "Fill element at point, when applicable.
21938 This function only applies to comment blocks, comments, example
21939 blocks and paragraphs. Also, as a special case, re-align table
21940 when point is at one.
21942 If JUSTIFY is non-nil (interactively, with prefix argument),
21943 justify as well. If `sentence-end-double-space' is non-nil, then
21944 period followed by one space does not end a sentence, so don't
21945 break a line there. The variable `fill-column' controls the
21946 width for filling.
21948 For convenience, when point is at a plain list, an item or
21949 a footnote definition, try to fill the first paragraph within."
21950 (with-syntax-table org-mode-transpose-word-syntax-table
21951 ;; Move to end of line in order to get the first paragraph within
21952 ;; a plain list or a footnote definition.
21953 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21954 ;; First check if point is in a blank line at the beginning of
21955 ;; the buffer. In that case, ignore filling.
21956 (cl-case (org-element-type element)
21957 ;; Use major mode filling function is src blocks.
21958 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21959 ;; Align Org tables, leave table.el tables as-is.
21960 (table-row (org-table-align) t)
21961 (table
21962 (when (eq (org-element-property :type element) 'org)
21963 (save-excursion
21964 (goto-char (org-element-property :post-affiliated element))
21965 (org-table-align)))
21967 (paragraph
21968 ;; Paragraphs may contain `line-break' type objects.
21969 (let ((beg (max (point-min)
21970 (org-element-property :contents-begin element)))
21971 (end (min (point-max)
21972 (org-element-property :contents-end element))))
21973 ;; Do nothing if point is at an affiliated keyword.
21974 (if (< (line-end-position) beg) t
21975 ;; Fill paragraph, taking line breaks into account.
21976 (save-excursion
21977 (goto-char beg)
21978 (let ((cuts (list beg)))
21979 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
21980 (when (eq 'line-break
21981 (org-element-type
21982 (save-excursion (backward-char)
21983 (org-element-context))))
21984 (push (point) cuts)))
21985 (dolist (c (delq end cuts))
21986 (fill-region-as-paragraph c end justify)
21987 (setq end c))))
21988 t)))
21989 ;; Contents of `comment-block' type elements should be
21990 ;; filled as plain text, but only if point is within block
21991 ;; markers.
21992 (comment-block
21993 (let* ((case-fold-search t)
21994 (beg (save-excursion
21995 (goto-char (org-element-property :begin element))
21996 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21997 (forward-line)
21998 (point)))
21999 (end (save-excursion
22000 (goto-char (org-element-property :end element))
22001 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22002 (line-beginning-position))))
22003 (if (or (< (point) beg) (> (point) end)) t
22004 (fill-region-as-paragraph
22005 (save-excursion (end-of-line)
22006 (re-search-backward "^[ \t]*$" beg 'move)
22007 (line-beginning-position))
22008 (save-excursion (beginning-of-line)
22009 (re-search-forward "^[ \t]*$" end 'move)
22010 (line-beginning-position))
22011 justify))))
22012 ;; Fill comments.
22013 (comment
22014 (let ((begin (org-element-property :post-affiliated element))
22015 (end (org-element-property :end element)))
22016 (when (and (>= (point) begin) (<= (point) end))
22017 (let ((begin (save-excursion
22018 (end-of-line)
22019 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22020 (progn (forward-line) (point))
22021 begin)))
22022 (end (save-excursion
22023 (end-of-line)
22024 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22025 (1- (line-beginning-position))
22026 (skip-chars-backward " \r\t\n")
22027 (line-end-position)))))
22028 ;; Do not fill comments when at a blank line.
22029 (when (> end begin)
22030 (let ((fill-prefix
22031 (save-excursion
22032 (beginning-of-line)
22033 (looking-at "[ \t]*#")
22034 (let ((comment-prefix (match-string 0)))
22035 (goto-char (match-end 0))
22036 (if (looking-at adaptive-fill-regexp)
22037 (concat comment-prefix (match-string 0))
22038 (concat comment-prefix " "))))))
22039 (save-excursion
22040 (fill-region-as-paragraph begin end justify))))))
22042 ;; Ignore every other element.
22043 (otherwise t)))))
22045 (defun org-fill-paragraph (&optional justify region)
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 For convenience, when point is at a plain list, an item or
22053 a footnote definition, try to fill the first paragraph within.
22055 If JUSTIFY is non-nil (interactively, with prefix argument),
22056 justify as well. If `sentence-end-double-space' is non-nil, then
22057 period followed by one space does not end a sentence, so don't
22058 break a line there. The variable `fill-column' controls the
22059 width for filling.
22061 The REGION argument is non-nil if called interactively; in that
22062 case, if Transient Mark mode is enabled and the mark is active,
22063 fill each of the elements in the active region, instead of just
22064 filling the current element."
22065 (interactive (progn
22066 (barf-if-buffer-read-only)
22067 (list (if current-prefix-arg 'full) t)))
22068 (cond
22069 ((and region transient-mark-mode mark-active
22070 (not (eq (region-beginning) (region-end))))
22071 (let ((origin (point-marker))
22072 (start (region-beginning)))
22073 (unwind-protect
22074 (progn
22075 (goto-char (region-end))
22076 (while (> (point) start)
22077 (org-backward-paragraph)
22078 (org-fill-element justify)))
22079 (goto-char origin)
22080 (set-marker origin nil))))
22081 (t (org-fill-element justify))))
22083 (defun org-auto-fill-function ()
22084 "Auto-fill function."
22085 ;; Check if auto-filling is meaningful.
22086 (let ((fc (current-fill-column)))
22087 (when (and fc (> (current-column) fc))
22088 (let* ((fill-prefix (org-adaptive-fill-function))
22089 ;; Enforce empty fill prefix, if required. Otherwise, it
22090 ;; will be computed again.
22091 (adaptive-fill-mode (not (equal fill-prefix ""))))
22092 (when fill-prefix (do-auto-fill))))))
22094 (defun org-comment-line-break-function (&optional soft)
22095 "Break line at point and indent, continuing comment if within one.
22096 The inserted newline is marked hard if variable
22097 `use-hard-newlines' is true, unless optional argument SOFT is
22098 non-nil."
22099 (if soft (insert-and-inherit ?\n) (newline 1))
22100 (save-excursion (forward-char -1) (delete-horizontal-space))
22101 (delete-horizontal-space)
22102 (indent-to-left-margin)
22103 (insert-before-markers-and-inherit fill-prefix))
22106 ;;; Fixed Width Areas
22108 (defun org-toggle-fixed-width ()
22109 "Toggle fixed-width markup.
22111 Add or remove fixed-width markup on current line, whenever it
22112 makes sense. Return an error otherwise.
22114 If a region is active and if it contains only fixed-width areas
22115 or blank lines, remove all fixed-width markup in it. If the
22116 region contains anything else, convert all non-fixed-width lines
22117 to fixed-width ones.
22119 Blank lines at the end of the region are ignored unless the
22120 region only contains such lines."
22121 (interactive)
22122 (if (not (org-region-active-p))
22123 ;; No region:
22125 ;; Remove fixed width marker only in a fixed-with element.
22127 ;; Add fixed width maker in paragraphs, in blank lines after
22128 ;; elements or at the beginning of a headline or an inlinetask,
22129 ;; and before any one-line elements (e.g., a clock).
22130 (progn
22131 (beginning-of-line)
22132 (let* ((element (org-element-at-point))
22133 (type (org-element-type element)))
22134 (cond
22135 ((and (eq type 'fixed-width)
22136 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22137 (replace-match
22138 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22139 ((and (memq type '(babel-call clock comment diary-sexp headline
22140 horizontal-rule keyword paragraph
22141 planning))
22142 (<= (org-element-property :post-affiliated element) (point)))
22143 (skip-chars-forward " \t")
22144 (insert ": "))
22145 ((and (looking-at-p "[ \t]*$")
22146 (or (eq type 'inlinetask)
22147 (save-excursion
22148 (skip-chars-forward " \r\t\n")
22149 (<= (org-element-property :end element) (point)))))
22150 (delete-region (point) (line-end-position))
22151 (org-indent-line)
22152 (insert ": "))
22153 (t (user-error "Cannot insert a fixed-width line here")))))
22154 ;; Region active.
22155 (let* ((begin (save-excursion
22156 (goto-char (region-beginning))
22157 (line-beginning-position)))
22158 (end (copy-marker
22159 (save-excursion
22160 (goto-char (region-end))
22161 (unless (eolp) (beginning-of-line))
22162 (if (save-excursion (re-search-backward "\\S-" begin t))
22163 (progn (skip-chars-backward " \r\t\n") (point))
22164 (point)))))
22165 (all-fixed-width-p
22166 (catch 'not-all-p
22167 (save-excursion
22168 (goto-char begin)
22169 (skip-chars-forward " \r\t\n")
22170 (when (eobp) (throw 'not-all-p nil))
22171 (while (< (point) end)
22172 (let ((element (org-element-at-point)))
22173 (if (eq (org-element-type element) 'fixed-width)
22174 (goto-char (org-element-property :end element))
22175 (throw 'not-all-p nil))))
22176 t))))
22177 (if all-fixed-width-p
22178 (save-excursion
22179 (goto-char begin)
22180 (while (< (point) end)
22181 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22182 (replace-match
22183 "" nil nil nil
22184 (if (= (line-end-position) (match-end 0)) 0 1)))
22185 (forward-line)))
22186 (let ((min-ind (point-max)))
22187 ;; Find minimum indentation across all lines.
22188 (save-excursion
22189 (goto-char begin)
22190 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22191 (setq min-ind 0)
22192 (catch 'zerop
22193 (while (< (point) end)
22194 (unless (looking-at-p "[ \t]*$")
22195 (let ((ind (org-get-indentation)))
22196 (setq min-ind (min min-ind ind))
22197 (when (zerop ind) (throw 'zerop t))))
22198 (forward-line)))))
22199 ;; Loop over all lines and add fixed-width markup everywhere
22200 ;; but in fixed-width lines.
22201 (save-excursion
22202 (goto-char begin)
22203 (while (< (point) end)
22204 (cond
22205 ((org-at-heading-p)
22206 (insert ": ")
22207 (forward-line)
22208 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22209 (insert ":")
22210 (forward-line)))
22211 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22212 (let* ((element (org-element-at-point))
22213 (element-end (org-element-property :end element)))
22214 (if (eq (org-element-type element) 'fixed-width)
22215 (progn (goto-char element-end)
22216 (skip-chars-backward " \r\t\n")
22217 (forward-line))
22218 (let ((limit (min end element-end)))
22219 (while (< (point) limit)
22220 (org-move-to-column min-ind t)
22221 (insert ": ")
22222 (forward-line))))))
22224 (org-move-to-column min-ind t)
22225 (insert ": ")
22226 (forward-line)))))))
22227 (set-marker end nil))))
22230 ;;; Blocks
22232 (defun org-block-map (function &optional start end)
22233 "Call FUNCTION at the head of all source blocks in the current buffer.
22234 Optional arguments START and END can be used to limit the range."
22235 (let ((start (or start (point-min)))
22236 (end (or end (point-max))))
22237 (save-excursion
22238 (goto-char start)
22239 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22240 (save-excursion
22241 (save-match-data
22242 (goto-char (match-beginning 0))
22243 (funcall function)))))))
22245 (defun org-next-block (arg &optional backward block-regexp)
22246 "Jump to the next block.
22248 With a prefix argument ARG, jump forward ARG many blocks.
22250 When BACKWARD is non-nil, jump to the previous block.
22252 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22253 Match data is set according to this regexp when the function
22254 returns.
22256 Return point at beginning of the opening line of found block.
22257 Throw an error if no block is found."
22258 (interactive "p")
22259 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22260 (case-fold-search t)
22261 (search-fn (if backward #'re-search-backward #'re-search-forward))
22262 (count (or arg 1))
22263 (origin (point))
22264 last-element)
22265 (if backward (beginning-of-line) (end-of-line))
22266 (while (and (> count 0) (funcall search-fn re nil t))
22267 (let ((element (save-excursion
22268 (goto-char (match-beginning 0))
22269 (save-match-data (org-element-at-point)))))
22270 (when (and (memq (org-element-type element)
22271 '(center-block comment-block dynamic-block
22272 example-block export-block quote-block
22273 special-block src-block verse-block))
22274 (<= (match-beginning 0)
22275 (org-element-property :post-affiliated element)))
22276 (setq last-element element)
22277 (cl-decf count))))
22278 (if (= count 0)
22279 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22280 (save-match-data (org-show-context)))
22281 (goto-char origin)
22282 (user-error "No %s code blocks" (if backward "previous" "further")))))
22284 (defun org-previous-block (arg &optional block-regexp)
22285 "Jump to the previous block.
22286 With a prefix argument ARG, jump backward ARG many source blocks.
22287 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22288 (interactive "p")
22289 (org-next-block arg t block-regexp))
22292 ;;; Comments
22294 ;; Org comments syntax is quite complex. It requires the entire line
22295 ;; to be just a comment. Also, even with the right syntax at the
22296 ;; beginning of line, some elements (e.g., verse-block or
22297 ;; example-block) don't accept comments. Usual Emacs comment commands
22298 ;; cannot cope with those requirements. Therefore, Org replaces them.
22300 ;; Org still relies on `comment-dwim', but cannot trust
22301 ;; `comment-only-p'. So, `comment-region-function' and
22302 ;; `uncomment-region-function' both point
22303 ;; to`org-comment-or-uncomment-region'. Eventually,
22304 ;; `org-insert-comment' takes care of insertion of comments at the
22305 ;; beginning of line.
22307 ;; `org-setup-comments-handling' install comments related variables
22308 ;; during `org-mode' initialization.
22310 (defun org-setup-comments-handling ()
22311 (interactive)
22312 (setq-local comment-use-syntax nil)
22313 (setq-local comment-start "# ")
22314 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22315 (setq-local comment-insert-comment-function 'org-insert-comment)
22316 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22317 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22319 (defun org-insert-comment ()
22320 "Insert an empty comment above current line.
22321 If the line is empty, insert comment at its beginning. When
22322 point is within a source block, comment according to the related
22323 major mode."
22324 (if (let ((element (org-element-at-point)))
22325 (and (eq (org-element-type element) 'src-block)
22326 (< (save-excursion
22327 (goto-char (org-element-property :post-affiliated element))
22328 (line-end-position))
22329 (point))
22330 (> (save-excursion
22331 (goto-char (org-element-property :end element))
22332 (skip-chars-backward " \r\t\n")
22333 (line-beginning-position))
22334 (point))))
22335 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22336 (beginning-of-line)
22337 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22338 (open-line 1))
22339 (org-indent-line)
22340 (insert "# ")))
22342 (defvar comment-empty-lines) ; From newcomment.el.
22343 (defun org-comment-or-uncomment-region (beg end &rest _)
22344 "Comment or uncomment each non-blank line in the region.
22345 Uncomment each non-blank line between BEG and END if it only
22346 contains commented lines. Otherwise, comment them. If region is
22347 strictly within a source block, use appropriate comment syntax."
22348 (if (let ((element (org-element-at-point)))
22349 (and (eq (org-element-type element) 'src-block)
22350 (< (save-excursion
22351 (goto-char (org-element-property :post-affiliated element))
22352 (line-end-position))
22353 beg)
22354 (>= (save-excursion
22355 (goto-char (org-element-property :end element))
22356 (skip-chars-backward " \r\t\n")
22357 (line-beginning-position))
22358 end)))
22359 ;; Translate region boundaries for the Org buffer to the source
22360 ;; buffer.
22361 (let ((offset (- end beg)))
22362 (save-excursion
22363 (goto-char beg)
22364 (org-babel-do-in-edit-buffer
22365 (comment-or-uncomment-region (point) (+ offset (point))))))
22366 (save-restriction
22367 ;; Restrict region
22368 (narrow-to-region (save-excursion (goto-char beg)
22369 (skip-chars-forward " \r\t\n" end)
22370 (line-beginning-position))
22371 (save-excursion (goto-char end)
22372 (skip-chars-backward " \r\t\n" beg)
22373 (line-end-position)))
22374 (let ((uncommentp
22375 ;; UNCOMMENTP is non-nil when every non blank line between
22376 ;; BEG and END is a comment.
22377 (save-excursion
22378 (goto-char (point-min))
22379 (while (and (not (eobp))
22380 (let ((element (org-element-at-point)))
22381 (and (eq (org-element-type element) 'comment)
22382 (goto-char (min (point-max)
22383 (org-element-property
22384 :end element)))))))
22385 (eobp))))
22386 (if uncommentp
22387 ;; Only blank lines and comments in region: uncomment it.
22388 (save-excursion
22389 (goto-char (point-min))
22390 (while (not (eobp))
22391 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22392 (replace-match "" nil nil nil 1))
22393 (forward-line)))
22394 ;; Comment each line in region.
22395 (let ((min-indent (point-max)))
22396 ;; First find the minimum indentation across all lines.
22397 (save-excursion
22398 (goto-char (point-min))
22399 (while (and (not (eobp)) (not (zerop min-indent)))
22400 (unless (looking-at "[ \t]*$")
22401 (setq min-indent (min min-indent (current-indentation))))
22402 (forward-line)))
22403 ;; Then loop over all lines.
22404 (save-excursion
22405 (goto-char (point-min))
22406 (while (not (eobp))
22407 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22408 ;; Don't get fooled by invisible text (e.g. link path)
22409 ;; when moving to column MIN-INDENT.
22410 (let ((buffer-invisibility-spec nil))
22411 (org-move-to-column min-indent t))
22412 (insert comment-start))
22413 (forward-line)))))))))
22415 (defun org-comment-dwim (_arg)
22416 "Call the comment command you mean.
22417 Call `org-toggle-comment' if on a heading, otherwise call
22418 `comment-dwim', within a source edit buffer if needed."
22419 (interactive "*P")
22420 (cond ((org-at-heading-p)
22421 (call-interactively #'org-toggle-comment))
22422 ((org-in-src-block-p)
22423 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22424 (t (call-interactively #'comment-dwim))))
22427 ;;; Timestamps API
22429 ;; This section contains tools to operate on, or create, timestamp
22430 ;; objects, as returned by, e.g. `org-element-context'.
22432 (defun org-timestamp-from-string (s)
22433 "Convert Org timestamp S, as a string, into a timestamp object.
22434 Return nil if S is not a valid timestamp string."
22435 (when (org-string-nw-p s)
22436 (with-temp-buffer
22437 (save-excursion (insert s))
22438 (org-element-timestamp-parser))))
22440 (defun org-timestamp-from-time (time &optional with-time inactive)
22441 "Convert a time value into a timestamp object.
22443 TIME is an Emacs internal time representation, as returned, e.g.,
22444 by `current-time'.
22446 When optional argument WITH-TIME is non-nil, return a timestamp
22447 object with a time part, i.e., with hours and minutes.
22449 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22450 return an active timestamp."
22451 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22452 (org-element-create 'timestamp
22453 (list :type (if inactive 'inactive 'active)
22454 :year-start year
22455 :month-start month
22456 :day-start day
22457 :hour-start (and with-time hour)
22458 :minute-start (and with-time minute)))))
22460 (defun org-timestamp-to-time (timestamp &optional end)
22461 "Convert TIMESTAMP object into an Emacs internal time value.
22462 Use end of date range or time range when END is non-nil.
22463 Otherwise, use its start."
22464 (apply #'encode-time
22465 (cons 0
22466 (mapcar
22467 (lambda (prop) (or (org-element-property prop timestamp) 0))
22468 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22469 '(:minute-start :hour-start :day-start :month-start
22470 :year-start))))))
22472 (defun org-timestamp-has-time-p (timestamp)
22473 "Non-nil when TIMESTAMP has a time specified."
22474 (org-element-property :hour-start timestamp))
22476 (defun org-timestamp-format (timestamp format &optional end utc)
22477 "Format a TIMESTAMP object into a string.
22479 FORMAT is a format specifier to be passed to
22480 `format-time-string'.
22482 When optional argument END is non-nil, use end of date-range or
22483 time-range, if possible.
22485 When optional argument UTC is non-nil, time is be expressed as
22486 Universal Time."
22487 (format-time-string format (org-timestamp-to-time timestamp end)
22488 (and utc t)))
22490 (defun org-timestamp-split-range (timestamp &optional end)
22491 "Extract a TIMESTAMP object from a date or time range.
22493 END, when non-nil, means extract the end of the range.
22494 Otherwise, extract its start.
22496 Return a new timestamp object."
22497 (let ((type (org-element-property :type timestamp)))
22498 (if (memq type '(active inactive diary)) timestamp
22499 (let ((split-ts (org-element-copy timestamp)))
22500 ;; Set new type.
22501 (org-element-put-property
22502 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22503 ;; Copy start properties over end properties if END is
22504 ;; non-nil. Otherwise, copy end properties over `start' ones.
22505 (let ((p-alist '((:minute-start . :minute-end)
22506 (:hour-start . :hour-end)
22507 (:day-start . :day-end)
22508 (:month-start . :month-end)
22509 (:year-start . :year-end))))
22510 (dolist (p-cell p-alist)
22511 (org-element-put-property
22512 split-ts
22513 (funcall (if end #'car #'cdr) p-cell)
22514 (org-element-property
22515 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22516 ;; Eventually refresh `:raw-value'.
22517 (org-element-put-property split-ts :raw-value nil)
22518 (org-element-put-property
22519 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22521 (defun org-timestamp-translate (timestamp &optional boundary)
22522 "Translate TIMESTAMP object to custom format.
22524 Format string is defined in `org-time-stamp-custom-formats',
22525 which see.
22527 When optional argument BOUNDARY is non-nil, it is either the
22528 symbol `start' or `end'. In this case, only translate the
22529 starting or ending part of TIMESTAMP if it is a date or time
22530 range. Otherwise, translate both parts.
22532 Return timestamp as-is if `org-display-custom-times' is nil or if
22533 it has a `diary' type."
22534 (let ((type (org-element-property :type timestamp)))
22535 (if (or (not org-display-custom-times) (eq type 'diary))
22536 (org-element-interpret-data timestamp)
22537 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22538 org-time-stamp-custom-formats)))
22539 (if (and (not boundary) (memq type '(active-range inactive-range)))
22540 (concat (org-timestamp-format timestamp fmt)
22541 "--"
22542 (org-timestamp-format timestamp fmt t))
22543 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22545 ;;; Other stuff
22547 (defvar reftex-docstruct-symbol)
22548 (defvar org--rds)
22550 (defun org-reftex-citation ()
22551 "Use reftex-citation to insert a citation into the buffer.
22552 This looks for a line like
22554 #+BIBLIOGRAPHY: foo plain option:-d
22556 and derives from it that foo.bib is the bibliography file relevant
22557 for this document. It then installs the necessary environment for RefTeX
22558 to work in this buffer and calls `reftex-citation' to insert a citation
22559 into the buffer.
22561 Export of such citations to both LaTeX and HTML is handled by the contributed
22562 package ox-bibtex by Taru Karttunen."
22563 (interactive)
22564 (let ((reftex-docstruct-symbol 'org--rds)
22565 org--rds bib)
22566 (org-with-wide-buffer
22567 (let ((case-fold-search t)
22568 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22569 (if (not (save-excursion
22570 (or (re-search-forward re nil t)
22571 (re-search-backward re nil t))))
22572 (user-error "No bibliography defined in file")
22573 (setq bib (concat (match-string 1) ".bib")
22574 org--rds (list (list 'bib bib))))))
22575 (call-interactively 'reftex-citation)))
22577 ;;;; Functions extending outline functionality
22579 (defun org-beginning-of-line (&optional n)
22580 "Go to the beginning of the current visible line.
22582 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22583 symbol `reversed', on the first attempt move to where the
22584 headline text starts, and only move to beginning of line when the
22585 cursor is already before the start of the text of the headline.
22587 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22588 start of the text on the second attempt.
22590 With argument N not nil or 1, move forward N - 1 lines first."
22591 (interactive "^p")
22592 (let ((origin (point))
22593 (special (pcase org-special-ctrl-a/e
22594 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22595 deactivate-mark)
22596 ;; First move to a visible line.
22597 (if (bound-and-true-p visual-line-mode)
22598 (beginning-of-visual-line n)
22599 (move-beginning-of-line n)
22600 ;; `move-beginning-of-line' may leave point after invisible
22601 ;; characters if line starts with such of these (e.g., with
22602 ;; a link at column 0). Really move to the beginning of the
22603 ;; current visible line.
22604 (beginning-of-line))
22605 (cond
22606 ;; No special behavior. Point is already at the beginning of
22607 ;; a line, logical or visual.
22608 ((not special))
22609 ;; `beginning-of-visual-line' left point before logical beginning
22610 ;; of line: point is at the beginning of a visual line. Bail
22611 ;; out.
22612 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22613 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22614 ;; At a headline, special position is before the title, but
22615 ;; after any TODO keyword or priority cookie.
22616 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22617 (line-end-position)))
22618 (bol (point)))
22619 (if (eq special 'reversed)
22620 (when (and (= origin bol) (eq last-command this-command))
22621 (goto-char refpos))
22622 (when (or (> origin refpos) (= origin bol))
22623 (goto-char refpos)))))
22624 ((and (looking-at org-list-full-item-re)
22625 (memq (org-element-type (save-match-data (org-element-at-point)))
22626 '(item plain-list)))
22627 ;; Set special position at first white space character after
22628 ;; bullet, and check-box, if any.
22629 (let ((after-bullet
22630 (let ((box (match-end 3)))
22631 (cond ((not box) (match-end 1))
22632 ((eq (char-after box) ?\s) (1+ box))
22633 (t box)))))
22634 (if (eq special 'reversed)
22635 (when (and (= (point) origin) (eq last-command this-command))
22636 (goto-char after-bullet))
22637 (when (or (> origin after-bullet) (= (point) origin))
22638 (goto-char after-bullet)))))
22639 ;; No special context. Point is already at beginning of line.
22640 (t nil))))
22642 (defun org-end-of-line (&optional n)
22643 "Go to the end of the line, but before ellipsis, if any.
22645 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22646 symbol `reversed', ignore tags on the first attempt, and only
22647 move to after the tags when the cursor is already beyond the end
22648 of the headline.
22650 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22651 on the second attempt.
22653 With argument N not nil or 1, move forward N - 1 lines first."
22654 (interactive "^p")
22655 (let ((origin (point))
22656 (special (pcase org-special-ctrl-a/e
22657 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22658 deactivate-mark)
22659 ;; First move to a visible line.
22660 (if (bound-and-true-p visual-line-mode)
22661 (beginning-of-visual-line n)
22662 (move-beginning-of-line n))
22663 (cond
22664 ;; At a headline, with tags.
22665 ((and special
22666 (save-excursion
22667 (beginning-of-line)
22668 (let ((case-fold-search nil))
22669 (looking-at org-complex-heading-regexp)))
22670 (match-end 5))
22671 (let ((tags (save-excursion
22672 (goto-char (match-beginning 5))
22673 (skip-chars-backward " \t")
22674 (point)))
22675 (visual-end (and (bound-and-true-p visual-line-mode)
22676 (save-excursion
22677 (end-of-visual-line)
22678 (point)))))
22679 ;; If `end-of-visual-line' brings us before end of line or
22680 ;; even tags, i.e., the headline spans over multiple visual
22681 ;; lines, move there.
22682 (cond ((and visual-end
22683 (< visual-end tags)
22684 (<= origin visual-end))
22685 (goto-char visual-end))
22686 ((eq special 'reversed)
22687 (if (and (= origin (line-end-position))
22688 (eq this-command last-command))
22689 (goto-char tags)
22690 (end-of-line)))
22692 (if (or (< origin tags) (= origin (line-end-position)))
22693 (goto-char tags)
22694 (end-of-line))))))
22695 ((bound-and-true-p visual-line-mode)
22696 (let ((bol (line-beginning-position)))
22697 (end-of-visual-line)
22698 ;; If `end-of-visual-line' gets us past the ellipsis at the
22699 ;; end of a line, backtrack and use `end-of-line' instead.
22700 (when (/= bol (line-beginning-position))
22701 (goto-char bol)
22702 (end-of-line))))
22703 (t (end-of-line)))))
22705 (defun org-backward-sentence (&optional _arg)
22706 "Go to beginning of sentence, or beginning of table field.
22707 This will call `backward-sentence' or `org-table-beginning-of-field',
22708 depending on context."
22709 (interactive)
22710 (let* ((element (org-element-at-point))
22711 (contents-begin (org-element-property :contents-begin element))
22712 (table (org-element-lineage element '(table) t)))
22713 (if (and table
22714 (> (point) contents-begin)
22715 (<= (point) (org-element-property :contents-end table)))
22716 (call-interactively #'org-table-beginning-of-field)
22717 (save-restriction
22718 (when (and contents-begin
22719 (< (point-min) contents-begin)
22720 (> (point) contents-begin))
22721 (narrow-to-region contents-begin
22722 (org-element-property :contents-end element)))
22723 (call-interactively #'backward-sentence)))))
22725 (defun org-forward-sentence (&optional _arg)
22726 "Go to end of sentence, or end of table field.
22727 This will call `forward-sentence' or `org-table-end-of-field',
22728 depending on context."
22729 (interactive)
22730 (if (and (org-at-heading-p)
22731 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22732 (save-restriction
22733 (narrow-to-region (line-beginning-position) (line-end-position))
22734 (call-interactively #'forward-sentence))
22735 (let* ((element (org-element-at-point))
22736 (contents-end (org-element-property :contents-end element))
22737 (table (org-element-lineage element '(table) t)))
22738 (if (and table
22739 (>= (point) (org-element-property :contents-begin table))
22740 (< (point) contents-end))
22741 (call-interactively #'org-table-end-of-field)
22742 (save-restriction
22743 (when (and contents-end
22744 (> (point-max) contents-end)
22745 ;; Skip blank lines between elements.
22746 (< (org-element-property :end element)
22747 (save-excursion (goto-char contents-end)
22748 (skip-chars-forward " \r\t\n"))))
22749 (narrow-to-region (org-element-property :contents-begin element)
22750 contents-end))
22751 ;; End of heading is considered as the end of a sentence.
22752 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22753 (call-interactively #'forward-sentence)))))))
22755 (defun org-kill-line (&optional _arg)
22756 "Kill line, to tags or end of line."
22757 (interactive)
22758 (cond
22759 ((or (not org-special-ctrl-k)
22760 (bolp)
22761 (not (org-at-heading-p)))
22762 (when (and (get-char-property (line-end-position) 'invisible)
22763 org-ctrl-k-protect-subtree
22764 (or (eq org-ctrl-k-protect-subtree 'error)
22765 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22766 (user-error
22767 (substitute-command-keys
22768 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22769 (call-interactively
22770 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22771 ((looking-at org-tag-line-re)
22772 (let ((end (save-excursion
22773 (goto-char (match-beginning 1))
22774 (skip-chars-backward " \t"))))
22775 (if (<= end (point)) ;on tags part
22776 (kill-region (point) (line-end-position))
22777 (kill-region (point) end)))
22778 (org-align-tags))
22779 (t (kill-region (point) (line-end-position)))))
22781 (defun org-yank (&optional arg)
22782 "Yank. If the kill is a subtree, treat it specially.
22783 This command will look at the current kill and check if is a single
22784 subtree, or a series of subtrees[1]. If it passes the test, and if the
22785 cursor is at the beginning of a line or after the stars of a currently
22786 empty headline, then the yank is handled specially. How exactly depends
22787 on the value of the following variables.
22789 `org-yank-folded-subtrees'
22790 By default, this variable is non-nil, which results in
22791 subtree(s) being folded after insertion, except if doing so
22792 would swallow text after the yanked text.
22794 `org-yank-adjusted-subtrees'
22795 When non-nil (the default value is nil), the subtree will be
22796 promoted or demoted in order to fit into the local outline tree
22797 structure, which means that the level will be adjusted so that it
22798 becomes the smaller one of the two *visible* surrounding headings.
22800 Any prefix to this command will cause `yank' to be called directly with
22801 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22802 will just
22803 plainly yank the text as it is.
22805 \[1] The test checks if the first non-white line is a heading
22806 and if there are no other headings with fewer stars."
22807 (interactive "P")
22808 (org-yank-generic 'yank arg))
22810 (defun org-yank-generic (command arg)
22811 "Perform some yank-like command.
22813 This function implements the behavior described in the `org-yank'
22814 documentation. However, it has been generalized to work for any
22815 interactive command with similar behavior."
22817 ;; pretend to be command COMMAND
22818 (setq this-command command)
22820 (if arg
22821 (call-interactively command)
22823 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22824 (and (org-kill-is-subtree-p)
22825 (or (bolp)
22826 (and (looking-at "[ \t]*$")
22827 (string-match
22828 "\\`\\*+\\'"
22829 (buffer-substring (point-at-bol) (point)))))))
22830 swallowp)
22831 (cond
22832 ((and subtreep org-yank-folded-subtrees)
22833 (let ((beg (point))
22834 end)
22835 (if (and subtreep org-yank-adjusted-subtrees)
22836 (org-paste-subtree nil nil 'for-yank)
22837 (call-interactively command))
22839 (setq end (point))
22840 (goto-char beg)
22841 (when (and (bolp) subtreep
22842 (not (setq swallowp
22843 (org-yank-folding-would-swallow-text beg end))))
22844 (org-with-limited-levels
22845 (or (looking-at org-outline-regexp)
22846 (re-search-forward org-outline-regexp-bol end t))
22847 (while (and (< (point) end) (looking-at org-outline-regexp))
22848 (outline-hide-subtree)
22849 (org-cycle-show-empty-lines 'folded)
22850 (condition-case nil
22851 (outline-forward-same-level 1)
22852 (error (goto-char end))))))
22853 (when swallowp
22854 (message
22855 "Inserted text not folded because that would swallow text"))
22857 (goto-char end)
22858 (skip-chars-forward " \t\n\r")
22859 (beginning-of-line 1)
22860 (push-mark beg 'nomsg)))
22861 ((and subtreep org-yank-adjusted-subtrees)
22862 (let ((beg (point-at-bol)))
22863 (org-paste-subtree nil nil 'for-yank)
22864 (push-mark beg 'nomsg)))
22866 (call-interactively command))))))
22868 (defun org-yank-folding-would-swallow-text (beg end)
22869 "Would hide-subtree at BEG swallow any text after END?"
22870 (let (level)
22871 (org-with-limited-levels
22872 (save-excursion
22873 (goto-char beg)
22874 (when (or (looking-at org-outline-regexp)
22875 (re-search-forward org-outline-regexp-bol end t))
22876 (setq level (org-outline-level)))
22877 (goto-char end)
22878 (skip-chars-forward " \t\r\n\v\f")
22879 (not (or (eobp)
22880 (and (bolp) (looking-at-p org-outline-regexp)
22881 (<= (org-outline-level) level))))))))
22883 (defun org-back-to-heading (&optional invisible-ok)
22884 "Call `outline-back-to-heading', but provide a better error message."
22885 (condition-case nil
22886 (outline-back-to-heading invisible-ok)
22887 (error (error "Before first headline at position %d in buffer %s"
22888 (point) (current-buffer)))))
22890 (defun org-before-first-heading-p ()
22891 "Before first heading?"
22892 (save-excursion
22893 (end-of-line)
22894 (null (re-search-backward org-outline-regexp-bol nil t))))
22896 (defun org-at-heading-p (&optional ignored)
22897 (outline-on-heading-p t))
22899 (defun org-in-commented-heading-p (&optional no-inheritance)
22900 "Non-nil if point is under a commented heading.
22901 This function also checks ancestors of the current headline,
22902 unless optional argument NO-INHERITANCE is non-nil."
22903 (cond
22904 ((org-before-first-heading-p) nil)
22905 ((let ((headline (nth 4 (org-heading-components))))
22906 (and headline
22907 (let ((case-fold-search nil))
22908 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22909 headline)))))
22910 (no-inheritance nil)
22912 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22914 (defun org-at-comment-p nil
22915 "Is cursor in a commented line?"
22916 (save-excursion
22917 (save-match-data
22918 (beginning-of-line)
22919 (looking-at "^[ \t]*# "))))
22921 (defun org-at-drawer-p nil
22922 "Is cursor at a drawer keyword?"
22923 (save-excursion
22924 (move-beginning-of-line 1)
22925 (looking-at org-drawer-regexp)))
22927 (defun org-at-block-p nil
22928 "Is cursor at a block keyword?"
22929 (save-excursion
22930 (move-beginning-of-line 1)
22931 (looking-at org-block-regexp)))
22933 (defun org-point-at-end-of-empty-headline ()
22934 "If point is at the end of an empty headline, return t, else nil.
22935 If the heading only contains a TODO keyword, it is still still considered
22936 empty."
22937 (let ((case-fold-search nil))
22938 (and (looking-at "[ \t]*$")
22939 org-todo-line-regexp
22940 (save-excursion
22941 (beginning-of-line)
22942 (looking-at org-todo-line-regexp)
22943 (string= (match-string 3) "")))))
22945 (defun org-at-heading-or-item-p ()
22946 (or (org-at-heading-p) (org-at-item-p)))
22948 (defun org-at-target-p ()
22949 (or (org-in-regexp org-radio-target-regexp)
22950 (org-in-regexp org-target-regexp)))
22951 ;; Compatibility alias with Org versions < 7.8.03
22952 (defalias 'org-on-target-p 'org-at-target-p)
22954 (defun org-up-heading-all (arg)
22955 "Move to the heading line of which the present line is a subheading.
22956 This function considers both visible and invisible heading lines.
22957 With argument, move up ARG levels."
22958 (outline-up-heading arg t))
22960 (defun org-up-heading-safe ()
22961 "Move to the heading line of which the present line is a subheading.
22962 This version will not throw an error. It will return the level of the
22963 headline found, or nil if no higher level is found.
22965 Also, this function will be a lot faster than `outline-up-heading',
22966 because it relies on stars being the outline starters. This can really
22967 make a significant difference in outlines with very many siblings."
22968 (when (ignore-errors (org-back-to-heading t))
22969 (let ((level-up (1- (funcall outline-level))))
22970 (and (> level-up 0)
22971 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
22972 (funcall outline-level)))))
22974 (defun org-first-sibling-p ()
22975 "Is this heading the first child of its parents?"
22976 (interactive)
22977 (let ((re org-outline-regexp-bol)
22978 level l)
22979 (unless (org-at-heading-p t)
22980 (user-error "Not at a heading"))
22981 (setq level (funcall outline-level))
22982 (save-excursion
22983 (if (not (re-search-backward re nil t))
22985 (setq l (funcall outline-level))
22986 (< l level)))))
22988 (defun org-goto-sibling (&optional previous)
22989 "Goto the next sibling, even if it is invisible.
22990 When PREVIOUS is set, go to the previous sibling instead. Returns t
22991 when a sibling was found. When none is found, return nil and don't
22992 move point."
22993 (let ((fun (if previous 're-search-backward 're-search-forward))
22994 (pos (point))
22995 (re org-outline-regexp-bol)
22996 level l)
22997 (when (ignore-errors (org-back-to-heading t))
22998 (setq level (funcall outline-level))
22999 (catch 'exit
23000 (or previous (forward-char 1))
23001 (while (funcall fun re nil t)
23002 (setq l (funcall outline-level))
23003 (when (< l level) (goto-char pos) (throw 'exit nil))
23004 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23005 (goto-char pos)
23006 nil))))
23008 (defun org-show-siblings ()
23009 "Show all siblings of the current headline."
23010 (save-excursion
23011 (while (org-goto-sibling) (org-flag-heading nil)))
23012 (save-excursion
23013 (while (org-goto-sibling 'previous)
23014 (org-flag-heading nil))))
23016 (defun org-goto-first-child ()
23017 "Goto the first child, even if it is invisible.
23018 Return t when a child was found. Otherwise don't move point and
23019 return nil."
23020 (let (level (pos (point)) (re org-outline-regexp-bol))
23021 (when (ignore-errors (org-back-to-heading t))
23022 (setq level (outline-level))
23023 (forward-char 1)
23024 (if (and (re-search-forward re nil t) (> (outline-level) level))
23025 (progn (goto-char (match-beginning 0)) t)
23026 (goto-char pos) nil))))
23028 (defun org-show-hidden-entry ()
23029 "Show an entry where even the heading is hidden."
23030 (save-excursion
23031 (org-show-entry)))
23033 (defun org-flag-heading (flag &optional entry)
23034 "Flag the current heading. FLAG non-nil means make invisible.
23035 When ENTRY is non-nil, show the entire entry."
23036 (save-excursion
23037 (org-back-to-heading t)
23038 ;; Check if we should show the entire entry
23039 (if (not entry)
23040 (org-flag-region
23041 (line-end-position 0) (line-end-position) flag 'outline)
23042 (org-show-entry)
23043 (save-excursion
23044 (and (outline-next-heading)
23045 (org-flag-heading nil))))))
23047 (defun org-get-next-sibling ()
23048 "Move to next heading of the same level, and return point.
23049 If there is no such heading, return nil.
23050 This is like outline-next-sibling, but invisible headings are ok."
23051 (let ((level (funcall outline-level)))
23052 (outline-next-heading)
23053 (while (and (not (eobp)) (> (funcall outline-level) level))
23054 (outline-next-heading))
23055 (unless (or (eobp) (< (funcall outline-level) level))
23056 (point))))
23058 (defun org-get-last-sibling ()
23059 "Move to previous heading of the same level, and return point.
23060 If there is no such heading, return nil."
23061 (let ((opoint (point))
23062 (level (funcall outline-level)))
23063 (outline-previous-heading)
23064 (when (and (/= (point) opoint) (outline-on-heading-p t))
23065 (while (and (> (funcall outline-level) level)
23066 (not (bobp)))
23067 (outline-previous-heading))
23068 (unless (< (funcall outline-level) level)
23069 (point)))))
23071 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23072 "Goto to the end of a subtree."
23073 ;; This contains an exact copy of the original function, but it uses
23074 ;; `org-back-to-heading', to make it work also in invisible
23075 ;; trees. And is uses an invisible-ok argument.
23076 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23077 ;; Furthermore, when used inside Org, finding the end of a large subtree
23078 ;; with many children and grandchildren etc, this can be much faster
23079 ;; than the outline version.
23080 (org-back-to-heading invisible-ok)
23081 (let ((first t)
23082 (level (funcall outline-level)))
23083 (if (and (derived-mode-p 'org-mode) (< level 1000))
23084 ;; A true heading (not a plain list item), in Org
23085 ;; This means we can easily find the end by looking
23086 ;; only for the right number of stars. Using a regexp to do
23087 ;; this is so much faster than using a Lisp loop.
23088 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23089 (forward-char 1)
23090 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23091 ;; something else, do it the slow way
23092 (while (and (not (eobp))
23093 (or first (> (funcall outline-level) level)))
23094 (setq first nil)
23095 (outline-next-heading)))
23096 (unless to-heading
23097 (when (memq (preceding-char) '(?\n ?\^M))
23098 ;; Go to end of line before heading
23099 (forward-char -1)
23100 (when (memq (preceding-char) '(?\n ?\^M))
23101 ;; leave blank line before heading
23102 (forward-char -1)))))
23103 (point))
23105 (defun org-end-of-meta-data (&optional full)
23106 "Skip planning line and properties drawer in current entry.
23107 When optional argument FULL is non-nil, also skip empty lines,
23108 clocking lines and regular drawers at the beginning of the
23109 entry."
23110 (org-back-to-heading t)
23111 (forward-line)
23112 (when (looking-at-p org-planning-line-re) (forward-line))
23113 (when (looking-at org-property-drawer-re)
23114 (goto-char (match-end 0))
23115 (forward-line))
23116 (when (and full (not (org-at-heading-p)))
23117 (catch 'exit
23118 (let ((end (save-excursion (outline-next-heading) (point)))
23119 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23120 (while (not (eobp))
23121 (cond ((looking-at-p org-drawer-regexp)
23122 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23123 (forward-line)
23124 (throw 'exit t)))
23125 ((looking-at-p re) (forward-line))
23126 (t (throw 'exit t))))))))
23128 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23129 "Move forward to the ARG'th subheading at same level as this one.
23130 Stop at the first and last subheadings of a superior heading.
23131 Normally this only looks at visible headings, but when INVISIBLE-OK is
23132 non-nil it will also look at invisible ones."
23133 (interactive "p")
23134 (let ((backward? (and arg (< arg 0))))
23135 (if (org-before-first-heading-p)
23136 (if backward? (goto-char (point-min)) (outline-next-heading))
23137 (org-back-to-heading invisible-ok)
23138 (unless backward? (end-of-line)) ;do not match current headline
23139 (let ((level (- (match-end 0) (match-beginning 0) 1))
23140 (f (if backward? #'re-search-backward #'re-search-forward))
23141 (count (if arg (abs arg) 1))
23142 (result (point)))
23143 (while (and (> count 0)
23144 (funcall f org-outline-regexp-bol nil 'move))
23145 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23146 (cond ((< l level) (setq count 0))
23147 ((and (= l level)
23148 (or invisible-ok
23149 (not (org-invisible-p
23150 (line-beginning-position)))))
23151 (cl-decf count)
23152 (when (= l level) (setq result (point)))))))
23153 (goto-char result))
23154 (beginning-of-line))))
23156 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23157 "Move backward to the ARG'th subheading at same level as this one.
23158 Stop at the first and last subheadings of a superior heading."
23159 (interactive "p")
23160 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23162 (defun org-next-visible-heading (arg)
23163 "Move to the next visible heading.
23165 This function wraps `outline-next-visible-heading' with
23166 `org-with-limited-levels' in order to skip over inline tasks and
23167 respect customization of `org-odd-levels-only'."
23168 (interactive "p")
23169 (org-with-limited-levels
23170 (outline-next-visible-heading arg)))
23172 (defun org-previous-visible-heading (arg)
23173 "Move to the previous visible heading.
23175 This function wraps `outline-previous-visible-heading' with
23176 `org-with-limited-levels' in order to skip over inline tasks and
23177 respect customization of `org-odd-levels-only'."
23178 (interactive "p")
23179 (org-with-limited-levels
23180 (outline-previous-visible-heading arg)))
23182 (defun org-forward-paragraph ()
23183 "Move forward to beginning of next paragraph or equivalent.
23185 The function moves point to the beginning of the next visible
23186 structural element, which can be a paragraph, a table, a list
23187 item, etc. It also provides some special moves for convenience:
23189 - On an affiliated keyword, jump to the beginning of the
23190 relative element.
23191 - On an item or a footnote definition, move to the second
23192 element inside, if any.
23193 - On a table or a property drawer, jump after it.
23194 - On a verse or source block, stop after blank lines."
23195 (interactive)
23196 (unless (eobp)
23197 (let* ((deactivate-mark nil)
23198 (element (org-element-at-point))
23199 (type (org-element-type element))
23200 (post-affiliated (org-element-property :post-affiliated element))
23201 (contents-begin (org-element-property :contents-begin element))
23202 (contents-end (org-element-property :contents-end element))
23203 (end (let ((end (org-element-property :end element)) (parent element))
23204 (while (and (setq parent (org-element-property :parent parent))
23205 (= (org-element-property :contents-end parent) end))
23206 (setq end (org-element-property :end parent)))
23207 end)))
23208 (cond ((not element)
23209 (skip-chars-forward " \r\t\n")
23210 (or (eobp) (beginning-of-line)))
23211 ;; On affiliated keywords, move to element's beginning.
23212 ((< (point) post-affiliated)
23213 (goto-char post-affiliated))
23214 ;; At a table row, move to the end of the table. Similarly,
23215 ;; at a node property, move to the end of the property
23216 ;; drawer.
23217 ((memq type '(node-property table-row))
23218 (goto-char (org-element-property
23219 :end (org-element-property :parent element))))
23220 ((memq type '(property-drawer table)) (goto-char end))
23221 ;; Consider blank lines as separators in verse and source
23222 ;; blocks to ease editing.
23223 ((memq type '(src-block verse-block))
23224 (when (eq type 'src-block)
23225 (setq contents-end
23226 (save-excursion (goto-char end)
23227 (skip-chars-backward " \r\t\n")
23228 (line-beginning-position))))
23229 (beginning-of-line)
23230 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23231 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23232 (goto-char end)
23233 (skip-chars-forward " \r\t\n")
23234 (if (= (point) contents-end) (goto-char end)
23235 (beginning-of-line))))
23236 ;; With no contents, just skip element.
23237 ((not contents-begin) (goto-char end))
23238 ;; If contents are invisible, skip the element altogether.
23239 ((org-invisible-p (line-end-position))
23240 (cl-case type
23241 (headline
23242 (org-with-limited-levels (outline-next-visible-heading 1)))
23243 ;; At a plain list, make sure we move to the next item
23244 ;; instead of skipping the whole list.
23245 (plain-list (forward-char)
23246 (org-forward-paragraph))
23247 (otherwise (goto-char end))))
23248 ((>= (point) contents-end) (goto-char end))
23249 ((>= (point) contents-begin)
23250 ;; This can only happen on paragraphs and plain lists.
23251 (cl-case type
23252 (paragraph (goto-char end))
23253 ;; At a plain list, try to move to second element in
23254 ;; first item, if possible.
23255 (plain-list (end-of-line)
23256 (org-forward-paragraph))))
23257 ;; When contents start on the middle of a line (e.g. in
23258 ;; items and footnote definitions), try to reach first
23259 ;; element starting after current line.
23260 ((> (line-end-position) contents-begin)
23261 (end-of-line)
23262 (org-forward-paragraph))
23263 (t (goto-char contents-begin))))))
23265 (defun org-backward-paragraph ()
23266 "Move backward to start of previous paragraph or equivalent.
23268 The function moves point to the beginning of the current
23269 structural element, which can be a paragraph, a table, a list
23270 item, etc., or to the beginning of the previous visible one if
23271 point is already there. It also provides some special moves for
23272 convenience:
23274 - On an affiliated keyword, jump to the first one.
23275 - On a table or a property drawer, move to its beginning.
23276 - On comment, example, export, src and verse blocks, stop
23277 before blank lines."
23278 (interactive)
23279 (unless (bobp)
23280 (let* ((deactivate-mark nil)
23281 (element (org-element-at-point))
23282 (type (org-element-type element))
23283 (contents-end (org-element-property :contents-end element))
23284 (post-affiliated (org-element-property :post-affiliated element))
23285 (begin (org-element-property :begin element))
23286 (special? ;blocks handled specially
23287 (memq type '(comment-block example-block export-block src-block
23288 verse-block)))
23289 (contents-begin
23290 (if special?
23291 ;; These types have no proper contents. Fake line
23292 ;; below the block opening line as contents beginning.
23293 (save-excursion (goto-char begin) (line-beginning-position 2))
23294 (org-element-property :contents-begin element))))
23295 (cond
23296 ((not element) (goto-char (point-min)))
23297 ((= (point) begin)
23298 (backward-char)
23299 (org-backward-paragraph))
23300 ((<= (point) post-affiliated) (goto-char begin))
23301 ;; Special behavior: on a table or a property drawer, move to
23302 ;; its beginning.
23303 ((memq type '(node-property table-row))
23304 (goto-char (org-element-property
23305 :post-affiliated (org-element-property :parent element))))
23306 (special?
23307 (if (<= (point) contents-begin) (goto-char post-affiliated)
23308 ;; Inside a verse block, see blank lines as paragraph
23309 ;; separators.
23310 (let ((origin (point)))
23311 (skip-chars-backward " \r\t\n" contents-begin)
23312 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23313 (skip-chars-forward " \r\t\n" origin)
23314 (if (= (point) origin) (goto-char contents-begin)
23315 (beginning-of-line))))))
23316 ((eq type 'paragraph) (goto-char contents-begin)
23317 ;; When at first paragraph in an item or a footnote definition,
23318 ;; move directly to beginning of line.
23319 (let ((parent-contents
23320 (org-element-property
23321 :contents-begin (org-element-property :parent element))))
23322 (when (and parent-contents (= parent-contents contents-begin))
23323 (beginning-of-line))))
23324 ;; At the end of a greater element, move to the beginning of
23325 ;; the last element within.
23326 ((and contents-end (>= (point) contents-end))
23327 (goto-char (1- contents-end))
23328 (org-backward-paragraph))
23329 (t (goto-char (or post-affiliated begin))))
23330 ;; Ensure we never leave point invisible.
23331 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23333 (defun org-forward-element ()
23334 "Move forward by one element.
23335 Move to the next element at the same level, when possible."
23336 (interactive)
23337 (cond ((eobp) (user-error "Cannot move further down"))
23338 ((org-with-limited-levels (org-at-heading-p))
23339 (let ((origin (point)))
23340 (goto-char (org-end-of-subtree nil t))
23341 (unless (org-with-limited-levels (org-at-heading-p))
23342 (goto-char origin)
23343 (user-error "Cannot move further down"))))
23345 (let* ((elem (org-element-at-point))
23346 (end (org-element-property :end elem))
23347 (parent (org-element-property :parent elem)))
23348 (cond ((and parent (= (org-element-property :contents-end parent) end))
23349 (goto-char (org-element-property :end parent)))
23350 ((integer-or-marker-p end) (goto-char end))
23351 (t (message "No element at point")))))))
23353 (defun org-backward-element ()
23354 "Move backward by one element.
23355 Move to the previous element at the same level, when possible."
23356 (interactive)
23357 (cond ((bobp) (user-error "Cannot move further up"))
23358 ((org-with-limited-levels (org-at-heading-p))
23359 ;; At a headline, move to the previous one, if any, or stay
23360 ;; here.
23361 (let ((origin (point)))
23362 (org-with-limited-levels (org-backward-heading-same-level 1))
23363 ;; When current headline has no sibling above, move to its
23364 ;; parent.
23365 (when (= (point) origin)
23366 (or (org-with-limited-levels (org-up-heading-safe))
23367 (progn (goto-char origin)
23368 (user-error "Cannot move further up"))))))
23370 (let* ((elem (org-element-at-point))
23371 (beg (org-element-property :begin elem)))
23372 (cond
23373 ;; Move to beginning of current element if point isn't
23374 ;; there already.
23375 ((null beg) (message "No element at point"))
23376 ((/= (point) beg) (goto-char beg))
23377 (t (goto-char beg)
23378 (skip-chars-backward " \r\t\n")
23379 (unless (bobp)
23380 (let ((prev (org-element-at-point)))
23381 (goto-char (org-element-property :begin prev))
23382 (while (and (setq prev (org-element-property :parent prev))
23383 (<= (org-element-property :end prev) beg))
23384 (goto-char (org-element-property :begin prev)))))))))))
23386 (defun org-up-element ()
23387 "Move to upper element."
23388 (interactive)
23389 (if (org-with-limited-levels (org-at-heading-p))
23390 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23391 (let* ((elem (org-element-at-point))
23392 (parent (org-element-property :parent elem)))
23393 (if parent (goto-char (org-element-property :begin parent))
23394 (if (org-with-limited-levels (org-before-first-heading-p))
23395 (user-error "No surrounding element")
23396 (org-with-limited-levels (org-back-to-heading)))))))
23398 (defun org-down-element ()
23399 "Move to inner element."
23400 (interactive)
23401 (let ((element (org-element-at-point)))
23402 (cond
23403 ((memq (org-element-type element) '(plain-list table))
23404 (goto-char (org-element-property :contents-begin element))
23405 (forward-char))
23406 ((memq (org-element-type element) org-element-greater-elements)
23407 ;; If contents are hidden, first disclose them.
23408 (when (org-invisible-p (line-end-position)) (org-cycle))
23409 (goto-char (or (org-element-property :contents-begin element)
23410 (user-error "No content for this element"))))
23411 (t (user-error "No inner element")))))
23413 (defun org-drag-element-backward ()
23414 "Move backward element at point."
23415 (interactive)
23416 (let ((elem (or (org-element-at-point)
23417 (user-error "No element at point"))))
23418 (if (eq (org-element-type elem) 'headline)
23419 ;; Preserve point when moving a whole tree, even if point was
23420 ;; on blank lines below the headline.
23421 (let ((offset (skip-chars-backward " \t\n")))
23422 (unwind-protect (org-move-subtree-up)
23423 (forward-char (- offset))))
23424 (let ((prev-elem
23425 (save-excursion
23426 (goto-char (org-element-property :begin elem))
23427 (skip-chars-backward " \r\t\n")
23428 (unless (bobp)
23429 (let* ((beg (org-element-property :begin elem))
23430 (prev (org-element-at-point))
23431 (up prev))
23432 (while (and (setq up (org-element-property :parent up))
23433 (<= (org-element-property :end up) beg))
23434 (setq prev up))
23435 prev)))))
23436 ;; Error out if no previous element or previous element is
23437 ;; a parent of the current one.
23438 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23439 (user-error "Cannot drag element backward")
23440 (let ((pos (point)))
23441 (org-element-swap-A-B prev-elem elem)
23442 (goto-char (+ (org-element-property :begin prev-elem)
23443 (- pos (org-element-property :begin elem))))))))))
23445 (defun org-drag-element-forward ()
23446 "Move forward element at point."
23447 (interactive)
23448 (let* ((pos (point))
23449 (elem (or (org-element-at-point)
23450 (user-error "No element at point"))))
23451 (when (= (point-max) (org-element-property :end elem))
23452 (user-error "Cannot drag element forward"))
23453 (goto-char (org-element-property :end elem))
23454 (let ((next-elem (org-element-at-point)))
23455 (when (or (org-element-nested-p elem next-elem)
23456 (and (eq (org-element-type next-elem) 'headline)
23457 (not (eq (org-element-type elem) 'headline))))
23458 (goto-char pos)
23459 (user-error "Cannot drag element forward"))
23460 ;; Compute new position of point: it's shifted by NEXT-ELEM
23461 ;; body's length (without final blanks) and by the length of
23462 ;; blanks between ELEM and NEXT-ELEM.
23463 (let ((size-next (- (save-excursion
23464 (goto-char (org-element-property :end next-elem))
23465 (skip-chars-backward " \r\t\n")
23466 (forward-line)
23467 ;; Small correction if buffer doesn't end
23468 ;; with a newline character.
23469 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23470 (org-element-property :begin next-elem)))
23471 (size-blank (- (org-element-property :end elem)
23472 (save-excursion
23473 (goto-char (org-element-property :end elem))
23474 (skip-chars-backward " \r\t\n")
23475 (forward-line)
23476 (point)))))
23477 (org-element-swap-A-B elem next-elem)
23478 (goto-char (+ pos size-next size-blank))))))
23480 (defun org-drag-line-forward (arg)
23481 "Drag the line at point ARG lines forward."
23482 (interactive "p")
23483 (dotimes (_ (abs arg))
23484 (let ((c (current-column)))
23485 (if (< 0 arg)
23486 (progn
23487 (beginning-of-line 2)
23488 (transpose-lines 1)
23489 (beginning-of-line 0))
23490 (transpose-lines 1)
23491 (beginning-of-line -1))
23492 (org-move-to-column c))))
23494 (defun org-drag-line-backward (arg)
23495 "Drag the line at point ARG lines backward."
23496 (interactive "p")
23497 (org-drag-line-forward (- arg)))
23499 (defun org-mark-element ()
23500 "Put point at beginning of this element, mark at end.
23502 Interactively, if this command is repeated or (in Transient Mark
23503 mode) if the mark is active, it marks the next element after the
23504 ones already marked."
23505 (interactive)
23506 (let (deactivate-mark)
23507 (if (and (called-interactively-p 'any)
23508 (or (and (eq last-command this-command) (mark t))
23509 (and transient-mark-mode mark-active)))
23510 (set-mark
23511 (save-excursion
23512 (goto-char (mark))
23513 (goto-char (org-element-property :end (org-element-at-point)))))
23514 (let ((element (org-element-at-point)))
23515 (end-of-line)
23516 (push-mark (org-element-property :end element) t t)
23517 (goto-char (org-element-property :begin element))))))
23519 (defun org-narrow-to-element ()
23520 "Narrow buffer to current element."
23521 (interactive)
23522 (let ((elem (org-element-at-point)))
23523 (cond
23524 ((eq (car elem) 'headline)
23525 (narrow-to-region
23526 (org-element-property :begin elem)
23527 (org-element-property :end elem)))
23528 ((memq (car elem) org-element-greater-elements)
23529 (narrow-to-region
23530 (org-element-property :contents-begin elem)
23531 (org-element-property :contents-end elem)))
23533 (narrow-to-region
23534 (org-element-property :begin elem)
23535 (org-element-property :end elem))))))
23537 (defun org-transpose-element ()
23538 "Transpose current and previous elements, keeping blank lines between.
23539 Point is moved after both elements."
23540 (interactive)
23541 (org-skip-whitespace)
23542 (let ((end (org-element-property :end (org-element-at-point))))
23543 (org-drag-element-backward)
23544 (goto-char end)))
23546 (defun org-unindent-buffer ()
23547 "Un-indent the visible part of the buffer.
23548 Relative indentation (between items, inside blocks, etc.) isn't
23549 modified."
23550 (interactive)
23551 (unless (eq major-mode 'org-mode)
23552 (user-error "Cannot un-indent a buffer not in Org mode"))
23553 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23554 (unindent-tree
23555 (lambda (contents)
23556 (dolist (element (reverse contents))
23557 (if (memq (org-element-type element) '(headline section))
23558 (funcall unindent-tree (org-element-contents element))
23559 (save-excursion
23560 (save-restriction
23561 (narrow-to-region
23562 (org-element-property :begin element)
23563 (org-element-property :end element))
23564 (org-do-remove-indentation))))))))
23565 (funcall unindent-tree (org-element-contents parse-tree))))
23567 (defun org-make-options-regexp (kwds &optional extra)
23568 "Make a regular expression for keyword lines.
23569 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23570 when non-nil, is a regexp matching keywords names."
23571 (concat "^[ \t]*#\\+\\("
23572 (regexp-opt kwds)
23573 (and extra (concat (and kwds "\\|") extra))
23574 "\\):[ \t]*\\(.*\\)"))
23577 ;;; Finish up
23579 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23580 (lambda () (add-hook 'change-major-mode-hook
23581 'org-show-all 'append 'local)))
23583 (provide 'org)
23585 (run-hooks 'org-load-hook)
23587 ;;; org.el ends here