Merge branch 'agenda-subtree-kill-with-subtree-feedback'
[org-mode/org-tableheadings.git] / lisp / org.el
blobdb025a1572d807bd9e9ec28a4b504d074f6858b9
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-2019 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.3
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 org-inlinetask-min-level)
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (eval-and-compile (require 'org-macs))
92 (require 'org-compat)
93 (require 'org-keys)
94 (require 'ol)
95 (require 'org-table)
97 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
98 ;; some places -- e.g. see the macro `org-with-limited-levels'.
99 (defvar org-outline-regexp "\\*+ "
100 "Regexp to match Org headlines.")
102 (defvar org-outline-regexp-bol "^\\*+ "
103 "Regexp to match Org headlines.
104 This is similar to `org-outline-regexp' but additionally makes
105 sure that we are at the beginning of the line.")
107 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
108 "Matches a headline, putting stars and text into groups.
109 Stars are put in group 1 and the trimmed body in group 2.")
111 (declare-function calendar-check-holidays "holidays" (date))
112 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
113 (declare-function cdlatex-math-symbol "ext:cdlatex")
114 (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
121 (declare-function org-archive-subtree "org-archive" (&optional find-done))
122 (declare-function org-archive-subtree-default "org-archive" ())
123 (declare-function org-archive-to-archive-sibling "org-archive" ())
124 (declare-function org-attach "org-attach" ())
125 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
126 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
127 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
128 (declare-function org-clock-cancel "org-clock" ())
129 (declare-function org-clock-display "org-clock" (&optional arg))
130 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
131 (declare-function org-clock-goto "org-clock" (&optional select))
132 (declare-function org-clock-in "org-clock" (&optional select start-time))
133 (declare-function org-clock-in-last "org-clock" (&optional arg))
134 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
135 (declare-function org-clock-out-if-current "org-clock" ())
136 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
137 (declare-function org-clock-report "org-clock" (&optional arg))
138 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
139 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
140 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
141 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
142 (declare-function org-clock-update-time-maybe "org-clock" ())
143 (declare-function org-clocking-buffer "org-clock" ())
144 (declare-function org-clocktable-shift "org-clock" (dir n))
145 (declare-function org-columns-insert-dblock "org-colview" ())
146 (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
147 (declare-function org-element-at-point "org-element" ())
148 (declare-function org-element-cache-refresh "org-element" (pos))
149 (declare-function org-element-cache-reset "org-element" (&optional all))
150 (declare-function org-element-contents "org-element" (element))
151 (declare-function org-element-context "org-element" (&optional element))
152 (declare-function org-element-copy "org-element" (datum))
153 (declare-function org-element-create "org-element" (type &optional props &rest children))
154 (declare-function org-element-interpret-data "org-element" (data))
155 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
156 (declare-function org-element-link-parser "org-element" ())
157 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
158 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
159 (declare-function org-element-property "org-element" (property element))
160 (declare-function org-element-put-property "org-element" (element property value))
161 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
162 (declare-function org-element-timestamp-parser "org-element" ())
163 (declare-function org-element-type "org-element" (element))
164 (declare-function org-export-dispatch "ox" (&optional arg))
165 (declare-function org-export-get-backend "ox" (name))
166 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
167 (declare-function org-feed-goto-inbox "org-feed" (feed))
168 (declare-function org-feed-update-all "org-feed" ())
169 (declare-function org-goto "org-goto" (&optional alternative-interface))
170 (declare-function org-id-find-id-file "org-id" (id))
171 (declare-function org-id-get-create "org-id" (&optional force))
172 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
173 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
174 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
175 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
176 (declare-function org-plot/gnuplot "org-plot" (&optional params))
177 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
178 (declare-function org-timer "org-timer" (&optional restart no-insert))
179 (declare-function org-timer-item "org-timer" (&optional arg))
180 (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
181 (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
182 (declare-function org-timer-set-timer "org-timer" (&optional opt))
183 (declare-function org-timer-start "org-timer" (&optional offset))
184 (declare-function org-timer-stop "org-timer" ())
185 (declare-function org-timer-stop "org-timer" ())
186 (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
187 (declare-function org-update-radio-target-regexp "ol" ())
189 (defvar ffap-url-regexp)
190 (defvar org-element-paragraph-separate)
191 (defvar org-indent-indentation-per-level)
192 (defvar org-radio-target-regexp)
193 (defvar org-target-link-regexp)
194 (defvar org-target-regexp)
196 ;; load languages based on value of `org-babel-load-languages'
197 (defvar org-babel-load-languages)
199 ;;;###autoload
200 (defun org-babel-do-load-languages (sym value)
201 "Load the languages defined in `org-babel-load-languages'."
202 (set-default sym value)
203 (dolist (pair org-babel-load-languages)
204 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
205 (if active
206 (require (intern (concat "ob-" lang)))
207 (fmakunbound
208 (intern (concat "org-babel-execute:" lang)))
209 (fmakunbound
210 (intern (concat "org-babel-expand-body:" lang)))))))
213 ;;;###autoload
214 (defun org-babel-load-file (file &optional compile)
215 "Load Emacs Lisp source code blocks in the Org FILE.
216 This function exports the source code using `org-babel-tangle'
217 and then loads the resulting file using `load-file'. With
218 optional prefix argument COMPILE, the tangled Emacs Lisp file is
219 byte-compiled before it is loaded."
220 (interactive "fFile to load: \nP")
221 (let* ((tangled-file (concat (file-name-sans-extension file) ".el")))
222 ;; Tangle only if the Org file is newer than the Elisp file.
223 (unless (org-file-newer-than-p
224 tangled-file
225 (file-attribute-modification-time (file-attributes file)))
226 (org-babel-tangle-file file tangled-file "emacs-lisp"))
227 (if compile
228 (progn
229 (byte-compile-file tangled-file 'load)
230 (message "Compiled and loaded %s" tangled-file))
231 (load-file tangled-file)
232 (message "Loaded %s" tangled-file))))
234 (defcustom org-babel-load-languages '((emacs-lisp . t))
235 "Languages which can be evaluated in Org buffers.
236 \\<org-mode-map>
237 This list can be used to load support for any of the languages
238 below. Each language will depend on a different set of system
239 executables and/or Emacs modes.
241 When a language is \"loaded\", code blocks in that language can
242 be evaluated with `org-babel-execute-src-block', which is bound
243 by default to \\[org-ctrl-c-ctrl-c].
245 The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
246 remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
247 default, only Emacs Lisp is loaded, since it has no specific
248 requirement."
249 :group 'org-babel
250 :set 'org-babel-do-load-languages
251 :version "24.1"
252 :type '(alist :tag "Babel Languages"
253 :key-type
254 (choice
255 (const :tag "Awk" awk)
256 (const :tag "C" C)
257 (const :tag "R" R)
258 (const :tag "Asymptote" asymptote)
259 (const :tag "Calc" calc)
260 (const :tag "Clojure" clojure)
261 (const :tag "CSS" css)
262 (const :tag "Ditaa" ditaa)
263 (const :tag "Dot" dot)
264 (const :tag "Ebnf2ps" ebnf2ps)
265 (const :tag "Emacs Lisp" emacs-lisp)
266 (const :tag "Forth" forth)
267 (const :tag "Fortran" fortran)
268 (const :tag "Gnuplot" gnuplot)
269 (const :tag "Haskell" haskell)
270 (const :tag "hledger" hledger)
271 (const :tag "IO" io)
272 (const :tag "J" J)
273 (const :tag "Java" java)
274 (const :tag "Javascript" js)
275 (const :tag "LaTeX" latex)
276 (const :tag "Ledger" ledger)
277 (const :tag "Lilypond" lilypond)
278 (const :tag "Lisp" lisp)
279 (const :tag "Makefile" makefile)
280 (const :tag "Maxima" maxima)
281 (const :tag "Matlab" matlab)
282 (const :tag "Mscgen" mscgen)
283 (const :tag "Ocaml" ocaml)
284 (const :tag "Octave" octave)
285 (const :tag "Org" org)
286 (const :tag "Perl" perl)
287 (const :tag "Pico Lisp" picolisp)
288 (const :tag "PlantUML" plantuml)
289 (const :tag "Python" python)
290 (const :tag "Ruby" ruby)
291 (const :tag "Sass" sass)
292 (const :tag "Scala" scala)
293 (const :tag "Scheme" scheme)
294 (const :tag "Screen" screen)
295 (const :tag "Shell Script" shell)
296 (const :tag "Shen" shen)
297 (const :tag "Sql" sql)
298 (const :tag "Sqlite" sqlite)
299 (const :tag "Stan" stan)
300 (const :tag "Vala" vala))
301 :value-type (boolean :tag "Activate" :value t)))
303 ;;;; Customization variables
304 (defcustom org-clone-delete-id nil
305 "Remove ID property of clones of a subtree.
306 When non-nil, clones of a subtree don't inherit the ID property.
307 Otherwise they inherit the ID property with a new unique
308 identifier."
309 :type 'boolean
310 :version "24.1"
311 :group 'org-id)
313 ;;; Version
314 (org-check-version)
316 ;;;###autoload
317 (defun org-version (&optional here full message)
318 "Show the Org version.
319 Interactively, or when MESSAGE is non-nil, show it in echo area.
320 With prefix argument, or when HERE is non-nil, insert it at point.
321 In non-interactive uses, a reduced version string is output unless
322 FULL is given."
323 (interactive (list current-prefix-arg t (not current-prefix-arg)))
324 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
325 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
326 (load-suffixes (list ".el"))
327 (org-install-dir
328 (ignore-errors (org-find-library-dir "org-loaddefs"))))
329 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
330 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
331 (let* ((load-suffixes save-load-suffixes)
332 (release (org-release))
333 (git-version (org-git-version))
334 (version (format "Org mode version %s (%s @ %s)"
335 release
336 git-version
337 (if org-install-dir
338 (if (string= org-dir org-install-dir)
339 org-install-dir
340 (concat "mixed installation! "
341 org-install-dir
342 " and "
343 org-dir))
344 "org-loaddefs.el can not be found!")))
345 (version1 (if full version release)))
346 (when here (insert version1))
347 (when message (message "%s" version1))
348 version1)))
350 (defconst org-version (org-version))
353 ;;; Syntax Constants
355 ;;;; Block
357 (defconst org-block-regexp
358 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
359 "Regular expression for hiding blocks.")
361 (defconst org-dblock-start-re
362 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
363 "Matches the start line of a dynamic block, with parameters.")
365 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
366 "Matches the end of a dynamic block.")
368 ;;;; Clock and Planning
370 (defconst org-clock-string "CLOCK:"
371 "String used as prefix for timestamps clocking work hours on an item.")
373 (defvar org-closed-string "CLOSED:"
374 "String used as the prefix for timestamps logging closing a TODO entry.")
376 (defvar org-deadline-string "DEADLINE:"
377 "String to mark deadline entries.
378 \\<org-mode-map>
379 A deadline is this string, followed by a time stamp. It must be
380 a word, terminated by a colon. You can insert a schedule keyword
381 and a timestamp with `\\[org-deadline]'.")
383 (defvar org-scheduled-string "SCHEDULED:"
384 "String to mark scheduled TODO entries.
385 \\<org-mode-map>
386 A schedule is this string, followed by a time stamp. It must be
387 a word, terminated by a colon. You can insert a schedule keyword
388 and a timestamp with `\\[org-schedule]'.")
390 (defconst org-ds-keyword-length
391 (+ 2
392 (apply #'max
393 (mapcar #'length
394 (list org-deadline-string org-scheduled-string
395 org-clock-string org-closed-string))))
396 "Maximum length of the DEADLINE and SCHEDULED keywords.")
398 (defconst org-planning-line-re
399 (concat "^[ \t]*"
400 (regexp-opt
401 (list org-closed-string org-deadline-string org-scheduled-string)
403 "Matches a line with planning info.
404 Matched keyword is in group 1.")
406 (defconst org-clock-line-re
407 (concat "^[ \t]*" org-clock-string)
408 "Matches a line with clock info.")
410 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
411 "Matches the DEADLINE keyword.")
413 (defconst org-deadline-time-regexp
414 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
415 "Matches the DEADLINE keyword together with a time stamp.")
417 (defconst org-deadline-time-hour-regexp
418 (concat "\\<" org-deadline-string
419 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
420 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
422 (defconst org-deadline-line-regexp
423 (concat "\\<\\(" org-deadline-string "\\).*")
424 "Matches the DEADLINE keyword and the rest of the line.")
426 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
427 "Matches the SCHEDULED keyword.")
429 (defconst org-scheduled-time-regexp
430 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
431 "Matches the SCHEDULED keyword together with a time stamp.")
433 (defconst org-scheduled-time-hour-regexp
434 (concat "\\<" org-scheduled-string
435 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
436 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
438 (defconst org-closed-time-regexp
439 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
440 "Matches the CLOSED keyword together with a time stamp.")
442 (defconst org-keyword-time-regexp
443 (concat "\\<"
444 (regexp-opt
445 (list org-scheduled-string org-deadline-string org-closed-string
446 org-clock-string)
448 " *[[<]\\([^]>]+\\)[]>]")
449 "Matches any of the 4 keywords, together with the time stamp.")
451 (defconst org-keyword-time-not-clock-regexp
452 (concat
453 "\\<"
454 (regexp-opt
455 (list org-scheduled-string org-deadline-string org-closed-string) t)
456 " *[[<]\\([^]>]+\\)[]>]")
457 "Matches any of the 3 keywords, together with the time stamp.")
459 (defconst org-maybe-keyword-time-regexp
460 (concat "\\(\\<"
461 (regexp-opt
462 (list org-scheduled-string org-deadline-string org-closed-string
463 org-clock-string)
465 "\\)?"
466 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
467 "\\|"
468 "<%%([^\r\n>]*>\\)")
469 "Matches a timestamp, possibly preceded by a keyword.")
471 (defconst org-all-time-keywords
472 (mapcar (lambda (w) (substring w 0 -1))
473 (list org-scheduled-string org-deadline-string
474 org-clock-string org-closed-string))
475 "List of time keywords.")
477 ;;;; Drawer
479 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
480 "Matches first or last line of a hidden block.
481 Group 1 contains drawer's name or \"END\".")
483 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
484 "Regular expression matching the first line of a property drawer.")
486 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
487 "Regular expression matching the last line of a property drawer.")
489 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
490 "Regular expression matching the first line of a clock drawer.")
492 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
493 "Regular expression matching the last line of a clock drawer.")
495 (defconst org-property-drawer-re
496 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
497 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
498 "[ \t]*:END:[ \t]*$")
499 "Matches an entire property drawer.")
501 (defconst org-clock-drawer-re
502 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
503 org-clock-drawer-end-re "\\)\n?")
504 "Matches an entire clock drawer.")
506 ;;;; Headline
508 (defconst org-heading-keyword-regexp-format
509 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
510 "Printf format for a regexp matching a headline with some keyword.
511 This regexp will match the headline of any node which has the
512 exact keyword that is put into the format. The keyword isn't in
513 any group by default, but the stars and the body are.")
515 (defconst org-heading-keyword-maybe-regexp-format
516 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
517 "Printf format for a regexp matching a headline, possibly with some keyword.
518 This regexp can match any headline with the specified keyword, or
519 without a keyword. The keyword isn't in any group by default,
520 but the stars and the body are.")
522 (defconst org-archive-tag "ARCHIVE"
523 "The tag that marks a subtree as archived.
524 An archived subtree does not open during visibility cycling, and does
525 not contribute to the agenda listings.")
527 (defconst org-tag-re "[[:alnum:]_@#%]+"
528 "Regexp matching a single tag.")
530 (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
531 "Regexp matching the tag group at the end of a line, with leading spaces.
532 Tags are stored in match group 1. Match group 2 stores the tags
533 without the enclosing colons.")
535 (defconst org-tag-line-re
536 "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
537 "Regexp matching tags in a headline.
538 Tags are stored in match group 1. Match group 2 stores the tags
539 without the enclosing colons.")
541 (eval-and-compile
542 (defconst org-comment-string "COMMENT"
543 "Entries starting with this keyword will never be exported.
544 \\<org-mode-map>
545 An entry can be toggled between COMMENT and normal with
546 `\\[org-toggle-comment]'."))
549 ;;;; LaTeX Environments and Fragments
551 (defconst org-latex-regexps
552 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
553 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
554 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
555 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
556 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
557 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
558 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
559 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
560 "Regular expressions for matching embedded LaTeX.")
562 ;;;; Node Property
564 (defconst org-effort-property "Effort"
565 "The property that is being used to keep track of effort estimates.
566 Effort estimates given in this property need to have the format H:MM.")
568 ;;;; Timestamp
570 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
571 "Regular expression for fast time stamp matching.")
573 (defconst org-ts-regexp-inactive
574 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
575 "Regular expression for fast inactive time stamp matching.")
577 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp0
581 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
582 "Regular expression matching time strings for analysis.
583 This one does not require the space after the date, so it can be used
584 on a string that terminates immediately after the date.")
586 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
587 "Regular expression matching time strings for analysis.")
589 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
590 "Regular expression matching time stamps, with groups.")
592 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
593 "Regular expression matching time stamps (also [..]), with groups.")
595 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
596 "Regular expression matching a time stamp range.")
598 (defconst org-tr-regexp-both
599 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
600 "Regular expression matching a time stamp range.")
602 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
603 org-ts-regexp "\\)?")
604 "Regular expression matching a time stamp or time stamp range.")
606 (defconst org-tsr-regexp-both
607 (concat org-ts-regexp-both "\\(--?-?"
608 org-ts-regexp-both "\\)?")
609 "Regular expression matching a time stamp or time stamp range.
610 The time stamps may be either active or inactive.")
612 (defconst org-repeat-re
613 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
614 \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
615 "Regular expression for specifying repeated events.
616 After a match, group 1 contains the repeat expression.")
618 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
619 "Formats for `format-time-string' which are used for time stamps.")
622 ;;; The custom variables
624 (defgroup org nil
625 "Outline-based notes management and organizer."
626 :tag "Org"
627 :group 'outlines
628 :group 'calendar)
630 (defcustom org-mode-hook nil
631 "Mode hook for Org mode, run after the mode was turned on."
632 :group 'org
633 :type 'hook)
635 (defcustom org-load-hook nil
636 "Hook that is run after org.el has been loaded."
637 :group 'org
638 :type 'hook)
640 (defcustom org-log-buffer-setup-hook nil
641 "Hook that is run after an Org log buffer is created."
642 :group 'org
643 :version "24.1"
644 :type 'hook)
646 (defvar org-modules) ; defined below
647 (defvar org-modules-loaded nil
648 "Have the modules been loaded already?")
650 (defun org-load-modules-maybe (&optional force)
651 "Load all extensions listed in `org-modules'."
652 (when (or force (not org-modules-loaded))
653 (dolist (ext org-modules)
654 (condition-case nil (require ext)
655 (error (message "Problems while trying to load feature `%s'" ext))))
656 (setq org-modules-loaded t)))
658 (defun org-set-modules (var value)
659 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
660 (set var value)
661 (when (featurep 'org)
662 (org-load-modules-maybe 'force)
663 (org-element-cache-reset 'all)))
665 (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
666 "Modules that should always be loaded together with org.el.
668 If a description starts with <C>, the file is not part of Emacs
669 and loading it will require that you have downloaded and properly
670 installed the Org mode distribution.
672 You can also use this system to load external packages (i.e. neither Org
673 core modules, nor modules from the CONTRIB directory). Just add symbols
674 to the end of the list. If the package is called org-xyz.el, then you need
675 to add the symbol `xyz', and the package must have a call to:
677 (provide \\='org-xyz)
679 For export specific modules, see also `org-export-backends'."
680 :group 'org
681 :set 'org-set-modules
682 :version "26.1"
683 :package-version '(Org . "9.2")
684 :type
685 '(set :greedy t
686 (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
687 (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
688 (const :tag " crypt: Encryption of subtrees" org-crypt)
689 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
690 (const :tag " docview: Links to Docview buffers" ol-docview)
691 (const :tag " eww: Store link to URL of Eww" ol-eww)
692 (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
693 (const :tag " habit: Track your consistency with habits" org-habit)
694 (const :tag " id: Global IDs for identifying entries" org-id)
695 (const :tag " info: Links to Info nodes" ol-info)
696 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
697 (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
698 (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
699 (const :tag " mouse: Additional mouse support" org-mouse)
700 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
701 (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
702 (const :tag " tempo: Fast completion for structures" org-tempo)
703 (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
704 (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
706 (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
707 (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
708 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
709 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
710 (const :tag "C collector: Collect properties into tables" org-collector)
711 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
712 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
713 (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
714 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
715 (const :tag "C eval: Include command output as text" org-eval)
716 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
717 (const :tag "C git-link: Links to specific file version" ol-git-link)
718 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
719 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
720 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
721 (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
722 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
723 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
724 (const :tag "C man: Links to man pages in Org mode" ol-man)
725 (const :tag "C mew: Links to Mew folders/messages" ol-mew)
726 (const :tag "C notify: Notifications for Org mode" org-notify)
727 (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
728 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
729 (const :tag "C registry: A registry for Org links" org-registry)
730 (const :tag "C screen: Visit screen sessions through links" org-screen)
731 (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
732 (const :tag "C secretary: Team management with Org" org-secretary)
733 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
734 (const :tag "C toc: Table of contents for Org buffer" org-toc)
735 (const :tag "C track: Keep up with Org mode development" org-track)
736 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
737 (const :tag "C vm: Links to VM folders/messages" ol-vm)
738 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
739 (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
740 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
742 (defvar org-export-registered-backends) ; From ox.el.
743 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
744 (declare-function org-export-backend-name "ox" (backend) t)
745 (defcustom org-export-backends '(ascii html icalendar latex odt)
746 "List of export back-ends that should be always available.
748 If a description starts with <C>, the file is not part of Emacs
749 and loading it will require that you have downloaded and properly
750 installed the Org mode distribution.
752 Unlike to `org-modules', libraries in this list will not be
753 loaded along with Org, but only once the export framework is
754 needed.
756 This variable needs to be set before org.el is loaded. If you
757 need to make a change while Emacs is running, use the customize
758 interface or run the following code, where VAL stands for the new
759 value of the variable, after updating it:
761 (progn
762 (setq org-export-registered-backends
763 (cl-remove-if-not
764 (lambda (backend)
765 (let ((name (org-export-backend-name backend)))
766 (or (memq name val)
767 (catch \\='parentp
768 (dolist (b val)
769 (and (org-export-derived-backend-p b name)
770 (throw \\='parentp t)))))))
771 org-export-registered-backends))
772 (let ((new-list (mapcar #\\='org-export-backend-name
773 org-export-registered-backends)))
774 (dolist (backend val)
775 (cond
776 ((not (load (format \"ox-%s\" backend) t t))
777 (message \"Problems while trying to load export back-end \\=`%s\\='\"
778 backend))
779 ((not (memq backend new-list)) (push backend new-list))))
780 (set-default \\='org-export-backends new-list)))
782 Adding a back-end to this list will also pull the back-end it
783 depends on, if any."
784 :group 'org
785 :group 'org-export
786 :version "26.1"
787 :package-version '(Org . "9.0")
788 :initialize 'custom-initialize-set
789 :set (lambda (var val)
790 (if (not (featurep 'ox)) (set-default var val)
791 ;; Any back-end not required anymore (not present in VAL and not
792 ;; a parent of any back-end in the new value) is removed from the
793 ;; list of registered back-ends.
794 (setq org-export-registered-backends
795 (cl-remove-if-not
796 (lambda (backend)
797 (let ((name (org-export-backend-name backend)))
798 (or (memq name val)
799 (catch 'parentp
800 (dolist (b val)
801 (and (org-export-derived-backend-p b name)
802 (throw 'parentp t)))))))
803 org-export-registered-backends))
804 ;; Now build NEW-LIST of both new back-ends and required
805 ;; parents.
806 (let ((new-list (mapcar #'org-export-backend-name
807 org-export-registered-backends)))
808 (dolist (backend val)
809 (cond
810 ((not (load (format "ox-%s" backend) t t))
811 (message "Problems while trying to load export back-end `%s'"
812 backend))
813 ((not (memq backend new-list)) (push backend new-list))))
814 ;; Set VAR to that list with fixed dependencies.
815 (set-default var new-list))))
816 :type '(set :greedy t
817 (const :tag " ascii Export buffer to ASCII format" ascii)
818 (const :tag " beamer Export buffer to Beamer presentation" beamer)
819 (const :tag " html Export buffer to HTML format" html)
820 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
821 (const :tag " latex Export buffer to LaTeX format" latex)
822 (const :tag " man Export buffer to MAN format" man)
823 (const :tag " md Export buffer to Markdown format" md)
824 (const :tag " odt Export buffer to ODT format" odt)
825 (const :tag " org Export buffer to Org format" org)
826 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
827 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
828 (const :tag "C deck Export buffer to deck.js presentations" deck)
829 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
830 (const :tag "C groff Export buffer to Groff format" groff)
831 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
832 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
833 (const :tag "C s5 Export buffer to s5 presentations" s5)
834 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
836 (eval-after-load 'ox
837 '(dolist (backend org-export-backends)
838 (condition-case nil (require (intern (format "ox-%s" backend)))
839 (error (message "Problems while trying to load export back-end `%s'"
840 backend)))))
842 (defcustom org-support-shift-select nil
843 "Non-nil means make shift-cursor commands select text when possible.
844 \\<org-mode-map>\
846 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
847 start selecting a region, or enlarge regions started in this way.
848 In Org mode, in special contexts, these same keys are used for
849 other purposes, important enough to compete with shift selection.
850 Org tries to balance these needs by supporting `shift-select-mode'
851 outside these special contexts, under control of this variable.
853 The default of this variable is nil, to avoid confusing behavior. Shifted
854 cursor keys will then execute Org commands in the following contexts:
855 - on a headline, changing TODO state (left/right) and priority (up/down)
856 - on a time stamp, changing the time
857 - in a plain list item, changing the bullet type
858 - in a property definition line, switching between allowed values
859 - in the BEGIN line of a clock table (changing the time block).
860 Outside these contexts, the commands will throw an error.
862 When this variable is t and the cursor is not in a special
863 context, Org mode will support shift-selection for making and
864 enlarging regions. To make this more effective, the bullet
865 cycling will no longer happen anywhere in an item line, but only
866 if the cursor is exactly on the bullet.
868 If you set this variable to the symbol `always', then the keys
869 will not be special in headlines, property lines, and item lines,
870 to make shift selection work there as well. If this is what you
871 want, you can use the following alternative commands:
872 `\\[org-todo]' and `\\[org-priority]' \
873 to change TODO state and priority,
874 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
875 can be used to switch TODO sets,
876 `\\[org-ctrl-c-minus]' to cycle item bullet types,
877 and properties can be edited by hand or in column view.
879 However, when the cursor is on a timestamp, shift-cursor commands
880 will still edit the time stamp - this is just too good to give up."
881 :group 'org
882 :type '(choice
883 (const :tag "Never" nil)
884 (const :tag "When outside special context" t)
885 (const :tag "Everywhere except timestamps" always)))
887 (defcustom org-loop-over-headlines-in-active-region nil
888 "Shall some commands act upon headlines in the active region?
890 When set to t, some commands will be performed in all headlines
891 within the active region.
893 When set to `start-level', some commands will be performed in all
894 headlines within the active region, provided that these headlines
895 are of the same level than the first one.
897 When set to a string, those commands will be performed on the
898 matching headlines within the active region. Such string must be
899 a tags/property/todo match as it is used in the agenda tags view.
901 The list of commands is: `org-schedule', `org-deadline',
902 `org-todo', `org-set-tags-command', `org-archive-subtree',
903 `org-archive-set-tag', `org-toggle-archive-tag' and
904 `org-archive-to-archive-sibling'. The archiving commands skip
905 already archived entries."
906 :type '(choice (const :tag "Don't loop" nil)
907 (const :tag "All headlines in active region" t)
908 (const :tag "In active region, headlines at the same level than the first one" start-level)
909 (string :tag "Tags/Property/Todo matcher"))
910 :version "24.1"
911 :group 'org-todo
912 :group 'org-archive)
914 (defcustom org-startup-folded t
915 "Non-nil means entering Org mode will switch to OVERVIEW.
917 This can also be configured on a per-file basis by adding one of
918 the following lines anywhere in the buffer:
920 #+STARTUP: fold (or `overview', this is equivalent)
921 #+STARTUP: nofold (or `showall', this is equivalent)
922 #+STARTUP: content
923 #+STARTUP: showeverything
925 Set `org-agenda-inhibit-startup' to a non-nil value if you want
926 to ignore this option when Org opens agenda files for the first
927 time."
928 :group 'org-startup
929 :type '(choice
930 (const :tag "nofold: show all" nil)
931 (const :tag "fold: overview" t)
932 (const :tag "content: all headlines" content)
933 (const :tag "show everything, even drawers" showeverything)))
935 (defcustom org-startup-truncated t
936 "Non-nil means entering Org mode will set `truncate-lines'.
937 This is useful since some lines containing links can be very long and
938 uninteresting. Also tables look terrible when wrapped.
940 The variable `org-startup-truncated' allows to configure
941 truncation for Org mode different to the other modes that use the
942 variable `truncate-lines' and as a shortcut instead of putting
943 the variable `truncate-lines' into the `org-mode-hook'. If one
944 wants to configure truncation for Org mode not statically but
945 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
946 the variable `truncate-lines' has to be used because in such a
947 case it is too late to set the variable `org-startup-truncated'."
948 :group 'org-startup
949 :type 'boolean)
951 (defcustom org-startup-indented nil
952 "Non-nil means turn on `org-indent-mode' on startup.
953 This can also be configured on a per-file basis by adding one of
954 the following lines anywhere in the buffer:
956 #+STARTUP: indent
957 #+STARTUP: noindent"
958 :group 'org-structure
959 :type '(choice
960 (const :tag "Not" nil)
961 (const :tag "Globally (slow on startup in large files)" t)))
963 (defcustom org-use-sub-superscripts t
964 "Non-nil means interpret \"_\" and \"^\" for display.
966 If you want to control how Org exports those characters, see
967 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
968 used to be an alias for `org-export-with-sub-superscripts' in
969 Org <8.0, it is not anymore.
971 When this option is turned on, you can use TeX-like syntax for
972 sub- and superscripts within the buffer. Several characters after
973 \"_\" or \"^\" will be considered as a single item - so grouping
974 with {} is normally not needed. For example, the following things
975 will be parsed as single sub- or superscripts:
977 10^24 or 10^tau several digits will be considered 1 item.
978 10^-12 or 10^-tau a leading sign with digits or a word
979 x^2-y^3 will be read as x^2 - y^3, because items are
980 terminated by almost any nonword/nondigit char.
981 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
983 Still, ambiguity is possible. So when in doubt, use {} to enclose
984 the sub/superscript. If you set this variable to the symbol `{}',
985 the braces are *required* in order to trigger interpretations as
986 sub/superscript. This can be helpful in documents that need \"_\"
987 frequently in plain text."
988 :group 'org-startup
989 :version "24.4"
990 :package-version '(Org . "8.0")
991 :type '(choice
992 (const :tag "Always interpret" t)
993 (const :tag "Only with braces" {})
994 (const :tag "Never interpret" nil)))
996 (defcustom org-startup-with-beamer-mode nil
997 "Non-nil means turn on `org-beamer-mode' on startup.
998 This can also be configured on a per-file basis by adding one of
999 the following lines anywhere in the buffer:
1001 #+STARTUP: beamer"
1002 :group 'org-startup
1003 :version "24.1"
1004 :type 'boolean)
1006 (defcustom org-startup-align-all-tables nil
1007 "Non-nil means align all tables when visiting a file.
1008 This can also be configured on a per-file basis by adding one of
1009 the following lines anywhere in the buffer:
1010 #+STARTUP: align
1011 #+STARTUP: noalign"
1012 :group 'org-startup
1013 :type 'boolean)
1015 (defcustom org-startup-shrink-all-tables nil
1016 "Non-nil means shrink all table columns with a width cookie.
1017 This can also be configured on a per-file basis by adding one of
1018 the following lines anywhere in the buffer:
1019 #+STARTUP: shrink"
1020 :group 'org-startup
1021 :type 'boolean
1022 :version "27.1"
1023 :package-version '(Org . "9.2")
1024 :safe #'booleanp)
1026 (defcustom org-startup-with-inline-images nil
1027 "Non-nil means show inline images when loading a new Org file.
1028 This can also be configured on a per-file basis by adding one of
1029 the following lines anywhere in the buffer:
1030 #+STARTUP: inlineimages
1031 #+STARTUP: noinlineimages"
1032 :group 'org-startup
1033 :version "24.1"
1034 :type 'boolean)
1036 (defcustom org-startup-with-latex-preview nil
1037 "Non-nil means preview LaTeX fragments when loading a new Org file.
1039 This can also be configured on a per-file basis by adding one of
1040 the following lines anywhere in the buffer:
1041 #+STARTUP: latexpreview
1042 #+STARTUP: nolatexpreview"
1043 :group 'org-startup
1044 :version "24.4"
1045 :package-version '(Org . "8.0")
1046 :type 'boolean)
1048 (defcustom org-insert-mode-line-in-empty-file nil
1049 "Non-nil means insert the first line setting Org mode in empty files.
1050 When the function `org-mode' is called interactively in an empty file, this
1051 normally means that the file name does not automatically trigger Org mode.
1052 To ensure that the file will always be in Org mode in the future, a
1053 line enforcing Org mode will be inserted into the buffer, if this option
1054 has been set."
1055 :group 'org-startup
1056 :type 'boolean)
1058 (defcustom org-ellipsis nil
1059 "The ellipsis to use in the Org mode outline.
1061 When nil, just use the standard three dots. When a non-empty string,
1062 use that string instead.
1064 The change affects only Org mode (which will then use its own display table).
1065 Changing this requires executing `\\[org-mode]' in a buffer to become
1066 effective."
1067 :group 'org-startup
1068 :type '(choice (const :tag "Default" nil)
1069 (string :tag "String" :value "...#"))
1070 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1072 (defvar org-display-table nil
1073 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1075 (defgroup org-keywords nil
1076 "Keywords in Org mode."
1077 :tag "Org Keywords"
1078 :group 'org)
1080 (defcustom org-closed-keep-when-no-todo nil
1081 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1082 :group 'org-todo
1083 :group 'org-keywords
1084 :version "24.4"
1085 :package-version '(Org . "8.0")
1086 :type 'boolean)
1088 (defgroup org-structure nil
1089 "Options concerning the general structure of Org files."
1090 :tag "Org Structure"
1091 :group 'org)
1093 (defgroup org-reveal-location nil
1094 "Options about how to make context of a location visible."
1095 :tag "Org Reveal Location"
1096 :group 'org-structure)
1098 (defcustom org-show-context-detail '((agenda . local)
1099 (bookmark-jump . lineage)
1100 (isearch . lineage)
1101 (default . ancestors))
1102 "Alist between context and visibility span when revealing a location.
1104 \\<org-mode-map>Some actions may move point into invisible
1105 locations. As a consequence, Org always expose a neighborhood
1106 around point. How much is shown depends on the initial action,
1107 or context. Valid contexts are
1109 agenda when exposing an entry from the agenda
1110 org-goto when using the command `org-goto' (`\\[org-goto]')
1111 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1112 tags-tree when constructing a sparse tree based on tags matches
1113 link-search when exposing search matches associated with a link
1114 mark-goto when exposing the jump goal of a mark
1115 bookmark-jump when exposing a bookmark location
1116 isearch when exiting from an incremental search
1117 default default for all contexts not set explicitly
1119 Allowed visibility spans are
1121 minimal show current headline; if point is not on headline,
1122 also show entry
1124 local show current headline, entry and next headline
1126 ancestors show current headline and its direct ancestors; if
1127 point is not on headline, also show entry
1129 lineage show current headline, its direct ancestors and all
1130 their children; if point is not on headline, also show
1131 entry and first child
1133 tree show current headline, its direct ancestors and all
1134 their children; if point is not on headline, also show
1135 entry and all children
1137 canonical show current headline, its direct ancestors along with
1138 their entries and children; if point is not located on
1139 the headline, also show current entry and all children
1141 As special cases, a nil or t value means show all contexts in
1142 `minimal' or `canonical' view, respectively.
1144 Some views can make displayed information very compact, but also
1145 make it harder to edit the location of the match. In such
1146 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1147 more context."
1148 :group 'org-reveal-location
1149 :version "26.1"
1150 :package-version '(Org . "9.0")
1151 :type '(choice
1152 (const :tag "Canonical" t)
1153 (const :tag "Minimal" nil)
1154 (repeat :greedy t :tag "Individual contexts"
1155 (cons
1156 (choice :tag "Context"
1157 (const agenda)
1158 (const org-goto)
1159 (const occur-tree)
1160 (const tags-tree)
1161 (const link-search)
1162 (const mark-goto)
1163 (const bookmark-jump)
1164 (const isearch)
1165 (const default))
1166 (choice :tag "Detail level"
1167 (const minimal)
1168 (const local)
1169 (const ancestors)
1170 (const lineage)
1171 (const tree)
1172 (const canonical))))))
1174 (defcustom org-indirect-buffer-display 'other-window
1175 "How should indirect tree buffers be displayed?
1177 This applies to indirect buffers created with the commands
1178 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1180 Valid values are:
1181 current-window Display in the current window
1182 other-window Just display in another window.
1183 dedicated-frame Create one new frame, and re-use it each time.
1184 new-frame Make a new frame each time. Note that in this case
1185 previously-made indirect buffers are kept, and you need to
1186 kill these buffers yourself."
1187 :group 'org-structure
1188 :group 'org-agenda-windows
1189 :type '(choice
1190 (const :tag "In current window" current-window)
1191 (const :tag "In current frame, other window" other-window)
1192 (const :tag "Each time a new frame" new-frame)
1193 (const :tag "One dedicated frame" dedicated-frame)))
1195 (defconst org-file-apps-gnu
1196 '((remote . emacs)
1197 (system . mailcap)
1198 (t . mailcap))
1199 "Default file applications on a UNIX or GNU/Linux system.
1200 See `org-file-apps'.")
1202 (defconst org-file-apps-macos
1203 '((remote . emacs)
1204 (system . "open %s")
1205 ("ps.gz" . "gv %s")
1206 ("eps.gz" . "gv %s")
1207 ("dvi" . "xdvi %s")
1208 ("fig" . "xfig %s")
1209 (t . "open %s"))
1210 "Default file applications on a macOS system.
1211 The system \"open\" is known as a default, but we use X11 applications
1212 for some files for which the OS does not have a good default.
1213 See `org-file-apps'.")
1215 (defconst org-file-apps-windowsnt
1216 (list '(remote . emacs)
1217 (cons 'system (lambda (file _path)
1218 (with-no-warnings (w32-shell-execute "open" file))))
1219 (cons t (lambda (file _path)
1220 (with-no-warnings (w32-shell-execute "open" file)))))
1221 "Default file applications on a Windows NT system.
1222 The system \"open\" is used for most files.
1223 See `org-file-apps'.")
1225 (defcustom org-file-apps
1226 '((auto-mode . emacs)
1227 ("\\.mm\\'" . default)
1228 ("\\.x?html?\\'" . default)
1229 ("\\.pdf\\'" . default))
1230 "External applications for opening `file:path' items in a document.
1231 \\<org-mode-map>\
1233 Org mode uses system defaults for different file types, but
1234 you can use this variable to set the application for a given file
1235 extension. The entries in this list are cons cells where the car identifies
1236 files and the cdr the corresponding command.
1238 Possible values for the file identifier are:
1240 \"string\" A string as a file identifier can be interpreted in different
1241 ways, depending on its contents:
1243 - Alphanumeric characters only:
1244 Match links with this file extension.
1245 Example: (\"pdf\" . \"evince %s\")
1246 to open PDFs with evince.
1248 - Regular expression: Match links where the
1249 filename matches the regexp. If you want to
1250 use groups here, use shy groups.
1252 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
1253 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
1254 to open *.html and *.xhtml with firefox.
1256 - Regular expression which contains (non-shy) groups:
1257 Match links where the whole link, including \"::\", and
1258 anything after that, matches the regexp.
1259 In a custom command string, %1, %2, etc. are replaced with
1260 the parts of the link that were matched by the groups.
1261 For backwards compatibility, if a command string is given
1262 that does not use any of the group matches, this case is
1263 handled identically to the second one (i.e. match against
1264 file name only).
1265 In a custom function, you can access the group matches with
1266 (match-string n link).
1268 Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
1269 \"evince -p %1 %s\")
1270 to open [[file:document.pdf::5]] with evince at page 5.
1272 `directory' Matches a directory
1273 `remote' Matches a remote file, accessible through tramp or efs.
1274 Remote files most likely should be visited through Emacs
1275 because external applications cannot handle such paths.
1276 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1277 so all files Emacs knows how to handle. Using this with
1278 command `emacs' will open most files in Emacs. Beware that this
1279 will also open html files inside Emacs, unless you add
1280 (\"html\" . default) to the list as well.
1281 `system' The system command to open files, like `open' on Windows
1282 and macOS, and mailcap under GNU/Linux. This is the command
1283 that will be selected if you call `org-open-at-point' with a
1284 double prefix argument (`\\[universal-argument] \
1285 \\[universal-argument] \\[org-open-at-point]').
1286 t Default for files not matched by any of the other options.
1288 Possible values for the command are:
1290 `emacs' The file will be visited by the current Emacs process.
1291 `default' Use the default application for this file type, which is the
1292 association for t in the list, most likely in the system-specific
1293 part. This can be used to overrule an unwanted setting in the
1294 system-specific variable.
1295 `system' Use the system command for opening files, like \"open\".
1296 This command is specified by the entry whose car is `system'.
1297 Most likely, the system-specific version of this variable
1298 does define this command, but you can overrule/replace it
1299 here.
1300 `mailcap' Use command specified in the mailcaps.
1301 string A command to be executed by a shell; %s will be replaced
1302 by the path to the file.
1303 function A Lisp function, which will be called with two arguments:
1304 the file path and the original link string, without the
1305 \"file:\" prefix.
1307 For more examples, see the system specific constants
1308 `org-file-apps-macos'
1309 `org-file-apps-windowsnt'
1310 `org-file-apps-gnu'."
1311 :group 'org
1312 :type '(repeat
1313 (cons (choice :value ""
1314 (string :tag "Extension")
1315 (const :tag "System command to open files" system)
1316 (const :tag "Default for unrecognized files" t)
1317 (const :tag "Remote file" remote)
1318 (const :tag "Links to a directory" directory)
1319 (const :tag "Any files that have Emacs modes"
1320 auto-mode))
1321 (choice :value ""
1322 (const :tag "Visit with Emacs" emacs)
1323 (const :tag "Use default" default)
1324 (const :tag "Use the system command" system)
1325 (string :tag "Command")
1326 (function :tag "Function")))))
1328 (defcustom org-open-non-existing-files nil
1329 "Non-nil means `org-open-file' opens non-existing files.
1331 When nil, an error is thrown.
1333 This variable applies only to external applications because they
1334 might choke on non-existing files. If the link is to a file that
1335 will be opened in Emacs, the variable is ignored."
1336 :group 'org
1337 :type 'boolean
1338 :safe #'booleanp)
1340 (defcustom org-open-directory-means-index-dot-org nil
1341 "When non-nil a link to a directory really means to \"index.org\".
1342 When nil, following a directory link runs Dired or opens
1343 a finder/explorer window on that directory."
1344 :group 'org
1345 :type 'boolean
1346 :safe #'booleanp)
1348 (defcustom org-bookmark-names-plist
1349 '(:last-capture "org-capture-last-stored"
1350 :last-refile "org-refile-last-stored"
1351 :last-capture-marker "org-capture-last-stored-marker")
1352 "Names for bookmarks automatically set by some Org commands.
1353 This can provide strings as names for a number of bookmarks Org sets
1354 automatically. The following keys are currently implemented:
1355 :last-capture
1356 :last-capture-marker
1357 :last-refile
1358 When a key does not show up in the property list, the corresponding bookmark
1359 is not set."
1360 :group 'org-structure
1361 :type 'plist)
1363 (defgroup org-cycle nil
1364 "Options concerning visibility cycling in Org mode."
1365 :tag "Org Cycle"
1366 :group 'org-structure)
1368 (defcustom org-cycle-skip-children-state-if-no-children t
1369 "Non-nil means skip CHILDREN state in entries that don't have any."
1370 :group 'org-cycle
1371 :type 'boolean)
1373 (defcustom org-cycle-max-level nil
1374 "Maximum level which should still be subject to visibility cycling.
1375 Levels higher than this will, for cycling, be treated as text, not a headline.
1376 When `org-odd-levels-only' is set, a value of N in this variable actually
1377 means 2N-1 stars as the limiting headline.
1378 When nil, cycle all levels.
1379 Note that the limiting level of cycling is also influenced by
1380 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1381 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1382 than its value."
1383 :group 'org-cycle
1384 :type '(choice
1385 (const :tag "No limit" nil)
1386 (integer :tag "Maximum level")))
1388 (defcustom org-hide-block-startup nil
1389 "Non-nil means entering Org mode will fold all blocks.
1390 This can also be set in on a per-file basis with
1392 #+STARTUP: hideblocks
1393 #+STARTUP: showblocks"
1394 :group 'org-startup
1395 :group 'org-cycle
1396 :type 'boolean)
1398 (defcustom org-cycle-global-at-bob nil
1399 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1401 This makes it possible to do global cycling without having to use `S-TAB'
1402 or `\\[universal-argument] TAB'. For this special case to work, the first \
1403 line of the buffer
1404 must not be a headline -- it may be empty or some other text.
1406 When used in this way, `org-cycle-hook' is disabled temporarily to make
1407 sure the cursor stays at the beginning of the buffer.
1409 When this option is nil, don't do anything special at the beginning of
1410 the buffer."
1411 :group 'org-cycle
1412 :type 'boolean)
1414 (defcustom org-cycle-level-after-item/entry-creation t
1415 "Non-nil means cycle entry level or item indentation in new empty entries.
1417 When the cursor is at the end of an empty headline, i.e., with only stars
1418 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1419 and then all possible ancestor states, before returning to the original state.
1420 This makes data entry extremely fast: M-RET to create a new headline,
1421 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1423 When the cursor is at the end of an empty plain list item, one TAB will
1424 make it a subitem, two or more tabs will back up to make this an item
1425 higher up in the item hierarchy."
1426 :group 'org-cycle
1427 :type 'boolean)
1429 (defcustom org-cycle-emulate-tab t
1430 "Where should `org-cycle' emulate TAB.
1431 nil Never
1432 white Only in completely white lines
1433 whitestart Only at the beginning of lines, before the first non-white char
1434 t Everywhere except in headlines
1435 exc-hl-bol Everywhere except at the start of a headline
1436 If TAB is used in a place where it does not emulate TAB, the current subtree
1437 visibility is cycled."
1438 :group 'org-cycle
1439 :type '(choice (const :tag "Never" nil)
1440 (const :tag "Only in completely white lines" white)
1441 (const :tag "Before first char in a line" whitestart)
1442 (const :tag "Everywhere except in headlines" t)
1443 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1445 (defcustom org-cycle-separator-lines 2
1446 "Number of empty lines needed to keep an empty line between collapsed trees.
1447 If you leave an empty line between the end of a subtree and the following
1448 headline, this empty line is hidden when the subtree is folded.
1449 Org mode will leave (exactly) one empty line visible if the number of
1450 empty lines is equal or larger to the number given in this variable.
1451 So the default 2 means at least 2 empty lines after the end of a subtree
1452 are needed to produce free space between a collapsed subtree and the
1453 following headline.
1455 If the number is negative, and the number of empty lines is at least -N,
1456 all empty lines are shown.
1458 Special case: when 0, never leave empty lines in collapsed view."
1459 :group 'org-cycle
1460 :type 'integer)
1461 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1463 (defcustom org-pre-cycle-hook nil
1464 "Hook that is run before visibility cycling is happening.
1465 The function(s) in this hook must accept a single argument which indicates
1466 the new state that will be set right after running this hook. The
1467 argument is a symbol. Before a global state change, it can have the values
1468 `overview', `content', or `all'. Before a local state change, it can have
1469 the values `folded', `children', or `subtree'."
1470 :group 'org-cycle
1471 :type 'hook)
1473 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1474 org-cycle-show-empty-lines
1475 org-optimize-window-after-visibility-change)
1476 "Hook that is run after `org-cycle' has changed the buffer visibility.
1477 The function(s) in this hook must accept a single argument which indicates
1478 the new state that was set by the most recent `org-cycle' command. The
1479 argument is a symbol. After a global state change, it can have the values
1480 `overview', `contents', or `all'. After a local state change, it can have
1481 the values `folded', `children', or `subtree'."
1482 :group 'org-cycle
1483 :type 'hook
1484 :version "26.1"
1485 :package-version '(Org . "8.3"))
1487 (defgroup org-edit-structure nil
1488 "Options concerning structure editing in Org mode."
1489 :tag "Org Edit Structure"
1490 :group 'org-structure)
1492 (defcustom org-odd-levels-only nil
1493 "Non-nil means skip even levels and only use odd levels for the outline.
1494 This has the effect that two stars are being added/taken away in
1495 promotion/demotion commands. It also influences how levels are
1496 handled by the exporters.
1497 Changing it requires restart of `font-lock-mode' to become effective
1498 for fontification also in regions already fontified.
1499 You may also set this on a per-file basis by adding one of the following
1500 lines to the buffer:
1502 #+STARTUP: odd
1503 #+STARTUP: oddeven"
1504 :group 'org-edit-structure
1505 :group 'org-appearance
1506 :type 'boolean)
1508 (defcustom org-adapt-indentation t
1509 "Non-nil means adapt indentation to outline node level.
1511 When this variable is set, Org assumes that you write outlines by
1512 indenting text in each node to align with the headline (after the
1513 stars). The following issues are influenced by this variable:
1515 - The indentation is increased by one space in a demotion
1516 command, and decreased by one in a promotion command. However,
1517 in the latter case, if shifting some line in the entry body
1518 would alter document structure (e.g., insert a new headline),
1519 indentation is not changed at all.
1521 - Property drawers and planning information is inserted indented
1522 when this variable is set. When nil, they will not be indented.
1524 - TAB indents a line relative to current level. The lines below
1525 a headline will be indented when this variable is set.
1527 Note that this is all about true indentation, by adding and
1528 removing space characters. See also \"org-indent.el\" which does
1529 level-dependent indentation in a virtual way, i.e. at display
1530 time in Emacs."
1531 :group 'org-edit-structure
1532 :type 'boolean
1533 :safe #'booleanp)
1535 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1537 (defcustom org-special-ctrl-a/e nil
1538 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1540 When t, `C-a' will bring back the cursor to the beginning of the
1541 headline text, i.e. after the stars and after a possible TODO
1542 keyword. In an item, this will be the position after bullet and
1543 check-box, if any. When the cursor is already at that position,
1544 another `C-a' will bring it to the beginning of the line.
1546 `C-e' will jump to the end of the headline, ignoring the presence
1547 of tags in the headline. A second `C-e' will then jump to the
1548 true end of the line, after any tags. This also means that, when
1549 this variable is non-nil, `C-e' also will never jump beyond the
1550 end of the heading of a folded section, i.e. not after the
1551 ellipses.
1553 When set to the symbol `reversed', the first `C-a' or `C-e' works
1554 normally, going to the true line boundary first. Only a directly
1555 following, identical keypress will bring the cursor to the
1556 special positions.
1558 This may also be a cons cell where the behavior for `C-a' and
1559 `C-e' is set separately."
1560 :group 'org-edit-structure
1561 :type '(choice
1562 (const :tag "off" nil)
1563 (const :tag "on: after stars/bullet and before tags first" t)
1564 (const :tag "reversed: true line boundary first" reversed)
1565 (cons :tag "Set C-a and C-e separately"
1566 (choice :tag "Special C-a"
1567 (const :tag "off" nil)
1568 (const :tag "on: after stars/bullet first" t)
1569 (const :tag "reversed: before stars/bullet first" reversed))
1570 (choice :tag "Special C-e"
1571 (const :tag "off" nil)
1572 (const :tag "on: before tags first" t)
1573 (const :tag "reversed: after tags first" reversed)))))
1575 (defcustom org-special-ctrl-k nil
1576 "Non-nil means `C-k' will behave specially in headlines.
1577 When nil, `C-k' will call the default `kill-line' command.
1578 When t, the following will happen while the cursor is in the headline:
1580 - When the cursor is at the beginning of a headline, kill the entire
1581 line and possible the folded subtree below the line.
1582 - When in the middle of the headline text, kill the headline up to the tags.
1583 - When after the headline text, kill the tags."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-ctrl-k-protect-subtree nil
1588 "Non-nil means, do not delete a hidden subtree with C-k.
1589 When set to the symbol `error', simply throw an error when C-k is
1590 used to kill (part-of) a headline that has hidden text behind it.
1591 Any other non-nil value will result in a query to the user, if it is
1592 OK to kill that hidden subtree. When nil, kill without remorse."
1593 :group 'org-edit-structure
1594 :version "24.1"
1595 :type '(choice
1596 (const :tag "Do not protect hidden subtrees" nil)
1597 (const :tag "Protect hidden subtrees with a security query" t)
1598 (const :tag "Never kill a hidden subtree with C-k" error)))
1600 (defcustom org-special-ctrl-o t
1601 "Non-nil means, make `C-o' insert a row in tables."
1602 :group 'org-edit-structure
1603 :type 'boolean)
1605 (defcustom org-catch-invisible-edits nil
1606 "Check if in invisible region before inserting or deleting a character.
1607 Valid values are:
1609 nil Do not check, so just do invisible edits.
1610 error Throw an error and do nothing.
1611 show Make point visible, and do the requested edit.
1612 show-and-error Make point visible, then throw an error and abort the edit.
1613 smart Make point visible, and do insertion/deletion if it is
1614 adjacent to visible text and the change feels predictable.
1615 Never delete a previously invisible character or add in the
1616 middle or right after an invisible region. Basically, this
1617 allows insertion and backward-delete right before ellipses.
1618 FIXME: maybe in this case we should not even show?"
1619 :group 'org-edit-structure
1620 :version "24.1"
1621 :type '(choice
1622 (const :tag "Do not check" nil)
1623 (const :tag "Throw error when trying to edit" error)
1624 (const :tag "Unhide, but do not do the edit" show-and-error)
1625 (const :tag "Show invisible part and do the edit" show)
1626 (const :tag "Be smart and do the right thing" smart)))
1628 (defcustom org-yank-folded-subtrees t
1629 "Non-nil means when yanking subtrees, fold them.
1630 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1631 it starts with a heading and all other headings in it are either children
1632 or siblings, then fold all the subtrees. However, do this only if no
1633 text after the yank would be swallowed into a folded tree by this action."
1634 :group 'org-edit-structure
1635 :type 'boolean)
1637 (defcustom org-yank-adjusted-subtrees nil
1638 "Non-nil means when yanking subtrees, adjust the level.
1639 With this setting, `org-paste-subtree' is used to insert the subtree, see
1640 this function for details."
1641 :group 'org-edit-structure
1642 :type 'boolean)
1644 (defcustom org-M-RET-may-split-line '((default . t))
1645 "Non-nil means M-RET will split the line at the cursor position.
1646 When nil, it will go to the end of the line before making a
1647 new line.
1648 You may also set this option in a different way for different
1649 contexts. Valid contexts are:
1651 headline when creating a new headline
1652 item when creating a new item
1653 table in a table field
1654 default the value to be used for all contexts not explicitly
1655 customized"
1656 :group 'org-structure
1657 :group 'org-table
1658 :type '(choice
1659 (const :tag "Always" t)
1660 (const :tag "Never" nil)
1661 (repeat :greedy t :tag "Individual contexts"
1662 (cons
1663 (choice :tag "Context"
1664 (const headline)
1665 (const item)
1666 (const table)
1667 (const default))
1668 (boolean)))))
1671 (defcustom org-insert-heading-respect-content nil
1672 "Non-nil means insert new headings after the current subtree.
1673 \\<org-mode-map>
1674 When nil, the new heading is created directly after the current line.
1675 The commands `\\[org-insert-heading-respect-content]' and \
1676 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1677 for the duration of the command."
1678 :group 'org-structure
1679 :type 'boolean)
1681 (defcustom org-blank-before-new-entry '((heading . auto)
1682 (plain-list-item . auto))
1683 "Should `org-insert-heading' leave a blank line before new heading/item?
1684 The value is an alist, with `heading' and `plain-list-item' as CAR,
1685 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1686 which case Org will look at the surrounding headings/items and try to
1687 make an intelligent decision whether to insert a blank line or not."
1688 :group 'org-edit-structure
1689 :type '(list
1690 (cons (const heading)
1691 (choice (const :tag "Never" nil)
1692 (const :tag "Always" t)
1693 (const :tag "Auto" auto)))
1694 (cons (const plain-list-item)
1695 (choice (const :tag "Never" nil)
1696 (const :tag "Always" t)
1697 (const :tag "Auto" auto)))))
1699 (defcustom org-insert-heading-hook nil
1700 "Hook being run after inserting a new heading."
1701 :group 'org-edit-structure
1702 :type 'hook)
1704 (defcustom org-enable-fixed-width-editor t
1705 "Non-nil means lines starting with \":\" are treated as fixed-width.
1706 This currently only means they are never auto-wrapped.
1707 When nil, such lines will be treated like ordinary lines."
1708 :group 'org-edit-structure
1709 :type 'boolean)
1711 (defgroup org-sparse-trees nil
1712 "Options concerning sparse trees in Org mode."
1713 :tag "Org Sparse Trees"
1714 :group 'org-structure)
1716 (defcustom org-highlight-sparse-tree-matches t
1717 "Non-nil means highlight all matches that define a sparse tree.
1718 The highlights will automatically disappear the next time the buffer is
1719 changed by an edit command."
1720 :group 'org-sparse-trees
1721 :type 'boolean)
1723 (defcustom org-remove-highlights-with-change t
1724 "Non-nil means any change to the buffer will remove temporary highlights.
1725 \\<org-mode-map>\
1726 Such highlights are created by `org-occur' and `org-clock-display'.
1727 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1728 to get rid of the highlights.
1729 The highlights created by `org-latex-preview' always need
1730 `\\[org-latex-preview]' to be removed."
1731 :group 'org-sparse-trees
1732 :group 'org-time
1733 :type 'boolean)
1735 (defcustom org-occur-case-fold-search t
1736 "Non-nil means `org-occur' should be case-insensitive.
1737 If set to `smart' the search will be case-insensitive only if it
1738 doesn't specify any upper case character."
1739 :group 'org-sparse-trees
1740 :version "26.1"
1741 :type '(choice
1742 (const :tag "Case-sensitive" nil)
1743 (const :tag "Case-insensitive" t)
1744 (const :tag "Case-insensitive for lower case searches only" smart)))
1746 (defcustom org-occur-hook '(org-first-headline-recenter)
1747 "Hook that is run after `org-occur' has constructed a sparse tree.
1748 This can be used to recenter the window to show as much of the structure
1749 as possible."
1750 :group 'org-sparse-trees
1751 :type 'hook)
1753 (defcustom org-self-insert-cluster-for-undo nil
1754 "Non-nil means cluster self-insert commands for undo when possible.
1755 If this is set, then, like in the Emacs command loop, 20 consecutive
1756 characters will be undone together.
1757 This is configurable, because there is some impact on typing performance."
1758 :group 'org-table
1759 :type 'boolean)
1761 (defvaralias 'org-activate-links 'org-highlight-links)
1762 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1763 "Types of links that should be highlighted in Org files.
1765 This is a list of symbols, each one of them leading to the
1766 highlighting of a certain link type.
1768 You can still open links that are not highlighted.
1770 In principle, it does not hurt to turn on highlighting for all
1771 link types. There may be a small gain when turning off unused
1772 link types. The types are:
1774 bracket The recommended [[link][description]] or [[link]] links with hiding.
1775 angle Links in angular brackets that may contain whitespace like
1776 <bbdb:Carsten Dominik>.
1777 plain Plain links in normal text, no whitespace, like http://google.com.
1778 radio Text that is matched by a radio target, see manual for details.
1779 tag Tag settings in a headline (link to tag search).
1780 date Time stamps (link to calendar).
1781 footnote Footnote labels.
1783 If you set this variable during an Emacs session, use `org-mode-restart'
1784 in the Org buffer so that the change takes effect."
1785 :group 'org-appearance
1786 :type '(set :greedy t
1787 (const :tag "Double bracket links" bracket)
1788 (const :tag "Angular bracket links" angle)
1789 (const :tag "Plain text links" plain)
1790 (const :tag "Radio target matches" radio)
1791 (const :tag "Tags" tag)
1792 (const :tag "Timestamps" date)
1793 (const :tag "Footnotes" footnote)))
1795 (defcustom org-mark-ring-length 4
1796 "Number of different positions to be recorded in the ring.
1797 Changing this requires a restart of Emacs to work correctly."
1798 :group 'org-link-follow
1799 :type 'integer)
1801 (defgroup org-refile nil
1802 "Options concerning refiling entries in Org mode."
1803 :tag "Org Refile"
1804 :group 'org)
1806 (defcustom org-directory "~/org"
1807 "Directory with Org files.
1808 This is just a default location to look for Org files. There is no need
1809 at all to put your files into this directory. It is used in the
1810 following situations:
1812 1. When a capture template specifies a target file that is not an
1813 absolute path. The path will then be interpreted relative to
1814 `org-directory'
1815 2. When the value of variable `org-agenda-files' is a single file, any
1816 relative paths in this file will be taken as relative to
1817 `org-directory'."
1818 :group 'org-refile
1819 :group 'org-capture
1820 :type 'directory)
1822 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1823 "Default target for storing notes.
1824 Used as a fall back file for org-capture.el, for templates that
1825 do not specify a target file."
1826 :group 'org-refile
1827 :group 'org-capture
1828 :type 'file)
1830 (defcustom org-reverse-note-order nil
1831 "Non-nil means store new notes at the beginning of a file or entry.
1832 When nil, new notes will be filed to the end of a file or entry.
1833 This can also be a list with cons cells of regular expressions that
1834 are matched against file names, and values."
1835 :group 'org-capture
1836 :group 'org-refile
1837 :type '(choice
1838 (const :tag "Reverse always" t)
1839 (const :tag "Reverse never" nil)
1840 (repeat :tag "By file name regexp"
1841 (cons regexp boolean))))
1843 (defcustom org-log-refile nil
1844 "Information to record when a task is refiled.
1846 Possible values are:
1848 nil Don't add anything
1849 time Add a time stamp to the task
1850 note Prompt for a note and add it with template `org-log-note-headings'
1852 This option can also be set with on a per-file-basis with
1854 #+STARTUP: nologrefile
1855 #+STARTUP: logrefile
1856 #+STARTUP: lognoterefile
1858 You can have local logging settings for a subtree by setting the LOGGING
1859 property to one or more of these keywords.
1861 When bulk-refiling, e.g., from the agenda, the value `note' is
1862 forbidden and will temporarily be changed to `time'."
1863 :group 'org-refile
1864 :group 'org-progress
1865 :version "24.1"
1866 :type '(choice
1867 (const :tag "No logging" nil)
1868 (const :tag "Record timestamp" time)
1869 (const :tag "Record timestamp with note." note)))
1871 (defcustom org-refile-targets nil
1872 "Targets for refiling entries with `\\[org-refile]'.
1873 This is a list of cons cells. Each cell contains:
1874 - a specification of the files to be considered, either a list of files,
1875 or a symbol whose function or variable value will be used to retrieve
1876 a file name or a list of file names. If you use `org-agenda-files' for
1877 that, all agenda files will be scanned for targets. Nil means consider
1878 headings in the current buffer.
1879 - A specification of how to find candidate refile targets. This may be
1880 any of:
1881 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1882 This tag has to be present in all target headlines, inheritance will
1883 not be considered.
1884 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1885 todo keyword.
1886 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1887 headlines that are refiling targets.
1888 - a cons cell (:level . N). Any headline of level N is considered a target.
1889 Note that, when `org-odd-levels-only' is set, level corresponds to
1890 order in hierarchy, not to the number of stars.
1891 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1892 Note that, when `org-odd-levels-only' is set, level corresponds to
1893 order in hierarchy, not to the number of stars.
1895 Each element of this list generates a set of possible targets.
1896 The union of these sets is presented (with completion) to
1897 the user by `org-refile'.
1899 You can set the variable `org-refile-target-verify-function' to a function
1900 to verify each headline found by the simple criteria above.
1902 When this variable is nil, all top-level headlines in the current buffer
1903 are used, equivalent to the value `((nil . (:level . 1))'."
1904 :group 'org-refile
1905 :type '(repeat
1906 (cons
1907 (choice :value org-agenda-files
1908 (const :tag "All agenda files" org-agenda-files)
1909 (const :tag "Current buffer" nil)
1910 (function) (variable) (file))
1911 (choice :tag "Identify target headline by"
1912 (cons :tag "Specific tag" (const :value :tag) (string))
1913 (cons :tag "TODO keyword" (const :value :todo) (string))
1914 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1915 (cons :tag "Level number" (const :value :level) (integer))
1916 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1918 (defcustom org-refile-target-verify-function nil
1919 "Function to verify if the headline at point should be a refile target.
1920 The function will be called without arguments, with point at the
1921 beginning of the headline. It should return t and leave point
1922 where it is if the headline is a valid target for refiling.
1924 If the target should not be selected, the function must return nil.
1925 In addition to this, it may move point to a place from where the search
1926 should be continued. For example, the function may decide that the entire
1927 subtree of the current entry should be excluded and move point to the end
1928 of the subtree."
1929 :group 'org-refile
1930 :type '(choice
1931 (const nil)
1932 (function)))
1934 (defcustom org-refile-use-cache nil
1935 "Non-nil means cache refile targets to speed up the process.
1936 \\<org-mode-map>\
1937 The cache for a particular file will be updated automatically when
1938 the buffer has been killed, or when any of the marker used for flagging
1939 refile targets no longer points at a live buffer.
1940 If you have added new entries to a buffer that might themselves be targets,
1941 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
1942 if you find that easier, \
1943 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
1944 \\[org-refile]'."
1945 :group 'org-refile
1946 :version "24.1"
1947 :type 'boolean)
1949 (defcustom org-refile-use-outline-path nil
1950 "Non-nil means provide refile targets as paths.
1951 So a level 3 headline will be available as level1/level2/level3.
1953 When the value is `file', also include the file name (without directory)
1954 into the path. In this case, you can also stop the completion after
1955 the file name, to get entries inserted as top level in the file.
1957 When `full-file-path', include the full file path.
1959 When `buffer-name', use the buffer name."
1960 :group 'org-refile
1961 :type '(choice
1962 (const :tag "Not" nil)
1963 (const :tag "Yes" t)
1964 (const :tag "Start with file name" file)
1965 (const :tag "Start with full file path" full-file-path)
1966 (const :tag "Start with buffer name" buffer-name)))
1968 (defcustom org-outline-path-complete-in-steps t
1969 "Non-nil means complete the outline path in hierarchical steps.
1970 When Org uses the refile interface to select an outline path (see
1971 `org-refile-use-outline-path'), the completion of the path can be
1972 done in a single go, or it can be done in steps down the headline
1973 hierarchy. Going in steps is probably the best if you do not use
1974 a special completion package like `ido' or `icicles'. However,
1975 when using these packages, going in one step can be very fast,
1976 while still showing the whole path to the entry."
1977 :group 'org-refile
1978 :type 'boolean)
1980 (defcustom org-refile-allow-creating-parent-nodes nil
1981 "Non-nil means allow the creation of new nodes as refile targets.
1982 New nodes are then created by adding \"/new node name\" to the completion
1983 of an existing node. When the value of this variable is `confirm',
1984 new node creation must be confirmed by the user (recommended).
1985 When nil, the completion must match an existing entry.
1987 Note that, if the new heading is not seen by the criteria
1988 listed in `org-refile-targets', multiple instances of the same
1989 heading would be created by trying again to file under the new
1990 heading."
1991 :group 'org-refile
1992 :type '(choice
1993 (const :tag "Never" nil)
1994 (const :tag "Always" t)
1995 (const :tag "Prompt for confirmation" confirm)))
1997 (defcustom org-refile-active-region-within-subtree nil
1998 "Non-nil means also refile active region within a subtree.
2000 By default `org-refile' doesn't allow refiling regions if they
2001 don't contain a set of subtrees, but it might be convenient to
2002 do so sometimes: in that case, the first line of the region is
2003 converted to a headline before refiling."
2004 :group 'org-refile
2005 :version "24.1"
2006 :type 'boolean)
2008 (defgroup org-todo nil
2009 "Options concerning TODO items in Org mode."
2010 :tag "Org TODO"
2011 :group 'org)
2013 (defgroup org-progress nil
2014 "Options concerning Progress logging in Org mode."
2015 :tag "Org Progress"
2016 :group 'org-time)
2018 (defvar org-todo-interpretation-widgets
2019 '((:tag "Sequence (cycling hits every state)" sequence)
2020 (:tag "Type (cycling directly to DONE)" type))
2021 "The available interpretation symbols for customizing `org-todo-keywords'.
2022 Interested libraries should add to this list.")
2024 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2025 "List of TODO entry keyword sequences and their interpretation.
2026 \\<org-mode-map>This is a list of sequences.
2028 Each sequence starts with a symbol, either `sequence' or `type',
2029 indicating if the keywords should be interpreted as a sequence of
2030 action steps, or as different types of TODO items. The first
2031 keywords are states requiring action - these states will select a headline
2032 for inclusion into the global TODO list Org produces. If one of the
2033 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2034 signify that no further action is necessary. If \"|\" is not found,
2035 the last keyword is treated as the only DONE state of the sequence.
2037 The command `\\[org-todo]' cycles an entry through these states, and one
2038 additional state where no keyword is present. For details about this
2039 cycling, see the manual.
2041 TODO keywords and interpretation can also be set on a per-file basis with
2042 the special #+SEQ_TODO and #+TYP_TODO lines.
2044 Each keyword can optionally specify a character for fast state selection
2045 \(in combination with the variable `org-use-fast-todo-selection')
2046 and specifiers for state change logging, using the same syntax that
2047 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2048 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2049 indicates to record a time stamp each time this state is selected.
2051 Each keyword may also specify if a timestamp or a note should be
2052 recorded when entering or leaving the state, by adding additional
2053 characters in the parenthesis after the keyword. This looks like this:
2054 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2055 record only the time of the state change. With X and Y being either
2056 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2057 Y when leaving the state if and only if the *target* state does not
2058 define X. You may omit any of the fast-selection key or X or /Y,
2059 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2061 For backward compatibility, this variable may also be just a list
2062 of keywords. In this case the interpretation (sequence or type) will be
2063 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2064 :group 'org-todo
2065 :group 'org-keywords
2066 :type '(choice
2067 (repeat :tag "Old syntax, just keywords"
2068 (string :tag "Keyword"))
2069 (repeat :tag "New syntax"
2070 (cons
2071 (choice
2072 :tag "Interpretation"
2073 ;;Quick and dirty way to see
2074 ;;`org-todo-interpretations'. This takes the
2075 ;;place of item arguments
2076 :convert-widget
2077 (lambda (widget)
2078 (widget-put widget
2079 :args (mapcar
2080 (lambda (x)
2081 (widget-convert
2082 (cons 'const x)))
2083 org-todo-interpretation-widgets))
2084 widget))
2085 (repeat
2086 (string :tag "Keyword"))))))
2088 (defvar-local org-todo-keywords-1 nil
2089 "All TODO and DONE keywords active in a buffer.")
2090 (defvar org-todo-keywords-for-agenda nil)
2091 (defvar org-done-keywords-for-agenda nil)
2092 (defvar org-todo-keyword-alist-for-agenda nil)
2093 (defvar org-tag-alist-for-agenda nil
2094 "Alist of all tags from all agenda files.")
2095 (defvar org-tag-groups-alist-for-agenda nil
2096 "Alist of all groups tags from all current agenda files.")
2097 (defvar-local org-tag-groups-alist nil)
2098 (defvar org-agenda-contributing-files nil)
2099 (defvar-local org-current-tag-alist nil
2100 "Alist of all tag groups in current buffer.
2101 This variable takes into consideration `org-tag-alist',
2102 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2103 (defvar-local org-not-done-keywords nil)
2104 (defvar-local org-done-keywords nil)
2105 (defvar-local org-todo-heads nil)
2106 (defvar-local org-todo-sets nil)
2107 (defvar-local org-todo-log-states nil)
2108 (defvar-local org-todo-kwd-alist nil)
2109 (defvar-local org-todo-key-alist nil)
2110 (defvar-local org-todo-key-trigger nil)
2112 (defcustom org-todo-interpretation 'sequence
2113 "Controls how TODO keywords are interpreted.
2114 This variable is in principle obsolete and is only used for
2115 backward compatibility, if the interpretation of todo keywords is
2116 not given already in `org-todo-keywords'. See that variable for
2117 more information."
2118 :group 'org-todo
2119 :group 'org-keywords
2120 :type '(choice (const sequence)
2121 (const type)))
2123 (defcustom org-use-fast-todo-selection t
2124 "\\<org-mode-map>\
2125 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2126 This variable describes if and under what circumstances the cycling
2127 mechanism for TODO keywords will be replaced by a single-key, direct
2128 selection scheme.
2130 When nil, fast selection is never used.
2132 When the symbol `prefix', it will be used when `org-todo' is called
2133 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2134 in an Org buffer, and
2135 `\\[universal-argument] t' in an agenda buffer.
2137 When t, fast selection is used by default. In this case, the prefix
2138 argument forces cycling instead.
2140 In all cases, the special interface is only used if access keys have
2141 actually been assigned by the user, i.e. if keywords in the configuration
2142 are followed by a letter in parenthesis, like TODO(t)."
2143 :group 'org-todo
2144 :type '(choice
2145 (const :tag "Never" nil)
2146 (const :tag "By default" t)
2147 (const :tag "Only with C-u C-c C-t" prefix)))
2149 (defcustom org-provide-todo-statistics t
2150 "Non-nil means update todo statistics after insert and toggle.
2151 ALL-HEADLINES means update todo statistics by including headlines
2152 with no TODO keyword as well, counting them as not done.
2153 A list of TODO keywords means the same, but skip keywords that are
2154 not in this list.
2155 When set to a list of two lists, the first list contains keywords
2156 to consider as TODO keywords, the second list contains keywords
2157 to consider as DONE keywords.
2159 When this is set, todo statistics is updated in the parent of the
2160 current entry each time a todo state is changed."
2161 :group 'org-todo
2162 :type '(choice
2163 (const :tag "Yes, only for TODO entries" t)
2164 (const :tag "Yes, including all entries" all-headlines)
2165 (repeat :tag "Yes, for TODOs in this list"
2166 (string :tag "TODO keyword"))
2167 (list :tag "Yes, for TODOs and DONEs in these lists"
2168 (repeat (string :tag "TODO keyword"))
2169 (repeat (string :tag "DONE keyword")))
2170 (other :tag "No TODO statistics" nil)))
2172 (defcustom org-hierarchical-todo-statistics t
2173 "Non-nil means TODO statistics covers just direct children.
2174 When nil, all entries in the subtree are considered.
2175 This has only an effect if `org-provide-todo-statistics' is set.
2176 To set this to nil for only a single subtree, use a COOKIE_DATA
2177 property and include the word \"recursive\" into the value."
2178 :group 'org-todo
2179 :type 'boolean)
2181 (defcustom org-after-todo-state-change-hook nil
2182 "Hook which is run after the state of a TODO item was changed.
2183 The new state (a string with a TODO keyword, or nil) is available in the
2184 Lisp variable `org-state'."
2185 :group 'org-todo
2186 :type 'hook)
2188 (defvar org-blocker-hook nil
2189 "Hook for functions that are allowed to block a state change.
2191 Functions in this hook should not modify the buffer.
2192 Each function gets as its single argument a property list,
2193 see `org-trigger-hook' for more information about this list.
2195 If any of the functions in this hook returns nil, the state change
2196 is blocked.")
2198 (defvar org-trigger-hook nil
2199 "Hook for functions that are triggered by a state change.
2201 Each function gets as its single argument a property list with at
2202 least the following elements:
2204 (:type type-of-change :position pos-at-entry-start
2205 :from old-state :to new-state)
2207 Depending on the type, more properties may be present.
2209 This mechanism is currently implemented for:
2211 TODO state changes
2212 ------------------
2213 :type todo-state-change
2214 :from previous state (keyword as a string), or nil, or a symbol
2215 `todo' or `done', to indicate the general type of state.
2216 :to new state, like in :from")
2218 (defcustom org-enforce-todo-dependencies nil
2219 "Non-nil means undone TODO entries will block switching the parent to DONE.
2220 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2221 be blocked if any prior sibling is not yet done.
2222 Finally, if the parent is blocked because of ordered siblings of its own,
2223 the child will also be blocked."
2224 :set (lambda (var val)
2225 (set var val)
2226 (if val
2227 (add-hook 'org-blocker-hook
2228 'org-block-todo-from-children-or-siblings-or-parent)
2229 (remove-hook 'org-blocker-hook
2230 'org-block-todo-from-children-or-siblings-or-parent)))
2231 :group 'org-todo
2232 :type 'boolean)
2234 (defcustom org-enforce-todo-checkbox-dependencies nil
2235 "Non-nil means unchecked boxes will block switching the parent to DONE.
2236 When this is nil, checkboxes have no influence on switching TODO states.
2237 When non-nil, you first need to check off all check boxes before the TODO
2238 entry can be switched to DONE.
2239 This variable needs to be set before org.el is loaded, and you need to
2240 restart Emacs after a change to make the change effective. The only way
2241 to change it while Emacs is running is through the customize interface."
2242 :set (lambda (var val)
2243 (set var val)
2244 (if val
2245 (add-hook 'org-blocker-hook
2246 'org-block-todo-from-checkboxes)
2247 (remove-hook 'org-blocker-hook
2248 'org-block-todo-from-checkboxes)))
2249 :group 'org-todo
2250 :type 'boolean)
2252 (defcustom org-treat-insert-todo-heading-as-state-change nil
2253 "Non-nil means inserting a TODO heading is treated as state change.
2254 So when the command `\\[org-insert-todo-heading]' is used, state change
2255 logging will apply if appropriate. When nil, the new TODO item will
2256 be inserted directly, and no logging will take place."
2257 :group 'org-todo
2258 :type 'boolean)
2260 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2261 "Non-nil means switching TODO states with S-cursor counts as state change.
2262 This is the default behavior. However, setting this to nil allows a
2263 convenient way to select a TODO state and bypass any logging associated
2264 with that."
2265 :group 'org-todo
2266 :type 'boolean)
2268 (defcustom org-todo-state-tags-triggers nil
2269 "Tag changes that should be triggered by TODO state changes.
2270 This is a list. Each entry is
2272 (state-change (tag . flag) .......)
2274 State-change can be a string with a state, and empty string to indicate the
2275 state that has no TODO keyword, or it can be one of the symbols `todo'
2276 or `done', meaning any not-done or done state, respectively."
2277 :group 'org-todo
2278 :group 'org-tags
2279 :type '(repeat
2280 (cons (choice :tag "When changing to"
2281 (const :tag "Not-done state" todo)
2282 (const :tag "Done state" done)
2283 (string :tag "State"))
2284 (repeat
2285 (cons :tag "Tag action"
2286 (string :tag "Tag")
2287 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2289 (defcustom org-log-done nil
2290 "Information to record when a task moves to the DONE state.
2292 Possible values are:
2294 nil Don't add anything, just change the keyword
2295 time Add a time stamp to the task
2296 note Prompt for a note and add it with template `org-log-note-headings'
2298 This option can also be set with on a per-file-basis with
2300 #+STARTUP: nologdone
2301 #+STARTUP: logdone
2302 #+STARTUP: lognotedone
2304 You can have local logging settings for a subtree by setting the LOGGING
2305 property to one or more of these keywords."
2306 :group 'org-todo
2307 :group 'org-progress
2308 :type '(choice
2309 (const :tag "No logging" nil)
2310 (const :tag "Record CLOSED timestamp" time)
2311 (const :tag "Record CLOSED timestamp with note." note)))
2313 ;; Normalize old uses of org-log-done.
2314 (cond
2315 ((eq org-log-done t) (setq org-log-done 'time))
2316 ((and (listp org-log-done) (memq 'done org-log-done))
2317 (setq org-log-done 'note)))
2319 (defcustom org-log-reschedule nil
2320 "Information to record when the scheduling date of a task is modified.
2322 Possible values are:
2324 nil Don't add anything, just change the date
2325 time Add a time stamp to the task
2326 note Prompt for a note and add it with template `org-log-note-headings'
2328 This option can also be set with on a per-file-basis with
2330 #+STARTUP: nologreschedule
2331 #+STARTUP: logreschedule
2332 #+STARTUP: lognotereschedule
2334 You can have local logging settings for a subtree by setting the LOGGING
2335 property to one or more of these keywords.
2337 This variable has an effect when calling `org-schedule' or
2338 `org-agenda-schedule' only."
2339 :group 'org-todo
2340 :group 'org-progress
2341 :type '(choice
2342 (const :tag "No logging" nil)
2343 (const :tag "Record timestamp" time)
2344 (const :tag "Record timestamp with note" note)))
2346 (defcustom org-log-redeadline nil
2347 "Information to record when the deadline date of a task is modified.
2349 Possible values are:
2351 nil Don't add anything, just change the date
2352 time Add a time stamp to the task
2353 note Prompt for a note and add it with template `org-log-note-headings'
2355 This option can also be set with on a per-file-basis with
2357 #+STARTUP: nologredeadline
2358 #+STARTUP: logredeadline
2359 #+STARTUP: lognoteredeadline
2361 You can have local logging settings for a subtree by setting the LOGGING
2362 property to one or more of these keywords.
2364 This variable has an effect when calling `org-deadline' or
2365 `org-agenda-deadline' only."
2366 :group 'org-todo
2367 :group 'org-progress
2368 :type '(choice
2369 (const :tag "No logging" nil)
2370 (const :tag "Record timestamp" time)
2371 (const :tag "Record timestamp with note." note)))
2373 (defcustom org-log-note-clock-out nil
2374 "Non-nil means record a note when clocking out of an item.
2375 This can also be configured on a per-file basis by adding one of
2376 the following lines anywhere in the buffer:
2378 #+STARTUP: lognoteclock-out
2379 #+STARTUP: nolognoteclock-out"
2380 :group 'org-todo
2381 :group 'org-progress
2382 :type 'boolean)
2384 (defcustom org-log-done-with-time t
2385 "Non-nil means the CLOSED time stamp will contain date and time.
2386 When nil, only the date will be recorded."
2387 :group 'org-progress
2388 :type 'boolean)
2390 (defcustom org-log-note-headings
2391 '((done . "CLOSING NOTE %t")
2392 (state . "State %-12s from %-12S %t")
2393 (note . "Note taken on %t")
2394 (reschedule . "Rescheduled from %S on %t")
2395 (delschedule . "Not scheduled, was %S on %t")
2396 (redeadline . "New deadline from %S on %t")
2397 (deldeadline . "Removed deadline, was %S on %t")
2398 (refile . "Refiled on %t")
2399 (clock-out . ""))
2400 "Headings for notes added to entries.
2402 The value is an alist, with the car being a symbol indicating the
2403 note context, and the cdr is the heading to be used. The heading
2404 may also be the empty string. The following placeholders can be
2405 used:
2407 %t a time stamp.
2408 %T an active time stamp instead the default inactive one
2409 %d a short-format time stamp.
2410 %D an active short-format time stamp.
2411 %s the new TODO state or time stamp (inactive), in double quotes.
2412 %S the old TODO state or time stamp (inactive), in double quotes.
2413 %u the user name.
2414 %U full user name.
2416 In fact, it is not a good idea to change the `state' entry,
2417 because Agenda Log mode depends on the format of these entries."
2418 :group 'org-todo
2419 :group 'org-progress
2420 :type '(list :greedy t
2421 (cons (const :tag "Heading when closing an item" done) string)
2422 (cons (const :tag
2423 "Heading when changing todo state (todo sequence only)"
2424 state) string)
2425 (cons (const :tag "Heading when just taking a note" note) string)
2426 (cons (const :tag "Heading when rescheduling" reschedule) string)
2427 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2428 (cons (const :tag "Heading when changing deadline" redeadline) string)
2429 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2430 (cons (const :tag "Heading when refiling" refile) string)
2431 (cons (const :tag "Heading when clocking out" clock-out) string)))
2433 (unless (assq 'note org-log-note-headings)
2434 (push '(note . "%t") org-log-note-headings))
2436 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2438 (defcustom org-log-into-drawer nil
2439 "Non-nil means insert state change notes and time stamps into a drawer.
2440 When nil, state changes notes will be inserted after the headline and
2441 any scheduling and clock lines, but not inside a drawer.
2443 The value of this variable should be the name of the drawer to use.
2444 LOGBOOK is proposed as the default drawer for this purpose, you can
2445 also set this to a string to define the drawer of your choice.
2447 A value of t is also allowed, representing \"LOGBOOK\".
2449 A value of t or nil can also be set with on a per-file-basis with
2451 #+STARTUP: logdrawer
2452 #+STARTUP: nologdrawer
2454 If this variable is set, `org-log-state-notes-insert-after-drawers'
2455 will be ignored.
2457 You can set the property LOG_INTO_DRAWER to overrule this setting for
2458 a subtree.
2460 Do not check directly this variable in a Lisp program. Call
2461 function `org-log-into-drawer' instead."
2462 :group 'org-todo
2463 :group 'org-progress
2464 :type '(choice
2465 (const :tag "Not into a drawer" nil)
2466 (const :tag "LOGBOOK" t)
2467 (string :tag "Other")))
2469 (defun org-log-into-drawer ()
2470 "Name of the log drawer, as a string, or nil.
2471 This is the value of `org-log-into-drawer'. However, if the
2472 current entry has or inherits a LOG_INTO_DRAWER property, it will
2473 be used instead of the default value."
2474 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2475 (cond ((equal p "nil") nil)
2476 ((equal p "t") "LOGBOOK")
2477 ((stringp p) p)
2478 (p "LOGBOOK")
2479 ((stringp org-log-into-drawer) org-log-into-drawer)
2480 (org-log-into-drawer "LOGBOOK"))))
2482 (defcustom org-log-state-notes-insert-after-drawers nil
2483 "Non-nil means insert state change notes after any drawers in entry.
2484 Only the drawers that *immediately* follow the headline and the
2485 deadline/scheduled line are skipped.
2486 When nil, insert notes right after the heading and perhaps the line
2487 with deadline/scheduling if present.
2489 This variable will have no effect if `org-log-into-drawer' is
2490 set."
2491 :group 'org-todo
2492 :group 'org-progress
2493 :type 'boolean)
2495 (defcustom org-log-states-order-reversed t
2496 "Non-nil means the latest state note will be directly after heading.
2497 When nil, the state change notes will be ordered according to time.
2499 This option can also be set with on a per-file-basis with
2501 #+STARTUP: logstatesreversed
2502 #+STARTUP: nologstatesreversed"
2503 :group 'org-todo
2504 :group 'org-progress
2505 :type 'boolean)
2507 (defcustom org-todo-repeat-to-state nil
2508 "The TODO state to which a repeater should return the repeating task.
2509 By default this is the first task of a TODO sequence or the
2510 previous state of a TYPE_TODO set. But you can specify to use
2511 the previous state in a TODO sequence or a string.
2513 Alternatively, you can set the :REPEAT_TO_STATE: property of the
2514 entry, which has precedence over this option."
2515 :group 'org-todo
2516 :version "24.1"
2517 :type '(choice (const :tag "Use the previous TODO state" t)
2518 (const :tag "Use the head of the TODO sequence" nil)
2519 (string :tag "Use a specific TODO state")))
2521 (defcustom org-log-repeat 'time
2522 "Non-nil means record moving through the DONE state when triggering repeat.
2523 An auto-repeating task is immediately switched back to TODO when
2524 marked DONE. If you are not logging state changes (by adding \"@\"
2525 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2526 record a closing note, there will be no record of the task moving
2527 through DONE. This variable forces taking a note anyway.
2529 nil Don't force a record
2530 time Record a time stamp
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologrepeat
2536 #+STARTUP: logrepeat
2537 #+STARTUP: lognoterepeat
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "Don't force a record" nil)
2545 (const :tag "Force recording the DONE state" time)
2546 (const :tag "Force recording a note with the DONE state" note)))
2548 (defcustom org-todo-repeat-hook nil
2549 "Hook that is run after a task has been repeated."
2550 :package-version '(Org . "9.2")
2551 :group 'org-todo
2552 :type 'hook)
2554 (defgroup org-priorities nil
2555 "Priorities in Org mode."
2556 :tag "Org Priorities"
2557 :group 'org-todo)
2559 (defcustom org-enable-priority-commands t
2560 "Non-nil means priority commands are active.
2561 When nil, these commands will be disabled, so that you never accidentally
2562 set a priority."
2563 :group 'org-priorities
2564 :type 'boolean)
2566 (defcustom org-highest-priority ?A
2567 "The highest priority of TODO items. A character like ?A, ?B etc.
2568 Must have a smaller ASCII number than `org-lowest-priority'."
2569 :group 'org-priorities
2570 :type 'character)
2572 (defcustom org-lowest-priority ?C
2573 "The lowest priority of TODO items. A character like ?A, ?B etc.
2574 Must have a larger ASCII number than `org-highest-priority'."
2575 :group 'org-priorities
2576 :type 'character)
2578 (defcustom org-default-priority ?B
2579 "The default priority of TODO items.
2580 This is the priority an item gets if no explicit priority is given.
2581 When starting to cycle on an empty priority the first step in the cycle
2582 depends on `org-priority-start-cycle-with-default'. The resulting first
2583 step priority must not exceed the range from `org-highest-priority' to
2584 `org-lowest-priority' which means that `org-default-priority' has to be
2585 in this range exclusive or inclusive the range boundaries. Else the
2586 first step refuses to set the default and the second will fall back
2587 to (depending on the command used) the highest or lowest priority."
2588 :group 'org-priorities
2589 :type 'character)
2591 (defcustom org-priority-start-cycle-with-default t
2592 "Non-nil means start with default priority when starting to cycle.
2593 When this is nil, the first step in the cycle will be (depending on the
2594 command used) one higher or lower than the default priority.
2595 See also `org-default-priority'."
2596 :group 'org-priorities
2597 :type 'boolean)
2599 (defcustom org-get-priority-function nil
2600 "Function to extract the priority from a string.
2601 The string is normally the headline. If this is nil Org computes the
2602 priority from the priority cookie like [#A] in the headline. It returns
2603 an integer, increasing by 1000 for each priority level.
2604 The user can set a different function here, which should take a string
2605 as an argument and return the numeric priority."
2606 :group 'org-priorities
2607 :version "24.1"
2608 :type '(choice
2609 (const nil)
2610 (function)))
2612 (defgroup org-time nil
2613 "Options concerning time stamps and deadlines in Org mode."
2614 :tag "Org Time"
2615 :group 'org)
2617 (defcustom org-time-stamp-rounding-minutes '(0 5)
2618 "Number of minutes to round time stamps to.
2619 \\<org-mode-map>\
2620 These are two values, the first applies when first creating a time stamp.
2621 The second applies when changing it with the commands `S-up' and `S-down'.
2622 When changing the time stamp, this means that it will change in steps
2623 of N minutes, as given by the second value.
2625 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2626 numbers should be factors of 60, so for example 5, 10, 15.
2628 When this is larger than 1, you can still force an exact time stamp by using
2629 a double prefix argument to a time stamp command like \
2630 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
2631 and by using a prefix arg to `S-up/down' to specify the exact number
2632 of minutes to shift."
2633 :group 'org-time
2634 :get (lambda (var) ; Make sure both elements are there
2635 (if (integerp (default-value var))
2636 (list (default-value var) 5)
2637 (default-value var)))
2638 :type '(list
2639 (integer :tag "when inserting times")
2640 (integer :tag "when modifying times")))
2642 ;; Normalize old customizations of this variable.
2643 (when (integerp org-time-stamp-rounding-minutes)
2644 (setq org-time-stamp-rounding-minutes
2645 (list org-time-stamp-rounding-minutes
2646 org-time-stamp-rounding-minutes)))
2648 (defcustom org-display-custom-times nil
2649 "Non-nil means overlay custom formats over all time stamps.
2650 The formats are defined through the variable `org-time-stamp-custom-formats'.
2651 To turn this on on a per-file basis, insert anywhere in the file:
2652 #+STARTUP: customtime"
2653 :group 'org-time
2654 :set 'set-default
2655 :type 'sexp)
2656 (make-variable-buffer-local 'org-display-custom-times)
2658 (defcustom org-time-stamp-custom-formats
2659 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2660 "Custom formats for time stamps. See `format-time-string' for the syntax.
2661 These are overlaid over the default ISO format if the variable
2662 `org-display-custom-times' is set. Time like %H:%M should be at the
2663 end of the second format. The custom formats are also honored by export
2664 commands, if custom time display is turned on at the time of export."
2665 :group 'org-time
2666 :type 'sexp)
2668 (defun org-time-stamp-format (&optional long inactive)
2669 "Get the right format for a time string."
2670 (let ((f (if long (cdr org-time-stamp-formats)
2671 (car org-time-stamp-formats))))
2672 (if inactive
2673 (concat "[" (substring f 1 -1) "]")
2674 f)))
2676 (defcustom org-deadline-warning-days 14
2677 "Number of days before expiration during which a deadline becomes active.
2678 This variable governs the display in sparse trees and in the agenda.
2679 When 0 or negative, it means use this number (the absolute value of it)
2680 even if a deadline has a different individual lead time specified.
2682 Custom commands can set this variable in the options section."
2683 :group 'org-time
2684 :group 'org-agenda-daily/weekly
2685 :type 'integer)
2687 (defcustom org-scheduled-delay-days 0
2688 "Number of days before a scheduled item becomes active.
2689 This variable governs the display in sparse trees and in the agenda.
2690 The default value (i.e. 0) means: don't delay scheduled item.
2691 When negative, it means use this number (the absolute value of it)
2692 even if a scheduled item has a different individual delay time
2693 specified.
2695 Custom commands can set this variable in the options section."
2696 :group 'org-time
2697 :group 'org-agenda-daily/weekly
2698 :version "24.4"
2699 :package-version '(Org . "8.0")
2700 :type 'integer)
2702 (defcustom org-read-date-prefer-future t
2703 "Non-nil means assume future for incomplete date input from user.
2704 This affects the following situations:
2705 1. The user gives a month but not a year.
2706 For example, if it is April and you enter \"feb 2\", this will be read
2707 as Feb 2, *next* year. \"May 5\", however, will be this year.
2708 2. The user gives a day, but no month.
2709 For example, if today is the 15th, and you enter \"3\", Org will read
2710 this as the third of *next* month. However, if you enter \"17\",
2711 it will be considered as *this* month.
2713 If you set this variable to the symbol `time', then also the following
2714 will work:
2716 3. If the user gives a time.
2717 If the time is before now, it will be interpreted as tomorrow.
2719 Currently none of this works for ISO week specifications.
2721 When this option is nil, the current day, month and year will always be
2722 used as defaults.
2724 See also `org-agenda-jump-prefer-future'."
2725 :group 'org-time
2726 :type '(choice
2727 (const :tag "Never" nil)
2728 (const :tag "Check month and day" t)
2729 (const :tag "Check month, day, and time" time)))
2731 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2732 "Should the agenda jump command prefer the future for incomplete dates?
2733 The default is to do the same as configured in `org-read-date-prefer-future'.
2734 But you can also set a deviating value here.
2735 This may t or nil, or the symbol `org-read-date-prefer-future'."
2736 :group 'org-agenda
2737 :group 'org-time
2738 :version "24.1"
2739 :type '(choice
2740 (const :tag "Use org-read-date-prefer-future"
2741 org-read-date-prefer-future)
2742 (const :tag "Never" nil)
2743 (const :tag "Always" t)))
2745 (defcustom org-read-date-force-compatible-dates t
2746 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2748 Depending on the system Emacs is running on, certain dates cannot
2749 be represented with the type used internally to represent time.
2750 Dates between 1970-1-1 and 2038-1-1 can always be represented
2751 correctly. Some systems allow for earlier dates, some for later,
2752 some for both. One way to find out is to insert any date into an
2753 Org buffer, putting the cursor on the year and hitting S-up and
2754 S-down to test the range.
2756 When this variable is set to t, the date/time prompt will not let
2757 you specify dates outside the 1970-2037 range, so it is certain that
2758 these dates will work in whatever version of Emacs you are
2759 running, and also that you can move a file from one Emacs implementation
2760 to another. Whenever Org is forcing the year for you, it will display
2761 a message and beep.
2763 When this variable is nil, Org will check if the date is
2764 representable in the specific Emacs implementation you are using.
2765 If not, it will force a year, usually the current year, and beep
2766 to remind you. Currently this setting is not recommended because
2767 the likelihood that you will open your Org files in an Emacs that
2768 has limited date range is not negligible.
2770 A workaround for this problem is to use diary sexp dates for time
2771 stamps outside of this range."
2772 :group 'org-time
2773 :version "24.1"
2774 :type 'boolean)
2776 (defcustom org-read-date-display-live t
2777 "Non-nil means display current interpretation of date prompt live.
2778 This display will be in an overlay, in the minibuffer."
2779 :group 'org-time
2780 :type 'boolean)
2782 (defvaralias 'org-popup-calendar-for-date-prompt
2783 'org-read-date-popup-calendar)
2785 (defcustom org-read-date-popup-calendar t
2786 "Non-nil means pop up a calendar when prompting for a date.
2787 In the calendar, the date can be selected with mouse-1. However, the
2788 minibuffer will also be active, and you can simply enter the date as well.
2789 When nil, only the minibuffer will be available."
2790 :group 'org-time
2791 :type 'boolean)
2793 (defcustom org-extend-today-until 0
2794 "The hour when your day really ends. Must be an integer.
2795 This has influence for the following applications:
2796 - When switching the agenda to \"today\". It it is still earlier than
2797 the time given here, the day recognized as TODAY is actually yesterday.
2798 - When a date is read from the user and it is still before the time given
2799 here, the current date and time will be assumed to be yesterday, 23:59.
2800 Also, timestamps inserted in capture templates follow this rule.
2802 IMPORTANT: This is a feature whose implementation is and likely will
2803 remain incomplete. Really, it is only here because past midnight seems to
2804 be the favorite working time of John Wiegley :-)"
2805 :group 'org-time
2806 :type 'integer)
2808 (defcustom org-use-effective-time nil
2809 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2810 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2811 \"effective time\" of any timestamps between midnight and 8am will be
2812 23:59 of the previous day."
2813 :group 'org-time
2814 :version "24.1"
2815 :type 'boolean)
2817 (defcustom org-use-last-clock-out-time-as-effective-time nil
2818 "When non-nil, use the last clock out time for `org-todo'.
2819 Note that this option has precedence over the combined use of
2820 `org-use-effective-time' and `org-extend-today-until'."
2821 :group 'org-time
2822 :version "24.4"
2823 :package-version '(Org . "8.0")
2824 :type 'boolean)
2826 (defcustom org-edit-timestamp-down-means-later nil
2827 "Non-nil means S-down will increase the time in a time stamp.
2828 When nil, S-up will increase."
2829 :group 'org-time
2830 :type 'boolean)
2832 (defcustom org-calendar-follow-timestamp-change t
2833 "Non-nil means make the calendar window follow timestamp changes.
2834 When a timestamp is modified and the calendar window is visible, it will be
2835 moved to the new date."
2836 :group 'org-time
2837 :type 'boolean)
2839 (defgroup org-tags nil
2840 "Options concerning tags in Org mode."
2841 :tag "Org Tags"
2842 :group 'org)
2844 (defcustom org-tag-alist nil
2845 "Default tags available in Org files.
2847 The value of this variable is an alist. Associations either:
2849 (TAG)
2850 (TAG . SELECT)
2851 (SPECIAL)
2853 where TAG is a tag as a string, SELECT is character, used to
2854 select that tag through the fast tag selection interface, and
2855 SPECIAL is one of the following keywords: `:startgroup',
2856 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
2857 `:newline'. These keywords are used to define a hierarchy of
2858 tags. See manual for details.
2860 When this variable is nil, Org mode bases tag input on what is
2861 already in the buffer. The value can be overridden locally by
2862 using a TAGS keyword, e.g.,
2864 #+TAGS: tag1 tag2
2866 See also `org-tag-persistent-alist' to sidestep this behavior."
2867 :group 'org-tags
2868 :type '(repeat
2869 (choice
2870 (cons :tag "Tag with key"
2871 (string :tag "Tag name")
2872 (character :tag "Access char"))
2873 (list :tag "Tag" (string :tag "Tag name"))
2874 (const :tag "Start radio group" (:startgroup))
2875 (const :tag "Start tag group, non distinct" (:startgrouptag))
2876 (const :tag "Group tags delimiter" (:grouptags))
2877 (const :tag "End radio group" (:endgroup))
2878 (const :tag "End tag group, non distinct" (:endgrouptag))
2879 (const :tag "New line" (:newline)))))
2881 (defcustom org-tag-persistent-alist nil
2882 "Tags always available in Org files.
2884 The value of this variable is an alist. Associations either:
2886 (TAG)
2887 (TAG . SELECT)
2888 (SPECIAL)
2890 where TAG is a tag as a string, SELECT is a character, used to
2891 select that tag through the fast tag selection interface, and
2892 SPECIAL is one of the following keywords: `:startgroup',
2893 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
2894 `:newline'. These keywords are used to define a hierarchy of
2895 tags. See manual for details.
2897 Unlike to `org-tag-alist', tags defined in this variable do not
2898 depend on a local TAGS keyword. Instead, to disable these tags
2899 on a per-file basis, insert anywhere in the file:
2901 #+STARTUP: noptag"
2902 :group 'org-tags
2903 :type '(repeat
2904 (choice
2905 (cons :tag "Tag with key"
2906 (string :tag "Tag name")
2907 (character :tag "Access char"))
2908 (list :tag "Tag" (string :tag "Tag name"))
2909 (const :tag "Start radio group" (:startgroup))
2910 (const :tag "Start tag group, non distinct" (:startgrouptag))
2911 (const :tag "Group tags delimiter" (:grouptags))
2912 (const :tag "End radio group" (:endgroup))
2913 (const :tag "End tag group, non distinct" (:endgrouptag))
2914 (const :tag "New line" (:newline)))))
2916 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2917 "If non-nil, always offer completion for all tags of all agenda files.
2919 Setting this variable locally allows for dynamic generation of tag
2920 completions in capture buffers.
2922 (add-hook \\='org-capture-mode-hook
2923 (lambda ()
2924 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
2925 :group 'org-tags
2926 :version "24.1"
2927 :type 'boolean)
2929 (defvar org-file-tags nil
2930 "List of tags that can be inherited by all entries in the file.
2931 The tags will be inherited if the variable `org-use-tag-inheritance'
2932 says they should be.
2933 This variable is populated from #+FILETAGS lines.")
2935 (defcustom org-use-fast-tag-selection 'auto
2936 "Non-nil means use fast tag selection scheme.
2937 This is a special interface to select and deselect tags with single keys.
2938 When nil, fast selection is never used.
2939 When the symbol `auto', fast selection is used if and only if selection
2940 characters for tags have been configured, either through the variable
2941 `org-tag-alist' or through a #+TAGS line in the buffer.
2942 When t, fast selection is always used and selection keys are assigned
2943 automatically if necessary."
2944 :group 'org-tags
2945 :type '(choice
2946 (const :tag "Always" t)
2947 (const :tag "Never" nil)
2948 (const :tag "When selection characters are configured" auto)))
2950 (defcustom org-fast-tag-selection-single-key nil
2951 "Non-nil means fast tag selection exits after first change.
2952 When nil, you have to press RET to exit it.
2953 During fast tag selection, you can toggle this flag with `C-c'.
2954 This variable can also have the value `expert'. In this case, the window
2955 displaying the tags menu is not even shown, until you press C-c again."
2956 :group 'org-tags
2957 :type '(choice
2958 (const :tag "No" nil)
2959 (const :tag "Yes" t)
2960 (const :tag "Expert" expert)))
2962 (defvar org-fast-tag-selection-include-todo nil
2963 "Non-nil means fast tags selection interface will also offer TODO states.
2964 This is an undocumented feature, you should not rely on it.")
2966 (defcustom org-tags-column -77
2967 "The column to which tags should be indented in a headline.
2968 If this number is positive, it specifies the column. If it is negative,
2969 it means that the tags should be flushright to that column. For example,
2970 -80 works well for a normal 80 character screen.
2971 When 0, place tags directly after headline text, with only one space in
2972 between."
2973 :group 'org-tags
2974 :type 'integer)
2976 (defcustom org-auto-align-tags t
2977 "Non-nil keeps tags aligned when modifying headlines.
2978 Some operations (i.e. demoting) change the length of a headline and
2979 therefore shift the tags around. With this option turned on, after
2980 each such operation the tags are again aligned to `org-tags-column'."
2981 :group 'org-tags
2982 :type 'boolean)
2984 (defcustom org-use-tag-inheritance t
2985 "Non-nil means tags in levels apply also for sublevels.
2986 When nil, only the tags directly given in a specific line apply there.
2987 This may also be a list of tags that should be inherited, or a regexp that
2988 matches tags that should be inherited. Additional control is possible
2989 with the variable `org-tags-exclude-from-inheritance' which gives an
2990 explicit list of tags to be excluded from inheritance, even if the value of
2991 `org-use-tag-inheritance' would select it for inheritance.
2993 If this option is t, a match early-on in a tree can lead to a large
2994 number of matches in the subtree when constructing the agenda or creating
2995 a sparse tree. If you only want to see the first match in a tree during
2996 a search, check out the variable `org-tags-match-list-sublevels'."
2997 :group 'org-tags
2998 :type '(choice
2999 (const :tag "Not" nil)
3000 (const :tag "Always" t)
3001 (repeat :tag "Specific tags" (string :tag "Tag"))
3002 (regexp :tag "Tags matched by regexp")))
3004 (defcustom org-tags-exclude-from-inheritance nil
3005 "List of tags that should never be inherited.
3006 This is a way to exclude a few tags from inheritance. For way to do
3007 the opposite, to actively allow inheritance for selected tags,
3008 see the variable `org-use-tag-inheritance'."
3009 :group 'org-tags
3010 :type '(repeat (string :tag "Tag")))
3012 (defun org-tag-inherit-p (tag)
3013 "Check if TAG is one that should be inherited."
3014 (cond
3015 ((member tag org-tags-exclude-from-inheritance) nil)
3016 ((eq org-use-tag-inheritance t) t)
3017 ((not org-use-tag-inheritance) nil)
3018 ((stringp org-use-tag-inheritance)
3019 (string-match org-use-tag-inheritance tag))
3020 ((listp org-use-tag-inheritance)
3021 (member tag org-use-tag-inheritance))
3022 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3024 (defcustom org-tags-match-list-sublevels t
3025 "Non-nil means list also sublevels of headlines matching a search.
3026 This variable applies to tags/property searches, and also to stuck
3027 projects because this search is based on a tags match as well.
3029 When set to the symbol `indented', sublevels are indented with
3030 leading dots.
3032 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3033 the sublevels of a headline matching a tag search often also match
3034 the same search. Listing all of them can create very long lists.
3035 Setting this variable to nil causes subtrees of a match to be skipped.
3037 This variable is semi-obsolete and probably should always be true. It
3038 is better to limit inheritance to certain tags using the variables
3039 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3040 :group 'org-tags
3041 :type '(choice
3042 (const :tag "No, don't list them" nil)
3043 (const :tag "Yes, do list them" t)
3044 (const :tag "List them, indented with leading dots" indented)))
3046 (defcustom org-tags-sort-function nil
3047 "When set, tags are sorted using this function as a comparator."
3048 :group 'org-tags
3049 :type '(choice
3050 (const :tag "No sorting" nil)
3051 (const :tag "Alphabetical" org-string-collate-lessp)
3052 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3053 (function :tag "Custom function" nil)))
3055 (defvar org-tags-history nil
3056 "History of minibuffer reads for tags.")
3057 (defvar org-last-tags-completion-table nil
3058 "The last used completion table for tags.")
3059 (defvar org-after-tags-change-hook nil
3060 "Hook that is run after the tags in a line have changed.")
3062 (defgroup org-properties nil
3063 "Options concerning properties in Org mode."
3064 :tag "Org Properties"
3065 :group 'org)
3067 (defcustom org-property-format "%-10s %s"
3068 "How property key/value pairs should be formatted by `indent-line'.
3069 When `indent-line' hits a property definition, it will format the line
3070 according to this format, mainly to make sure that the values are
3071 lined-up with respect to each other."
3072 :group 'org-properties
3073 :type 'string)
3075 (defcustom org-properties-postprocess-alist nil
3076 "Alist of properties and functions to adjust inserted values.
3077 Elements of this alist must be of the form
3079 ([string] [function])
3081 where [string] must be a property name and [function] must be a
3082 lambda expression: this lambda expression must take one argument,
3083 the value to adjust, and return the new value as a string.
3085 For example, this element will allow the property \"Remaining\"
3086 to be updated wrt the relation between the \"Effort\" property
3087 and the clock summary:
3089 ((\"Remaining\" (lambda(value)
3090 (let ((clocksum (org-clock-sum-current-item))
3091 (effort (org-duration-to-minutes
3092 (org-entry-get (point) \"Effort\"))))
3093 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3094 :group 'org-properties
3095 :version "24.1"
3096 :type '(alist :key-type (string :tag "Property")
3097 :value-type (function :tag "Function")))
3099 (defcustom org-use-property-inheritance nil
3100 "Non-nil means properties apply also for sublevels.
3102 This setting is chiefly used during property searches. Turning it on can
3103 cause significant overhead when doing a search, which is why it is not
3104 on by default.
3106 When nil, only the properties directly given in the current entry count.
3107 When t, every property is inherited. The value may also be a list of
3108 properties that should have inheritance, or a regular expression matching
3109 properties that should be inherited.
3111 However, note that some special properties use inheritance under special
3112 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3113 and the properties ending in \"_ALL\" when they are used as descriptor
3114 for valid values of a property.
3116 Note for programmers:
3117 When querying an entry with `org-entry-get', you can control if inheritance
3118 should be used. By default, `org-entry-get' looks only at the local
3119 properties. You can request inheritance by setting the inherit argument
3120 to t (to force inheritance) or to `selective' (to respect the setting
3121 in this variable)."
3122 :group 'org-properties
3123 :type '(choice
3124 (const :tag "Not" nil)
3125 (const :tag "Always" t)
3126 (repeat :tag "Specific properties" (string :tag "Property"))
3127 (regexp :tag "Properties matched by regexp")))
3129 (defun org-property-inherit-p (property)
3130 "Return a non-nil value if PROPERTY should be inherited."
3131 (cond
3132 ((eq org-use-property-inheritance t) t)
3133 ((not org-use-property-inheritance) nil)
3134 ((stringp org-use-property-inheritance)
3135 (string-match org-use-property-inheritance property))
3136 ((listp org-use-property-inheritance)
3137 (member-ignore-case property org-use-property-inheritance))
3138 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3140 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3141 "The default column format, if no other format has been defined.
3142 This variable can be set on the per-file basis by inserting a line
3144 #+COLUMNS: %25ITEM ....."
3145 :group 'org-properties
3146 :type 'string)
3148 (defcustom org-columns-ellipses ".."
3149 "The ellipses to be used when a field in column view is truncated.
3150 When this is the empty string, as many characters as possible are shown,
3151 but then there will be no visual indication that the field has been truncated.
3152 When this is a string of length N, the last N characters of a truncated
3153 field are replaced by this string. If the column is narrower than the
3154 ellipses string, only part of the ellipses string will be shown."
3155 :group 'org-properties
3156 :type 'string)
3158 (defconst org-global-properties-fixed
3159 '(("VISIBILITY_ALL" . "folded children content all")
3160 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3161 "List of property/value pairs that can be inherited by any entry.
3163 These are fixed values, for the preset properties. The user variable
3164 that can be used to add to this list is `org-global-properties'.
3166 The entries in this list are cons cells where the car is a property
3167 name and cdr is a string with the value. If the value represents
3168 multiple items like an \"_ALL\" property, separate the items by
3169 spaces.")
3171 (defcustom org-global-properties nil
3172 "List of property/value pairs that can be inherited by any entry.
3174 This list will be combined with the constant `org-global-properties-fixed'.
3176 The entries in this list are cons cells where the car is a property
3177 name and cdr is a string with the value.
3179 You can set buffer-local values for the same purpose in the variable
3180 `org-file-properties' this by adding lines like
3182 #+PROPERTY: NAME VALUE"
3183 :group 'org-properties
3184 :type '(repeat
3185 (cons (string :tag "Property")
3186 (string :tag "Value"))))
3188 (defvar-local org-file-properties nil
3189 "List of property/value pairs that can be inherited by any entry.
3190 Valid for the current buffer.
3191 This variable is populated from #+PROPERTY lines.")
3193 (defgroup org-agenda nil
3194 "Options concerning agenda views in Org mode."
3195 :tag "Org Agenda"
3196 :group 'org)
3198 (defvar-local org-category nil
3199 "Variable used by Org files to set a category for agenda display.
3200 Such files should use a file variable to set it, for example
3202 # -*- mode: org; org-category: \"ELisp\"
3204 or contain a special line
3206 #+CATEGORY: ELisp
3208 If the file does not specify a category, then file's base name
3209 is used instead.")
3210 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3212 (defcustom org-agenda-files nil
3213 "The files to be used for agenda display.
3215 If an entry is a directory, all files in that directory that are matched
3216 by `org-agenda-file-regexp' will be part of the file list.
3218 If the value of the variable is not a list but a single file name, then
3219 the list of agenda files is actually stored and maintained in that file,
3220 one agenda file per line. In this file paths can be given relative to
3221 `org-directory'. Tilde expansion and environment variable substitution
3222 are also made.
3224 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3225 and removed with `\\[org-remove-file]'."
3226 :group 'org-agenda
3227 :type '(choice
3228 (repeat :tag "List of files and directories" file)
3229 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3231 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3232 "Regular expression to match files for `org-agenda-files'.
3233 If any element in the list in that variable contains a directory instead
3234 of a normal file, all files in that directory that are matched by this
3235 regular expression will be included."
3236 :group 'org-agenda
3237 :type 'regexp)
3239 (defvaralias 'org-agenda-multi-occur-extra-files
3240 'org-agenda-text-search-extra-files)
3242 (defcustom org-agenda-text-search-extra-files nil
3243 "List of extra files to be searched by text search commands.
3244 These files will be searched in addition to the agenda files by the
3245 commands `org-search-view' (`\\[org-agenda] s') \
3246 and `org-occur-in-agenda-files'.
3247 Note that these files will only be searched for text search commands,
3248 not for the other agenda views like todo lists, tag searches or the weekly
3249 agenda. This variable is intended to list notes and possibly archive files
3250 that should also be searched by these two commands.
3251 In fact, if the first element in the list is the symbol `agenda-archives',
3252 then all archive files of all agenda files will be added to the search
3253 scope."
3254 :group 'org-agenda
3255 :type '(set :greedy t
3256 (const :tag "Agenda Archives" agenda-archives)
3257 (repeat :inline t (file))))
3259 (defcustom org-agenda-skip-unavailable-files nil
3260 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3261 A nil value means to remove them, after a query, from the list."
3262 :group 'org-agenda
3263 :type 'boolean)
3265 (defcustom org-agenda-diary-file 'diary-file
3266 "File to which to add new entries with the `i' key in agenda and calendar.
3267 When this is the symbol `diary-file', the functionality in the Emacs
3268 calendar will be used to add entries to the `diary-file'. But when this
3269 points to a file, `org-agenda-diary-entry' will be used instead."
3270 :group 'org-agenda
3271 :type '(choice
3272 (const :tag "The standard Emacs diary file" diary-file)
3273 (file :tag "Special Org file diary entries")))
3275 (defgroup org-latex nil
3276 "Options for embedding LaTeX code into Org mode."
3277 :tag "Org LaTeX"
3278 :group 'org)
3280 (defcustom org-format-latex-options
3281 '(:foreground default :background default :scale 1.0
3282 :html-foreground "Black" :html-background "Transparent"
3283 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3284 "Options for creating images from LaTeX fragments.
3285 This is a property list with the following properties:
3286 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3287 `default' means use the foreground of the default face.
3288 `auto' means use the foreground from the text face.
3289 :background the background color, or \"Transparent\".
3290 `default' means use the background of the default face.
3291 `auto' means use the background from the text face.
3292 :scale a scaling factor for the size of the images, to get more pixels
3293 :html-foreground, :html-background, :html-scale
3294 the same numbers for HTML export.
3295 :matchers a list indicating which matchers should be used to
3296 find LaTeX fragments. Valid members of this list are:
3297 \"begin\" find environments
3298 \"$1\" find single characters surrounded by $.$
3299 \"$\" find math expressions surrounded by $...$
3300 \"$$\" find math expressions surrounded by $$....$$
3301 \"\\(\" find math expressions surrounded by \\(...\\)
3302 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3303 :group 'org-latex
3304 :type 'plist)
3306 (defcustom org-format-latex-signal-error t
3307 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3308 When nil, just push out a message."
3309 :group 'org-latex
3310 :version "24.1"
3311 :type 'boolean)
3313 (defcustom org-latex-to-mathml-jar-file nil
3314 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3315 Use this to specify additional executable file say a jar file.
3317 When using MathToWeb as the converter, specify the full-path to
3318 your mathtoweb.jar file."
3319 :group 'org-latex
3320 :version "24.1"
3321 :type '(choice
3322 (const :tag "None" nil)
3323 (file :tag "JAR file" :must-match t)))
3325 (defcustom org-latex-to-mathml-convert-command nil
3326 "Command to convert LaTeX fragments to MathML.
3327 Replace format-specifiers in the command as noted below and use
3328 `shell-command' to convert LaTeX to MathML.
3329 %j: Executable file in fully expanded form as specified by
3330 `org-latex-to-mathml-jar-file'.
3331 %I: Input LaTeX file in fully expanded form.
3332 %i: The latex fragment to be converted.
3333 %o: Output MathML file.
3335 This command is used by `org-create-math-formula'.
3337 When using MathToWeb as the converter, set this option to
3338 \"java -jar %j -unicode -force -df %o %I\".
3340 When using LaTeXML set this option to
3341 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3342 :group 'org-latex
3343 :version "24.1"
3344 :type '(choice
3345 (const :tag "None" nil)
3346 (string :tag "\nShell command")))
3348 (defcustom org-preview-latex-default-process 'dvipng
3349 "The default process to convert LaTeX fragments to image files.
3350 All available processes and theirs documents can be found in
3351 `org-preview-latex-process-alist', which see."
3352 :group 'org-latex
3353 :version "26.1"
3354 :package-version '(Org . "9.0")
3355 :type 'symbol)
3357 (defcustom org-preview-latex-process-alist
3358 '((dvipng
3359 :programs ("latex" "dvipng")
3360 :description "dvi > png"
3361 :message "you need to install the programs: latex and dvipng."
3362 :image-input-type "dvi"
3363 :image-output-type "png"
3364 :image-size-adjust (1.0 . 1.0)
3365 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3366 :image-converter ("dvipng -D %D -T tight -o %O %f"))
3367 (dvisvgm
3368 :programs ("latex" "dvisvgm")
3369 :description "dvi > svg"
3370 :message "you need to install the programs: latex and dvisvgm."
3371 :image-input-type "dvi"
3372 :image-output-type "svg"
3373 :image-size-adjust (1.7 . 1.5)
3374 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3375 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3376 (imagemagick
3377 :programs ("latex" "convert")
3378 :description "pdf > png"
3379 :message "you need to install the programs: latex and imagemagick."
3380 :image-input-type "pdf"
3381 :image-output-type "png"
3382 :image-size-adjust (1.0 . 1.0)
3383 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3384 :image-converter
3385 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3386 "Definitions of external processes for LaTeX previewing.
3387 Org mode can use some external commands to generate TeX snippet's images for
3388 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3389 `org-create-formula-image' how to call them.
3391 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3392 PROPERTIES accepts the following attributes:
3394 :programs list of strings, required programs.
3395 :description string, describe the process.
3396 :message string, message it when required programs cannot be found.
3397 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3398 :image-output-type string, output file type of image converter (e.g., \"png\").
3399 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3400 image size showed in buffer and the cdr element is for
3401 HTML file. This option is only useful for process
3402 developers, users should use variable
3403 `org-format-latex-options' instead.
3404 :post-clean list of strings, files matched are to be cleaned up once
3405 the image is generated. When nil, the files with \".dvi\",
3406 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3407 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3408 be cleaned up.
3409 :latex-header list of strings, the LaTeX header of the snippet file.
3410 When nil, the fallback value is used instead, which is
3411 controlled by `org-format-latex-header',
3412 `org-latex-default-packages-alist' and
3413 `org-latex-packages-alist', which see.
3414 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3415 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3416 replaced with values defined below.
3417 :image-converter list of image converter commands strings. Each of them is
3418 given to the shell and supports any of the following
3419 place-holders defined below.
3421 Place-holders used by `:image-converter' and `:latex-compiler':
3423 %f input file name
3424 %b base name of input file
3425 %o base directory of input file
3426 %O absolute output file name
3428 Place-holders only used by `:image-converter':
3430 %D dpi, which is used to adjust image size by some processing commands.
3431 %S the image size scale ratio, which is used to adjust image size by some
3432 processing commands."
3433 :group 'org-latex
3434 :version "26.1"
3435 :package-version '(Org . "9.0")
3436 :type '(alist :tag "LaTeX to image backends"
3437 :value-type (plist)))
3439 (defcustom org-preview-latex-image-directory "ltximg/"
3440 "Path to store latex preview images.
3441 A relative path here creates many directories relative to the
3442 processed Org files paths. An absolute path puts all preview
3443 images at the same place."
3444 :group 'org-latex
3445 :version "26.1"
3446 :package-version '(Org . "9.0")
3447 :type 'string)
3449 (defun org-format-latex-mathml-available-p ()
3450 "Return t if `org-latex-to-mathml-convert-command' is usable."
3451 (save-match-data
3452 (when (and (boundp 'org-latex-to-mathml-convert-command)
3453 org-latex-to-mathml-convert-command)
3454 (let ((executable (car (split-string
3455 org-latex-to-mathml-convert-command))))
3456 (when (executable-find executable)
3457 (if (string-match
3458 "%j" org-latex-to-mathml-convert-command)
3459 (file-readable-p org-latex-to-mathml-jar-file)
3460 t))))))
3462 (defcustom org-format-latex-header "\\documentclass{article}
3463 \\usepackage[usenames]{color}
3464 \[PACKAGES]
3465 \[DEFAULT-PACKAGES]
3466 \\pagestyle{empty} % do not remove
3467 % The settings below are copied from fullpage.sty
3468 \\setlength{\\textwidth}{\\paperwidth}
3469 \\addtolength{\\textwidth}{-3cm}
3470 \\setlength{\\oddsidemargin}{1.5cm}
3471 \\addtolength{\\oddsidemargin}{-2.54cm}
3472 \\setlength{\\evensidemargin}{\\oddsidemargin}
3473 \\setlength{\\textheight}{\\paperheight}
3474 \\addtolength{\\textheight}{-\\headheight}
3475 \\addtolength{\\textheight}{-\\headsep}
3476 \\addtolength{\\textheight}{-\\footskip}
3477 \\addtolength{\\textheight}{-3cm}
3478 \\setlength{\\topmargin}{1.5cm}
3479 \\addtolength{\\topmargin}{-2.54cm}"
3480 "The document header used for processing LaTeX fragments.
3481 It is imperative that this header make sure that no page number
3482 appears on the page. The package defined in the variables
3483 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3484 will either replace the placeholder \"[PACKAGES]\" in this
3485 header, or they will be appended."
3486 :group 'org-latex
3487 :type 'string)
3489 (defun org-set-packages-alist (var val)
3490 "Set the packages alist and make sure it has 3 elements per entry."
3491 (set var (mapcar (lambda (x)
3492 (if (and (consp x) (= (length x) 2))
3493 (list (car x) (nth 1 x) t)
3495 val)))
3497 (defun org-get-packages-alist (var)
3498 "Get the packages alist and make sure it has 3 elements per entry."
3499 (mapcar (lambda (x)
3500 (if (and (consp x) (= (length x) 2))
3501 (list (car x) (nth 1 x) t)
3503 (default-value var)))
3505 (defcustom org-latex-default-packages-alist
3506 '(("AUTO" "inputenc" t ("pdflatex"))
3507 ("T1" "fontenc" t ("pdflatex"))
3508 ("" "graphicx" t)
3509 ("" "grffile" t)
3510 ("" "longtable" nil)
3511 ("" "wrapfig" nil)
3512 ("" "rotating" nil)
3513 ("normalem" "ulem" t)
3514 ("" "amsmath" t)
3515 ("" "textcomp" t)
3516 ("" "amssymb" t)
3517 ("" "capt-of" nil)
3518 ("" "hyperref" nil))
3519 "Alist of default packages to be inserted in the header.
3521 Change this only if one of the packages here causes an
3522 incompatibility with another package you are using.
3524 The packages in this list are needed by one part or another of
3525 Org mode to function properly:
3527 - inputenc, fontenc: for basic font and character selection
3528 - graphicx: for including images
3529 - grffile: allow periods and spaces in graphics file names
3530 - longtable: For multipage tables
3531 - wrapfig: for figure placement
3532 - rotating: for sideways figures and tables
3533 - ulem: for underline and strike-through
3534 - amsmath: for subscript and superscript and math environments
3535 - textcomp, amssymb: for various symbols used
3536 for interpreting the entities in `org-entities'. You can skip
3537 some of these packages if you don't use any of their symbols.
3538 - capt-of: for captions outside of floats
3539 - hyperref: for cross references
3541 Therefore you should not modify this variable unless you know
3542 what you are doing. The one reason to change it anyway is that
3543 you might be loading some other package that conflicts with one
3544 of the default packages. Each element is either a cell or
3545 a string.
3547 A cell is of the format
3549 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
3551 If SNIPPET-FLAG is non-nil, the package also needs to be included
3552 when compiling LaTeX snippets into images for inclusion into
3553 non-LaTeX output.
3555 COMPILERS is a list of compilers that should include the package,
3556 see `org-latex-compiler'. If the document compiler is not in the
3557 list, and the list is non-nil, the package will not be inserted
3558 in the final document.
3560 A string will be inserted as-is in the header of the document."
3561 :group 'org-latex
3562 :group 'org-export-latex
3563 :set 'org-set-packages-alist
3564 :get 'org-get-packages-alist
3565 :version "26.1"
3566 :package-version '(Org . "8.3")
3567 :type '(repeat
3568 (choice
3569 (list :tag "options/package pair"
3570 (string :tag "options")
3571 (string :tag "package")
3572 (boolean :tag "Snippet")
3573 (choice
3574 (const :tag "For all compilers" nil)
3575 (repeat :tag "Allowed compiler" string)))
3576 (string :tag "A line of LaTeX"))))
3578 (defcustom org-latex-packages-alist nil
3579 "Alist of packages to be inserted in every LaTeX header.
3581 These will be inserted after `org-latex-default-packages-alist'.
3582 Each element is either a cell or a string.
3584 A cell is of the format:
3586 (\"options\" \"package\" SNIPPET-FLAG)
3588 SNIPPET-FLAG, when non-nil, indicates that this package is also
3589 needed when turning LaTeX snippets into images for inclusion into
3590 non-LaTeX output.
3592 COMPILERS is a list of compilers that should include the package,
3593 see `org-latex-compiler'. If the document compiler is not in the
3594 list, and the list is non-nil, the package will not be inserted
3595 in the final document.
3597 A string will be inserted as-is in the header of the document.
3599 Make sure that you only list packages here which:
3601 - you want in every file;
3602 - do not conflict with the setup in `org-format-latex-header';
3603 - do not conflict with the default packages in
3604 `org-latex-default-packages-alist'."
3605 :group 'org-latex
3606 :group 'org-export-latex
3607 :set 'org-set-packages-alist
3608 :get 'org-get-packages-alist
3609 :type '(repeat
3610 (choice
3611 (list :tag "options/package pair"
3612 (string :tag "options")
3613 (string :tag "package")
3614 (boolean :tag "Snippet"))
3615 (string :tag "A line of LaTeX"))))
3617 (defgroup org-appearance nil
3618 "Settings for Org mode appearance."
3619 :tag "Org Appearance"
3620 :group 'org)
3622 (defcustom org-level-color-stars-only nil
3623 "Non-nil means fontify only the stars in each headline.
3624 When nil, the entire headline is fontified.
3625 Changing it requires restart of `font-lock-mode' to become effective
3626 also in regions already fontified."
3627 :group 'org-appearance
3628 :type 'boolean)
3630 (defcustom org-hide-leading-stars nil
3631 "Non-nil means hide the first N-1 stars in a headline.
3632 This works by using the face `org-hide' for these stars. This
3633 face is white for a light background, and black for a dark
3634 background. You may have to customize the face `org-hide' to
3635 make this work.
3636 Changing it requires restart of `font-lock-mode' to become effective
3637 also in regions already fontified.
3638 You may also set this on a per-file basis by adding one of the following
3639 lines to the buffer:
3641 #+STARTUP: hidestars
3642 #+STARTUP: showstars"
3643 :group 'org-appearance
3644 :type 'boolean)
3646 (defcustom org-hidden-keywords nil
3647 "List of symbols corresponding to keywords to be hidden in the Org buffer.
3648 For example, a value \\='(title) for this list makes the document's title
3649 appear in the buffer without the initial \"#+TITLE:\" part."
3650 :group 'org-appearance
3651 :version "24.1"
3652 :type '(set (const :tag "#+AUTHOR" author)
3653 (const :tag "#+DATE" date)
3654 (const :tag "#+EMAIL" email)
3655 (const :tag "#+TITLE" title)))
3657 (defcustom org-custom-properties nil
3658 "List of properties (as strings) with a special meaning.
3659 The default use of these custom properties is to let the user
3660 hide them with `org-toggle-custom-properties-visibility'."
3661 :group 'org-properties
3662 :group 'org-appearance
3663 :version "24.3"
3664 :type '(repeat (string :tag "Property Name")))
3666 (defcustom org-fontify-done-headline nil
3667 "Non-nil means change the face of a headline if it is marked DONE.
3668 Normally, only the TODO/DONE keyword indicates the state of a headline.
3669 When this is non-nil, the headline after the keyword is set to the
3670 `org-headline-done' as an additional indication."
3671 :group 'org-appearance
3672 :type 'boolean)
3674 (defcustom org-fontify-emphasized-text t
3675 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3676 Changing this variable requires a restart of Emacs to take effect."
3677 :group 'org-appearance
3678 :type 'boolean)
3680 (defcustom org-fontify-whole-heading-line nil
3681 "Non-nil means fontify the whole line for headings.
3682 This is useful when setting a background color for the
3683 org-level-* faces."
3684 :group 'org-appearance
3685 :type 'boolean)
3687 (defcustom org-highlight-latex-and-related nil
3688 "Non-nil means highlight LaTeX related syntax in the buffer.
3689 When non nil, the value should be a list containing any of the
3690 following symbols:
3691 `native' Highlight LaTeX snippets and environments natively.
3692 `latex' Highlight LaTeX snippets and environments.
3693 `script' Highlight subscript and superscript.
3694 `entities' Highlight entities."
3695 :group 'org-appearance
3696 :version "24.4"
3697 :package-version '(Org . "8.0")
3698 :type '(choice
3699 (const :tag "No highlighting" nil)
3700 (set :greedy t :tag "Highlight"
3701 (const :tag "LaTeX snippets and environments (native)" native)
3702 (const :tag "LaTeX snippets and environments" latex)
3703 (const :tag "Subscript and superscript" script)
3704 (const :tag "Entities" entities))))
3706 (defcustom org-hide-emphasis-markers nil
3707 "Non-nil mean font-lock should hide the emphasis marker characters."
3708 :group 'org-appearance
3709 :type 'boolean
3710 :safe #'booleanp)
3712 (defcustom org-hide-macro-markers nil
3713 "Non-nil mean font-lock should hide the brackets marking macro calls."
3714 :group 'org-appearance
3715 :type 'boolean)
3717 (defcustom org-pretty-entities nil
3718 "Non-nil means show entities as UTF8 characters.
3719 When nil, the \\name form remains in the buffer."
3720 :group 'org-appearance
3721 :version "24.1"
3722 :type 'boolean)
3724 (defcustom org-pretty-entities-include-sub-superscripts t
3725 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3726 :group 'org-appearance
3727 :version "24.1"
3728 :type 'boolean)
3730 (defvar org-emph-re nil
3731 "Regular expression for matching emphasis.
3732 After a match, the match groups contain these elements:
3733 0 The match of the full regular expression, including the characters
3734 before and after the proper match
3735 1 The character before the proper match, or empty at beginning of line
3736 2 The proper match, including the leading and trailing markers
3737 3 The leading marker like * or /, indicating the type of highlighting
3738 4 The text between the emphasis markers, not including the markers
3739 5 The character after the match, empty at the end of a line")
3741 (defvar org-verbatim-re nil
3742 "Regular expression for matching verbatim text.")
3744 (defvar org-emphasis-regexp-components) ; defined just below
3745 (defvar org-emphasis-alist) ; defined just below
3746 (defun org-set-emph-re (var val)
3747 "Set variable and compute the emphasis regular expression."
3748 (set var val)
3749 (when (and (boundp 'org-emphasis-alist)
3750 (boundp 'org-emphasis-regexp-components)
3751 org-emphasis-alist org-emphasis-regexp-components)
3752 (pcase-let*
3753 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
3754 (body (if (<= nl 0) body
3755 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
3756 (template
3757 (format (concat "\\([%s]\\|^\\)" ;before markers
3758 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
3759 "\\([%s]\\|$\\)") ;after markers
3760 pre border border body border post)))
3761 (setq org-emph-re (format template "*/_+"))
3762 (setq org-verbatim-re (format template "=~")))))
3764 ;; This used to be a defcustom (Org <8.0) but allowing the users to
3765 ;; set this option proved cumbersome. See this message/thread:
3766 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
3767 (defvar org-emphasis-regexp-components
3768 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
3769 "Components used to build the regular expression for emphasis.
3770 This is a list with five entries. Terminology: In an emphasis string
3771 like \" *strong word* \", we call the initial space PREMATCH, the final
3772 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3773 and \"trong wor\" is the body. The different components in this variable
3774 specify what is allowed/forbidden in each part:
3776 pre Chars allowed as prematch. Beginning of line will be allowed too.
3777 post Chars allowed as postmatch. End of line will be allowed too.
3778 border The chars *forbidden* as border characters.
3779 body-regexp A regexp like \".\" to match a body character. Don't use
3780 non-shy groups here, and don't allow newline here.
3781 newline The maximum number of newlines allowed in an emphasis exp.
3783 You need to reload Org or to restart Emacs after setting this.")
3785 (defcustom org-emphasis-alist
3786 '(("*" bold)
3787 ("/" italic)
3788 ("_" underline)
3789 ("=" org-verbatim verbatim)
3790 ("~" org-code verbatim)
3791 ("+" (:strike-through t)))
3792 "Alist of characters and faces to emphasize text.
3793 Text starting and ending with a special character will be emphasized,
3794 for example *bold*, _underlined_ and /italic/. This variable sets the
3795 marker characters and the face to be used by font-lock for highlighting
3796 in Org buffers.
3798 You need to reload Org or to restart Emacs after customizing this."
3799 :group 'org-appearance
3800 :set 'org-set-emph-re
3801 :version "24.4"
3802 :package-version '(Org . "8.0")
3803 :type '(repeat
3804 (list
3805 (string :tag "Marker character")
3806 (choice
3807 (face :tag "Font-lock-face")
3808 (plist :tag "Face property list"))
3809 (option (const verbatim)))))
3811 (defvar org-protecting-blocks '("src" "example" "export")
3812 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3813 This is needed for font-lock setup.")
3815 ;;; Functions and variables from their packages
3816 ;; Declared here to avoid compiler warnings
3817 (defvar mark-active)
3819 ;; Various packages
3820 (declare-function calc-eval "calc" (str &optional separator &rest args))
3821 (declare-function calendar-forward-day "cal-move" (arg))
3822 (declare-function calendar-goto-date "cal-move" (date))
3823 (declare-function calendar-goto-today "cal-move" ())
3824 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3825 (declare-function calendar-iso-to-absolute "cal-iso" (date))
3826 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3827 (declare-function cdlatex-tab "ext:cdlatex" ())
3828 (declare-function dired-get-filename
3829 "dired"
3830 (&optional localp no-error-if-not-filep))
3831 (declare-function iswitchb-read-buffer
3832 "iswitchb"
3833 (prompt &optional
3834 default require-match _predicate start matches-set))
3835 (declare-function org-agenda-change-all-lines
3836 "org-agenda"
3837 (newhead hdmarker &optional fixface just-this))
3838 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3839 "org-agenda"
3840 (&optional end))
3841 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3842 (declare-function org-agenda-format-item
3843 "org-agenda"
3844 (extra txt &optional level category tags dotime
3845 remove-re habitp))
3846 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3847 (declare-function org-agenda-save-markers-for-cut-and-paste
3848 "org-agenda"
3849 (beg end))
3850 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3851 (declare-function org-agenda-skip "org-agenda" ())
3852 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3853 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3854 (declare-function org-indent-mode "org-indent" (&optional arg))
3855 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3856 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3857 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3858 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3859 (declare-function parse-time-string "parse-time" (string))
3861 (defvar align-mode-rules-list)
3862 (defvar calc-embedded-close-formula)
3863 (defvar calc-embedded-open-formula)
3864 (defvar calc-embedded-open-mode)
3865 (defvar font-lock-unfontify-region-function)
3866 (defvar iswitchb-temp-buflist)
3867 (defvar org-agenda-tags-todo-honor-ignore-options)
3868 (defvar remember-data-file)
3869 (defvar texmathp-why)
3871 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3872 (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
3873 (declare-function org-resolve-clocks "org-clock"
3874 (&optional also-non-dangling-p prompt last-valid))
3876 (defvar org-clock-start-time)
3877 (defvar org-clock-marker (make-marker)
3878 "Marker recording the last clock-in.")
3879 (defvar org-clock-hd-marker (make-marker)
3880 "Marker recording the last clock-in, but the headline position.")
3881 (defvar org-clock-heading ""
3882 "The heading of the current clock entry.")
3883 (defun org-clock-is-active ()
3884 "Return the buffer where the clock is currently running.
3885 Return nil if no clock is running."
3886 (marker-buffer org-clock-marker))
3888 (defun org-check-running-clock ()
3889 "Check if the current buffer contains the running clock.
3890 If yes, offer to stop it and to save the buffer with the changes."
3891 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3892 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3893 (buffer-name))))
3894 (org-clock-out)
3895 (when (y-or-n-p "Save changed buffer?")
3896 (save-buffer))))
3898 (defun org-clocktable-try-shift (dir n)
3899 "Check if this line starts a clock table, if yes, shift the time block."
3900 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
3901 (org-clocktable-shift dir n)))
3903 ;;;###autoload
3904 (defun org-clock-persistence-insinuate ()
3905 "Set up hooks for clock persistence."
3906 (require 'org-clock)
3907 (add-hook 'org-mode-hook 'org-clock-load)
3908 (add-hook 'kill-emacs-hook 'org-clock-save))
3910 (defgroup org-archive nil
3911 "Options concerning archiving in Org mode."
3912 :tag "Org Archive"
3913 :group 'org-structure)
3915 (defcustom org-archive-location "%s_archive::"
3916 "The location where subtrees should be archived.
3918 The value of this variable is a string, consisting of two parts,
3919 separated by a double-colon. The first part is a filename and
3920 the second part is a headline.
3922 When the filename is omitted, archiving happens in the same file.
3923 %s in the filename will be replaced by the current file
3924 name (without the directory part). Archiving to a different file
3925 is useful to keep archived entries from contributing to the
3926 Org Agenda.
3928 The archived entries will be filed as subtrees of the specified
3929 headline. When the headline is omitted, the subtrees are simply
3930 filed away at the end of the file, as top-level entries. Also in
3931 the heading you can use %s to represent the file name, this can be
3932 useful when using the same archive for a number of different files.
3934 Here are a few examples:
3935 \"%s_archive::\"
3936 If the current file is Projects.org, archive in file
3937 Projects.org_archive, as top-level trees. This is the default.
3939 \"::* Archived Tasks\"
3940 Archive in the current file, under the top-level headline
3941 \"* Archived Tasks\".
3943 \"~/org/archive.org::\"
3944 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3946 \"~/org/archive.org::* From %s\"
3947 Archive in file ~/org/archive.org (absolute path), under headlines
3948 \"From FILENAME\" where file name is the current file name.
3950 \"~/org/datetree.org::datetree/* Finished Tasks\"
3951 The \"datetree/\" string is special, signifying to archive
3952 items to the datetree. Items are placed in either the CLOSED
3953 date of the item, or the current date if there is no CLOSED date.
3954 The heading will be a subentry to the current date. There doesn't
3955 need to be a heading, but there always needs to be a slash after
3956 datetree. For example, to store archived items directly in the
3957 datetree, use \"~/org/datetree.org::datetree/\".
3959 \"basement::** Finished Tasks\"
3960 Archive in file ./basement (relative path), as level 3 trees
3961 below the level 2 heading \"** Finished Tasks\".
3963 You may set this option on a per-file basis by adding to the buffer a
3964 line like
3966 #+ARCHIVE: basement::** Finished Tasks
3968 You may also define it locally for a subtree by setting an ARCHIVE property
3969 in the entry. If such a property is found in an entry, or anywhere up
3970 the hierarchy, it will be used."
3971 :group 'org-archive
3972 :type 'string)
3974 (defcustom org-agenda-skip-archived-trees t
3975 "Non-nil means the agenda will skip any items located in archived trees.
3976 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3977 variable is no longer recommended, you should leave it at the value t.
3978 Instead, use the key `v' to cycle the archives-mode in the agenda."
3979 :group 'org-archive
3980 :group 'org-agenda-skip
3981 :type 'boolean)
3983 (defcustom org-columns-skip-archived-trees t
3984 "Non-nil means ignore archived trees when creating column view."
3985 :group 'org-archive
3986 :group 'org-properties
3987 :type 'boolean)
3989 (defcustom org-cycle-open-archived-trees nil
3990 "Non-nil means `org-cycle' will open archived trees.
3991 An archived tree is a tree marked with the tag ARCHIVE.
3992 When nil, archived trees will stay folded. You can still open them with
3993 normal outline commands like `show-all', but not with the cycling commands."
3994 :group 'org-archive
3995 :group 'org-cycle
3996 :type 'boolean)
3998 (defcustom org-sparse-tree-open-archived-trees nil
3999 "Non-nil means sparse tree construction shows matches in archived trees.
4000 When nil, matches in these trees are highlighted, but the trees are kept in
4001 collapsed state."
4002 :group 'org-archive
4003 :group 'org-sparse-trees
4004 :type 'boolean)
4006 (defcustom org-sparse-tree-default-date-type nil
4007 "The default date type when building a sparse tree.
4008 When this is nil, a date is a scheduled or a deadline timestamp.
4009 Otherwise, these types are allowed:
4011 all: all timestamps
4012 active: only active timestamps (<...>)
4013 inactive: only inactive timestamps ([...])
4014 scheduled: only scheduled timestamps
4015 deadline: only deadline timestamps"
4016 :type '(choice (const :tag "Scheduled or deadline" nil)
4017 (const :tag "All timestamps" all)
4018 (const :tag "Only active timestamps" active)
4019 (const :tag "Only inactive timestamps" inactive)
4020 (const :tag "Only scheduled timestamps" scheduled)
4021 (const :tag "Only deadline timestamps" deadline)
4022 (const :tag "Only closed timestamps" closed))
4023 :version "26.1"
4024 :package-version '(Org . "8.3")
4025 :group 'org-sparse-trees)
4027 (defun org-cycle-hide-archived-subtrees (state)
4028 "Re-hide all archived subtrees after a visibility state change.
4029 STATE should be one of the symbols listed in the docstring of
4030 `org-cycle-hook'."
4031 (when (and (not org-cycle-open-archived-trees)
4032 (not (memq state '(overview folded))))
4033 (save-excursion
4034 (let* ((globalp (memq state '(contents all)))
4035 (beg (if globalp (point-min) (point)))
4036 (end (if globalp (point-max) (org-end-of-subtree t))))
4037 (org-hide-archived-subtrees beg end)
4038 (goto-char beg)
4039 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4040 (message "%s" (substitute-command-keys
4041 "Subtree is archived and stays closed. Use \
4042 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4044 (defun org-force-cycle-archived ()
4045 "Cycle subtree even if it is archived."
4046 (interactive)
4047 (setq this-command 'org-cycle)
4048 (let ((org-cycle-open-archived-trees t))
4049 (call-interactively 'org-cycle)))
4051 (defun org-hide-archived-subtrees (beg end)
4052 "Re-hide all archived subtrees after a visibility state change."
4053 (org-with-wide-buffer
4054 (let ((case-fold-search nil)
4055 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4056 (goto-char beg)
4057 ;; Include headline point is currently on.
4058 (beginning-of-line)
4059 (while (and (< (point) end) (re-search-forward re end t))
4060 (when (member org-archive-tag (org-get-tags nil t))
4061 (org-flag-subtree t)
4062 (org-end-of-subtree t))))))
4064 (defun org-flag-subtree (flag)
4065 (save-excursion
4066 (org-back-to-heading t)
4067 (org-flag-region (line-end-position)
4068 (progn (org-end-of-subtree t) (point))
4069 flag
4070 'outline)))
4072 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4074 ;; Declare Column View Code
4076 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4077 (declare-function org-columns-compute "org-colview" (property))
4079 ;; Declare ID code
4081 (declare-function org-id-store-link "org-id")
4082 (declare-function org-id-locations-load "org-id")
4083 (declare-function org-id-locations-save "org-id")
4084 (defvar org-id-track-globally)
4086 ;;; Variables for pre-computed regular expressions, all buffer local
4088 (defvar-local org-todo-regexp nil
4089 "Matches any of the TODO state keywords.
4090 Since TODO keywords are case-sensitive, `case-fold-search' is
4091 expected to be bound to nil when matching against this regexp.")
4093 (defvar-local org-not-done-regexp nil
4094 "Matches any of the TODO state keywords except the last one.
4095 Since TODO keywords are case-sensitive, `case-fold-search' is
4096 expected to be bound to nil when matching against this regexp.")
4098 (defvar-local org-not-done-heading-regexp nil
4099 "Matches a TODO headline that is not done.
4100 Since TODO keywords are case-sensitive, `case-fold-search' is
4101 expected to be bound to nil when matching against this regexp.")
4103 (defvar-local org-todo-line-regexp nil
4104 "Matches a headline and puts TODO state into group 2 if present.
4105 Since TODO keywords are case-sensitive, `case-fold-search' is
4106 expected to be bound to nil when matching against this regexp.")
4108 (defvar-local org-complex-heading-regexp nil
4109 "Matches a headline and puts everything into groups:
4111 group 1: Stars
4112 group 2: The TODO keyword, maybe
4113 group 3: Priority cookie
4114 group 4: True headline
4115 group 5: Tags
4117 Since TODO keywords are case-sensitive, `case-fold-search' is
4118 expected to be bound to nil when matching against this regexp.")
4120 (defvar-local org-complex-heading-regexp-format nil
4121 "Printf format to make regexp to match an exact headline.
4122 This regexp will match the headline of any node which has the
4123 exact headline text that is put into the format, but may have any
4124 TODO state, priority and tags.")
4126 (defvar-local org-todo-line-tags-regexp nil
4127 "Matches a headline and puts TODO state into group 2 if present.
4128 Also put tags into group 4 if tags are present.")
4130 (defconst org-plain-time-of-day-regexp
4131 (concat
4132 "\\(\\<[012]?[0-9]"
4133 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4134 "\\(--?"
4135 "\\(\\<[012]?[0-9]"
4136 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4137 "\\)?")
4138 "Regular expression to match a plain time or time range.
4139 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4140 groups carry important information:
4141 0 the full match
4142 1 the first time, range or not
4143 8 the second time, if it is a range.")
4145 (defconst org-plain-time-extension-regexp
4146 (concat
4147 "\\(\\<[012]?[0-9]"
4148 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4149 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4150 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4151 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4152 groups carry important information:
4153 0 the full match
4154 7 hours of duration
4155 9 minutes of duration")
4157 (defconst org-stamp-time-of-day-regexp
4158 (concat
4159 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4160 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4161 "\\(--?"
4162 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4163 "Regular expression to match a timestamp time or time range.
4164 After a match, the following groups carry important information:
4165 0 the full match
4166 1 date plus weekday, for back referencing to make sure both times are on the same day
4167 2 the first time, range or not
4168 4 the second time, if it is a range.")
4170 (defconst org-startup-options
4171 '(("fold" org-startup-folded t)
4172 ("overview" org-startup-folded t)
4173 ("nofold" org-startup-folded nil)
4174 ("showall" org-startup-folded nil)
4175 ("showeverything" org-startup-folded showeverything)
4176 ("content" org-startup-folded content)
4177 ("indent" org-startup-indented t)
4178 ("noindent" org-startup-indented nil)
4179 ("hidestars" org-hide-leading-stars t)
4180 ("showstars" org-hide-leading-stars nil)
4181 ("odd" org-odd-levels-only t)
4182 ("oddeven" org-odd-levels-only nil)
4183 ("align" org-startup-align-all-tables t)
4184 ("noalign" org-startup-align-all-tables nil)
4185 ("shrink" org-startup-shrink-all-tables t)
4186 ("inlineimages" org-startup-with-inline-images t)
4187 ("noinlineimages" org-startup-with-inline-images nil)
4188 ("latexpreview" org-startup-with-latex-preview t)
4189 ("nolatexpreview" org-startup-with-latex-preview nil)
4190 ("customtime" org-display-custom-times t)
4191 ("logdone" org-log-done time)
4192 ("lognotedone" org-log-done note)
4193 ("nologdone" org-log-done nil)
4194 ("lognoteclock-out" org-log-note-clock-out t)
4195 ("nolognoteclock-out" org-log-note-clock-out nil)
4196 ("logrepeat" org-log-repeat state)
4197 ("lognoterepeat" org-log-repeat note)
4198 ("logdrawer" org-log-into-drawer t)
4199 ("nologdrawer" org-log-into-drawer nil)
4200 ("logstatesreversed" org-log-states-order-reversed t)
4201 ("nologstatesreversed" org-log-states-order-reversed nil)
4202 ("nologrepeat" org-log-repeat nil)
4203 ("logreschedule" org-log-reschedule time)
4204 ("lognotereschedule" org-log-reschedule note)
4205 ("nologreschedule" org-log-reschedule nil)
4206 ("logredeadline" org-log-redeadline time)
4207 ("lognoteredeadline" org-log-redeadline note)
4208 ("nologredeadline" org-log-redeadline nil)
4209 ("logrefile" org-log-refile time)
4210 ("lognoterefile" org-log-refile note)
4211 ("nologrefile" org-log-refile nil)
4212 ("fninline" org-footnote-define-inline t)
4213 ("nofninline" org-footnote-define-inline nil)
4214 ("fnlocal" org-footnote-section nil)
4215 ("fnauto" org-footnote-auto-label t)
4216 ("fnprompt" org-footnote-auto-label nil)
4217 ("fnconfirm" org-footnote-auto-label confirm)
4218 ("fnplain" org-footnote-auto-label plain)
4219 ("fnadjust" org-footnote-auto-adjust t)
4220 ("nofnadjust" org-footnote-auto-adjust nil)
4221 ("constcgs" constants-unit-system cgs)
4222 ("constSI" constants-unit-system SI)
4223 ("noptag" org-tag-persistent-alist nil)
4224 ("hideblocks" org-hide-block-startup t)
4225 ("nohideblocks" org-hide-block-startup nil)
4226 ("beamer" org-startup-with-beamer-mode t)
4227 ("entitiespretty" org-pretty-entities t)
4228 ("entitiesplain" org-pretty-entities nil))
4229 "Variable associated with STARTUP options for Org.
4230 Each element is a list of three items: the startup options (as written
4231 in the #+STARTUP line), the corresponding variable, and the value to set
4232 this variable to if the option is found. An optional forth element PUSH
4233 means to push this value onto the list in the variable.")
4235 (defcustom org-group-tags t
4236 "When non-nil (the default), use group tags.
4237 This can be turned on/off through `org-toggle-tags-groups'."
4238 :group 'org-tags
4239 :group 'org-startup
4240 :type 'boolean)
4242 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4244 (defun org-toggle-tags-groups ()
4245 "Toggle support for group tags.
4246 Support for group tags is controlled by the option
4247 `org-group-tags', which is non-nil by default."
4248 (interactive)
4249 (setq org-group-tags (not org-group-tags))
4250 (cond ((and (derived-mode-p 'org-agenda-mode)
4251 org-group-tags)
4252 (org-agenda-redo))
4253 ((derived-mode-p 'org-mode)
4254 (let ((org-inhibit-startup t)) (org-mode))))
4255 (message "Groups tags support has been turned %s"
4256 (if org-group-tags "on" "off")))
4258 (defun org--tag-add-to-alist (alist1 alist2)
4259 "Merge tags from ALIST1 into ALIST2.
4261 Duplicates tags outside a group are removed. Keywords and order
4262 are preserved.
4264 The function assumes ALIST1 and ALIST2 are proper tag alists.
4265 See `org-tag-alist' for their structure."
4266 (cond
4267 ((null alist2) alist1)
4268 ((null alist1) alist2)
4270 (let ((to-add nil)
4271 (group-flag nil))
4272 (dolist (tag-pair alist1)
4273 (pcase tag-pair
4274 (`(,(or :startgrouptag :startgroup))
4275 (setq group-flag t)
4276 (push tag-pair to-add))
4277 (`(,(or :endgrouptag :endgroup))
4278 (setq group-flag nil)
4279 (push tag-pair to-add))
4280 (`(,(or :grouptags :newline))
4281 (push tag-pair to-add))
4282 (`(,tag . ,_)
4283 ;; Remove duplicates from ALIST1, unless they are in
4284 ;; a group. Indeed, it makes sense to have a tag appear in
4285 ;; multiple groups.
4286 (when (or group-flag (not (assoc tag alist2)))
4287 (push tag-pair to-add)))
4288 (_ (error "Invalid association in tag alist: %S" tag-pair))))
4289 ;; Preserve order of ALIST1.
4290 (append (nreverse to-add) alist2)))))
4292 (defun org-set-regexps-and-options (&optional tags-only)
4293 "Precompute regular expressions used in the current buffer.
4294 When optional argument TAGS-ONLY is non-nil, only compute tags
4295 related expressions."
4296 (when (derived-mode-p 'org-mode)
4297 (let ((alist (org--setup-collect-keywords
4298 (org-make-options-regexp
4299 (append '("FILETAGS" "TAGS" "SETUPFILE")
4300 (and (not tags-only)
4301 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4302 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4303 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4304 ;; Startup options. Get this early since it does change
4305 ;; behavior for other options (e.g., tags).
4306 (let ((startup (cdr (assq 'startup alist))))
4307 (dolist (option startup)
4308 (let ((entry (assoc-string option org-startup-options t)))
4309 (when entry
4310 (let ((var (nth 1 entry))
4311 (val (nth 2 entry)))
4312 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4313 (unless (listp (symbol-value var))
4314 (set (make-local-variable var) nil))
4315 (add-to-list var val)))))))
4316 (setq-local org-file-tags
4317 (mapcar #'org-add-prop-inherited
4318 (cdr (assq 'filetags alist))))
4319 (setq org-current-tag-alist
4320 (org--tag-add-to-alist
4321 org-tag-persistent-alist
4322 (let ((tags (cdr (assq 'tags alist))))
4323 (if tags (org-tag-string-to-alist tags)
4324 org-tag-alist))))
4325 (setq org-tag-groups-alist
4326 (org-tag-alist-to-groups org-current-tag-alist))
4327 (unless tags-only
4328 ;; File properties.
4329 (setq-local org-file-properties (cdr (assq 'property alist)))
4330 ;; Archive location.
4331 (let ((archive (cdr (assq 'archive alist))))
4332 (when archive (setq-local org-archive-location archive)))
4333 ;; Category.
4334 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4335 (when cat
4336 (setq-local org-category (intern cat))
4337 (setq-local org-file-properties
4338 (org--update-property-plist
4339 "CATEGORY" cat org-file-properties))))
4340 ;; Columns.
4341 (let ((column (cdr (assq 'columns alist))))
4342 (when column (setq-local org-columns-default-format column)))
4343 ;; Constants.
4344 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4345 ;; Link abbreviations.
4346 (let ((links (cdr (assq 'link alist))))
4347 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4348 ;; Priorities.
4349 (let ((priorities (cdr (assq 'priorities alist))))
4350 (when priorities
4351 (setq-local org-highest-priority (nth 0 priorities))
4352 (setq-local org-lowest-priority (nth 1 priorities))
4353 (setq-local org-default-priority (nth 2 priorities))))
4354 ;; Scripts.
4355 (let ((scripts (assq 'scripts alist)))
4356 (when scripts
4357 (setq-local org-use-sub-superscripts (cdr scripts))))
4358 ;; TODO keywords.
4359 (setq-local org-todo-kwd-alist nil)
4360 (setq-local org-todo-key-alist nil)
4361 (setq-local org-todo-key-trigger nil)
4362 (setq-local org-todo-keywords-1 nil)
4363 (setq-local org-done-keywords nil)
4364 (setq-local org-todo-heads nil)
4365 (setq-local org-todo-sets nil)
4366 (setq-local org-todo-log-states nil)
4367 (let ((todo-sequences
4368 (or (nreverse (cdr (assq 'todo alist)))
4369 (let ((d (default-value 'org-todo-keywords)))
4370 (if (not (stringp (car d))) d
4371 ;; XXX: Backward compatibility code.
4372 (list (cons org-todo-interpretation d)))))))
4373 (dolist (sequence todo-sequences)
4374 (let* ((sequence (or (run-hook-with-args-until-success
4375 'org-todo-setup-filter-hook sequence)
4376 sequence))
4377 (sequence-type (car sequence))
4378 (keywords (cdr sequence))
4379 (sep (member "|" keywords))
4380 names alist)
4381 (dolist (k (remove "|" keywords))
4382 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4384 (error "Invalid TODO keyword %s" k))
4385 (let ((name (match-string 1 k))
4386 (key (match-string 2 k))
4387 (log (org-extract-log-state-settings k)))
4388 (push name names)
4389 (push (cons name (and key (string-to-char key))) alist)
4390 (when log (push log org-todo-log-states))))
4391 (let* ((names (nreverse names))
4392 (done (if sep (org-remove-keyword-keys (cdr sep))
4393 (last names)))
4394 (head (car names))
4395 (tail (list sequence-type head (car done) (org-last done))))
4396 (add-to-list 'org-todo-heads head 'append)
4397 (push names org-todo-sets)
4398 (setq org-done-keywords (append org-done-keywords done nil))
4399 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4400 (setq org-todo-key-alist
4401 (append org-todo-key-alist
4402 (and alist
4403 (append '((:startgroup))
4404 (nreverse alist)
4405 '((:endgroup))))))
4406 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4407 (setq org-todo-sets (nreverse org-todo-sets)
4408 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4409 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4410 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4411 ;; Compute the regular expressions and other local variables.
4412 ;; Using `org-outline-regexp-bol' would complicate them much,
4413 ;; because of the fixed white space at the end of that string.
4414 (unless org-done-keywords
4415 (setq org-done-keywords
4416 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4417 (setq org-not-done-keywords
4418 (org-delete-all org-done-keywords
4419 (copy-sequence org-todo-keywords-1))
4420 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4421 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4422 org-not-done-heading-regexp
4423 (format org-heading-keyword-regexp-format org-not-done-regexp)
4424 org-todo-line-regexp
4425 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4426 org-complex-heading-regexp
4427 (concat "^\\(\\*+\\)"
4428 "\\(?: +" org-todo-regexp "\\)?"
4429 "\\(?: +\\(\\[#.\\]\\)\\)?"
4430 "\\(?: +\\(.*?\\)\\)??"
4431 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4432 "[ \t]*$")
4433 org-complex-heading-regexp-format
4434 (concat "^\\(\\*+\\)"
4435 "\\(?: +" org-todo-regexp "\\)?"
4436 "\\(?: +\\(\\[#.\\]\\)\\)?"
4437 "\\(?: +"
4438 ;; Stats cookies can be stuck to body.
4439 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4440 "\\(%s\\)"
4441 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4442 "\\)"
4443 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
4444 "[ \t]*$")
4445 org-todo-line-tags-regexp
4446 (concat "^\\(\\*+\\)"
4447 "\\(?: +" org-todo-regexp "\\)?"
4448 "\\(?: +\\(.*?\\)\\)??"
4449 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
4450 "[ \t]*$"))
4451 (org-compute-latex-and-related-regexp)))))
4453 (defun org--setup-collect-keywords (regexp &optional files alist)
4454 "Return setup keywords values as an alist.
4456 REGEXP matches a subset of setup keywords. FILES is a list of
4457 file names already visited. It is used to avoid circular setup
4458 files. ALIST, when non-nil, is the alist computed so far.
4460 Return value contains the following keys: `archive', `category',
4461 `columns', `constants', `filetags', `link', `priorities',
4462 `property', `scripts', `startup', `tags' and `todo'."
4463 (org-with-wide-buffer
4464 (goto-char (point-min))
4465 (let ((case-fold-search t))
4466 (while (re-search-forward regexp nil t)
4467 (let ((element (org-element-at-point)))
4468 (when (eq (org-element-type element) 'keyword)
4469 (let ((key (org-element-property :key element))
4470 (value (org-element-property :value element)))
4471 (cond
4472 ((equal key "ARCHIVE")
4473 (when (org-string-nw-p value)
4474 (push (cons 'archive value) alist)))
4475 ((equal key "CATEGORY") (push (cons 'category value) alist))
4476 ((equal key "COLUMNS") (push (cons 'columns value) alist))
4477 ((equal key "CONSTANTS")
4478 (let* ((constants (assq 'constants alist))
4479 (store (cdr constants)))
4480 (dolist (pair (split-string value))
4481 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
4482 pair)
4483 (let* ((name (match-string 1 pair))
4484 (value (match-string 2 pair))
4485 (old (assoc name store)))
4486 (if old (setcdr old value)
4487 (push (cons name value) store)))))
4488 (if constants (setcdr constants store)
4489 (push (cons 'constants store) alist))))
4490 ((equal key "FILETAGS")
4491 (when (org-string-nw-p value)
4492 (let ((old (assq 'filetags alist))
4493 (new (apply #'nconc
4494 (mapcar (lambda (x) (org-split-string x ":"))
4495 (split-string value)))))
4496 (if old (setcdr old (append new (cdr old)))
4497 (push (cons 'filetags new) alist)))))
4498 ((equal key "LINK")
4499 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4500 (let ((links (assq 'link alist))
4501 (pair (cons (match-string-no-properties 1 value)
4502 (match-string-no-properties 2 value))))
4503 (if links (push pair (cdr links))
4504 (push (list 'link pair) alist)))))
4505 ((equal key "OPTIONS")
4506 (when (and (org-string-nw-p value)
4507 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
4508 (push (cons 'scripts (read (match-string 1 value))) alist)))
4509 ((equal key "PRIORITIES")
4510 (push (cons 'priorities
4511 (let ((prio (split-string value)))
4512 (if (< (length prio) 3) '(?A ?C ?B)
4513 (mapcar #'string-to-char prio))))
4514 alist))
4515 ((equal key "PROPERTY")
4516 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
4517 (let* ((property (assq 'property alist))
4518 (value (org--update-property-plist
4519 (match-string-no-properties 1 value)
4520 (match-string-no-properties 2 value)
4521 (cdr property))))
4522 (if property (setcdr property value)
4523 (push (cons 'property value) alist)))))
4524 ((equal key "STARTUP")
4525 (let ((startup (assq 'startup alist)))
4526 (if startup
4527 (setcdr startup
4528 (append (cdr startup) (split-string value)))
4529 (push (cons 'startup (split-string value)) alist))))
4530 ((equal key "TAGS")
4531 (let ((tag-cell (assq 'tags alist)))
4532 (if tag-cell
4533 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
4534 (push (cons 'tags value) alist))))
4535 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
4536 (let ((todo (assq 'todo alist))
4537 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
4538 (split-string value))))
4539 (if todo (push value (cdr todo))
4540 (push (list 'todo value) alist))))
4541 ((equal key "SETUPFILE")
4542 (unless buffer-read-only ; Do not check in Gnus messages.
4543 (let ((f (and (org-string-nw-p value)
4544 (expand-file-name (org-strip-quotes value)))))
4545 (when (and f (file-readable-p f) (not (member f files)))
4546 (with-temp-buffer
4547 (setq default-directory (file-name-directory f))
4548 (insert-file-contents f)
4549 (setq alist
4550 ;; Fake Org mode to benefit from cache
4551 ;; without recurring needlessly.
4552 (let ((major-mode 'org-mode))
4553 (org--setup-collect-keywords
4554 regexp (cons f files) alist)))))))))))))))
4555 alist)
4557 (defun org-tag-string-to-alist (s)
4558 "Return tag alist associated to string S.
4559 S is a value for TAGS keyword or produced with
4560 `org-tag-alist-to-string'. Return value is an alist suitable for
4561 `org-tag-alist' or `org-tag-persistent-alist'."
4562 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
4563 (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
4564 "\\(?:(\\(.\\))\\)?\\'"))
4565 alist group-flag)
4566 (dolist (tokens lines (cdr (nreverse alist)))
4567 (push '(:newline) alist)
4568 (while tokens
4569 (let ((token (pop tokens)))
4570 (pcase token
4571 ("{"
4572 (push '(:startgroup) alist)
4573 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
4574 ("}"
4575 (push '(:endgroup) alist)
4576 (setq group-flag nil))
4577 ("["
4578 (push '(:startgrouptag) alist)
4579 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
4580 ("]"
4581 (push '(:endgrouptag) alist)
4582 (setq group-flag nil))
4583 (":"
4584 (push '(:grouptags) alist))
4585 ((guard (string-match tag-re token))
4586 (let ((tag (match-string 1 token))
4587 (key (and (match-beginning 2)
4588 (string-to-char (match-string 2 token)))))
4589 ;; Push all tags in groups, no matter if they already
4590 ;; appear somewhere else in the list.
4591 (when (or group-flag (not (assoc tag alist)))
4592 (push (cons tag key) alist))))))))))
4594 (defun org-tag-alist-to-string (alist &optional skip-key)
4595 "Return tag string associated to ALIST.
4597 ALIST is an alist, as defined in `org-tag-alist' or
4598 `org-tag-persistent-alist', or produced with
4599 `org-tag-string-to-alist'.
4601 Return value is a string suitable as a value for \"TAGS\"
4602 keyword.
4604 When optional argument SKIP-KEY is non-nil, skip selection keys
4605 next to tags."
4606 (mapconcat (lambda (token)
4607 (pcase token
4608 (`(:startgroup) "{")
4609 (`(:endgroup) "}")
4610 (`(:startgrouptag) "[")
4611 (`(:endgrouptag) "]")
4612 (`(:grouptags) ":")
4613 (`(:newline) "\\n")
4614 ((and
4615 (guard (not skip-key))
4616 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
4617 (format "%s(%c)" tag key))
4618 (`(,(and tag (pred stringp)) . ,_) tag)
4619 (_ (user-error "Invalid tag token: %S" token))))
4620 alist
4621 " "))
4623 (defun org-tag-alist-to-groups (alist)
4624 "Return group alist from tag ALIST.
4625 ALIST is an alist, as defined in `org-tag-alist' or
4626 `org-tag-persistent-alist', or produced with
4627 `org-tag-string-to-alist'. Return value is an alist following
4628 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
4629 a string, summarizing TAGS, as a list of strings."
4630 (let (groups group-status current-group)
4631 (dolist (token alist (nreverse groups))
4632 (pcase token
4633 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
4634 (`(,(or :endgroup :endgrouptag))
4635 (when (eq group-status 'append)
4636 (push (nreverse current-group) groups))
4637 (setq group-status nil current-group nil))
4638 (`(:grouptags) (setq group-status 'append))
4639 ((and `(,tag . ,_) (guard group-status))
4640 (if (eq group-status 'append) (push tag current-group)
4641 (setq current-group (list tag))))
4642 (_ nil)))))
4644 (defvar org--file-cache (make-hash-table :test #'equal)
4645 "Hash table to store contents of files referenced via a URL.
4646 This is the cache of file URLs read using `org-file-contents'.")
4648 (defun org-reset-file-cache ()
4649 "Reset the cache of files downloaded by `org-file-contents'."
4650 (clrhash org--file-cache))
4652 (defun org-file-url-p (file)
4653 "Non-nil if FILE is a URL."
4654 (require 'ffap)
4655 (string-match-p ffap-url-regexp file))
4657 (defun org-file-contents (file &optional noerror nocache)
4658 "Return the contents of FILE, as a string.
4660 FILE can be a file name or URL.
4662 If FILE is a URL, download the contents. If the URL contents are
4663 already cached in the `org--file-cache' hash table, the download step
4664 is skipped.
4666 If NOERROR is non-nil, ignore the error when unable to read the FILE
4667 from file or URL.
4669 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
4670 is available. This option applies only if FILE is a URL."
4671 (let* ((is-url (org-file-url-p file))
4672 (cache (and is-url
4673 (not nocache)
4674 (gethash file org--file-cache))))
4675 (cond
4676 (cache)
4677 (is-url
4678 (with-current-buffer (url-retrieve-synchronously file)
4679 (goto-char (point-min))
4680 ;; Move point to after the url-retrieve header.
4681 (search-forward "\n\n" nil :move)
4682 ;; Search for the success code only in the url-retrieve header.
4683 (if (save-excursion
4684 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
4685 ;; Update the cache `org--file-cache' and return contents.
4686 (puthash file
4687 (buffer-substring-no-properties (point) (point-max))
4688 org--file-cache)
4689 (funcall (if noerror #'message #'user-error)
4690 "Unable to fetch file from %S"
4691 file))))
4693 (with-temp-buffer
4694 (condition-case nil
4695 (progn
4696 (insert-file-contents file)
4697 (buffer-string))
4698 (file-error
4699 (funcall (if noerror #'message #'user-error)
4700 "Unable to read file %S"
4701 file))))))))
4703 (defun org-extract-log-state-settings (x)
4704 "Extract the log state setting from a TODO keyword string.
4705 This will extract info from a string like \"WAIT(w@/!)\"."
4706 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4707 (let ((kw (match-string 1 x))
4708 (log1 (and (match-end 3) (match-string 3 x)))
4709 (log2 (and (match-end 4) (match-string 4 x))))
4710 (and (or log1 log2)
4711 (list kw
4712 (and log1 (if (equal log1 "!") 'time 'note))
4713 (and log2 (if (equal log2 "!") 'time 'note)))))))
4715 (defun org-remove-keyword-keys (list)
4716 "Remove a pair of parenthesis at the end of each string in LIST."
4717 (mapcar (lambda (x)
4718 (if (string-match "(.*)$" x)
4719 (substring x 0 (match-beginning 0))
4721 list))
4723 (defun org-assign-fast-keys (alist)
4724 "Assign fast keys to a keyword-key alist.
4725 Respect keys that are already there."
4726 (let (new e (alt ?0))
4727 (while (setq e (pop alist))
4728 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
4729 (cdr e)) ;; Key already assigned.
4730 (push e new)
4731 (let ((clist (string-to-list (downcase (car e))))
4732 (used (append new alist)))
4733 (when (= (car clist) ?@)
4734 (pop clist))
4735 (while (and clist (rassoc (car clist) used))
4736 (pop clist))
4737 (unless clist
4738 (while (rassoc alt used)
4739 (cl-incf alt)))
4740 (push (cons (car e) (or (car clist) alt)) new))))
4741 (nreverse new)))
4743 ;;; Some variables used in various places
4745 (defvar org-window-configuration nil
4746 "Used in various places to store a window configuration.")
4747 (defvar org-selected-window nil
4748 "Used in various places to store a window configuration.")
4749 (defvar org-finish-function nil
4750 "Function to be called when `C-c C-c' is used.
4751 This is for getting out of special buffers like capture.")
4752 (defvar org-last-state)
4754 ;; Defined somewhere in this file, but used before definition.
4755 (defvar org-entities) ;; defined in org-entities.el
4756 (defvar org-struct-menu)
4757 (defvar org-org-menu)
4758 (defvar org-tbl-menu)
4760 ;;;; Define the Org mode
4762 (defun org-before-change-function (_beg _end)
4763 "Every change indicates that a table might need an update."
4764 (setq org-table-may-need-update t))
4765 (defvar org-mode-map)
4766 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4767 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4768 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4769 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4771 (defvar bidi-paragraph-direction)
4772 (defvar buffer-face-mode-face)
4774 (require 'outline)
4776 ;; Other stuff we need.
4777 (require 'time-date)
4778 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4779 (require 'easymenu)
4780 (autoload 'easy-menu-add "easymenu")
4781 (require 'overlay)
4783 ;; (require 'org-macs) moved higher up in the file before it is first used
4784 (require 'org-entities)
4785 ;; (require 'org-compat) moved higher up in the file before it is first used
4786 (require 'org-faces)
4787 (require 'org-list)
4788 (require 'org-pcomplete)
4789 (require 'org-src)
4790 (require 'org-footnote)
4791 (require 'org-macro)
4793 ;; babel
4794 (require 'ob)
4796 ;;;###autoload
4797 (define-derived-mode org-mode outline-mode "Org"
4798 "Outline-based notes management and organizer, alias
4799 \"Carsten's outline-mode for keeping track of everything.\"
4801 Org mode develops organizational tasks around a NOTES file which
4802 contains information about projects as plain text. Org mode is
4803 implemented on top of Outline mode, which is ideal to keep the content
4804 of large files well structured. It supports ToDo items, deadlines and
4805 time stamps, which magically appear in the diary listing of the Emacs
4806 calendar. Tables are easily created with a built-in table editor.
4807 Plain text URL-like links connect to websites, emails (VM), Usenet
4808 messages (Gnus), BBDB entries, and any files related to the project.
4809 For printing and sharing of notes, an Org file (or a part of it)
4810 can be exported as a structured ASCII or HTML file.
4812 The following commands are available:
4814 \\{org-mode-map}"
4815 (org-load-modules-maybe)
4816 (org-install-agenda-files-menu)
4817 (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
4818 (add-to-invisibility-spec '(org-hide-block . t))
4819 (add-to-invisibility-spec '(org-hide-drawer . t))
4820 (setq-local outline-regexp org-outline-regexp)
4821 (setq-local outline-level 'org-outline-level)
4822 (setq bidi-paragraph-direction 'left-to-right)
4823 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
4824 (unless org-display-table
4825 (setq org-display-table (make-display-table)))
4826 (set-display-table-slot
4827 org-display-table 4
4828 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
4829 org-ellipsis)))
4830 (setq buffer-display-table org-display-table))
4831 (org-set-regexps-and-options)
4832 (org-set-font-lock-defaults)
4833 (when (and org-tag-faces (not org-tags-special-faces-re))
4834 ;; tag faces set outside customize.... force initialization.
4835 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4836 ;; Calc embedded
4837 (setq-local calc-embedded-open-mode "# ")
4838 ;; Modify a few syntax entries
4839 (modify-syntax-entry ?\" "\"")
4840 (modify-syntax-entry ?\\ "_")
4841 (modify-syntax-entry ?~ "_")
4842 (modify-syntax-entry ?< "(>")
4843 (modify-syntax-entry ?> ")<")
4844 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
4845 ;; Activate before-change-function
4846 (setq-local org-table-may-need-update t)
4847 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
4848 ;; Check for running clock before killing a buffer
4849 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4850 ;; Initialize macros templates.
4851 (org-macro-initialize-templates)
4852 ;; Initialize radio targets.
4853 (org-update-radio-target-regexp)
4854 ;; Indentation.
4855 (setq-local indent-line-function 'org-indent-line)
4856 (setq-local indent-region-function 'org-indent-region)
4857 ;; Filling and auto-filling.
4858 (org-setup-filling)
4859 ;; Comments.
4860 (org-setup-comments-handling)
4861 ;; Initialize cache.
4862 (org-element-cache-reset)
4863 ;; Beginning/end of defun
4864 (setq-local beginning-of-defun-function 'org-backward-element)
4865 (setq-local end-of-defun-function
4866 (lambda ()
4867 (if (not (org-at-heading-p))
4868 (org-forward-element)
4869 (org-forward-element)
4870 (forward-char -1))))
4871 ;; Next error for sparse trees
4872 (setq-local next-error-function 'org-occur-next-match)
4873 ;; Make commit log messages from Org documents easier.
4874 (setq-local add-log-current-defun-function #'org-add-log-current-headline)
4875 ;; Make sure dependence stuff works reliably, even for users who set it
4876 ;; too late :-(
4877 (if org-enforce-todo-dependencies
4878 (add-hook 'org-blocker-hook
4879 'org-block-todo-from-children-or-siblings-or-parent)
4880 (remove-hook 'org-blocker-hook
4881 'org-block-todo-from-children-or-siblings-or-parent))
4882 (if org-enforce-todo-checkbox-dependencies
4883 (add-hook 'org-blocker-hook
4884 'org-block-todo-from-checkboxes)
4885 (remove-hook 'org-blocker-hook
4886 'org-block-todo-from-checkboxes))
4888 ;; Align options lines
4889 (setq-local
4890 align-mode-rules-list
4891 '((org-in-buffer-settings
4892 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4893 (modes . '(org-mode)))))
4895 ;; Make isearch reveal context
4896 (setq-local outline-isearch-open-invisible-function
4897 (lambda (&rest _) (org-show-context 'isearch)))
4899 ;; Setup the pcomplete hooks
4900 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
4901 (setq-local pcomplete-command-name-function 'org-command-at-point)
4902 (setq-local pcomplete-default-completion-function 'ignore)
4903 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
4904 (setq-local pcomplete-termination-string "")
4905 (setq-local buffer-face-mode-face 'org-default)
4907 ;; If empty file that did not turn on Org mode automatically, make
4908 ;; it to.
4909 (when (and org-insert-mode-line-in-empty-file
4910 (called-interactively-p 'any)
4911 (= (point-min) (point-max)))
4912 (insert "# -*- mode: org -*-\n\n"))
4913 (unless org-inhibit-startup
4914 (org-unmodified
4915 (when org-startup-with-beamer-mode (org-beamer-mode))
4916 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
4917 (org-table-map-tables
4918 (cond ((and org-startup-align-all-tables
4919 org-startup-shrink-all-tables)
4920 (lambda () (org-table-align) (org-table-shrink)))
4921 (org-startup-align-all-tables #'org-table-align)
4922 (t #'org-table-shrink))
4924 (when org-startup-with-inline-images (org-display-inline-images))
4925 (when org-startup-with-latex-preview (org-latex-preview '(16)))
4926 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
4927 (when org-startup-truncated (setq truncate-lines t))
4928 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
4929 ;; Try to set `org-hide' face correctly.
4930 (let ((foreground (org-find-invisible-foreground)))
4931 (when foreground
4932 (set-face-foreground 'org-hide foreground))))
4934 ;; Update `customize-package-emacs-version-alist'
4935 (add-to-list 'customize-package-emacs-version-alist
4936 '(Org ("8.0" . "24.4")
4937 ("8.1" . "24.4")
4938 ("8.2" . "24.4")
4939 ("8.2.7" . "24.4")
4940 ("8.3" . "26.1")
4941 ("9.0" . "26.1")
4942 ("9.1" . "26.1")
4943 ("9.2" . "27.1")))
4945 (defvar org-mode-transpose-word-syntax-table
4946 (let ((st (make-syntax-table text-mode-syntax-table)))
4947 (dolist (c org-emphasis-alist st)
4948 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
4950 (when (fboundp 'abbrev-table-put)
4951 (abbrev-table-put org-mode-abbrev-table
4952 :parents (list text-mode-abbrev-table)))
4954 (defun org-find-invisible-foreground ()
4955 (let ((candidates (remove
4956 "unspecified-bg"
4957 (nconc
4958 (list (face-background 'default)
4959 (face-background 'org-default))
4960 (mapcar
4961 (lambda (alist)
4962 (when (boundp alist)
4963 (cdr (assq 'background-color (symbol-value alist)))))
4964 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
4965 (list (face-foreground 'org-hide))))))
4966 (car (remove nil candidates))))
4968 (defun org-current-time (&optional rounding-minutes past)
4969 "Current time, possibly rounded to ROUNDING-MINUTES.
4970 When ROUNDING-MINUTES is not an integer, fall back on the car of
4971 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
4972 the rounding returns a past time."
4973 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
4974 (car org-time-stamp-rounding-minutes)))
4975 (time (decode-time)) res)
4976 (if (< r 1)
4977 (current-time)
4978 (setq res
4979 (apply 'encode-time
4980 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4981 (nthcdr 2 time))))
4982 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
4983 (seconds-to-time (- (float-time res) (* r 60)))
4984 res))))
4986 (defun org-today ()
4987 "Return today date, considering `org-extend-today-until'."
4988 (time-to-days
4989 (time-subtract (current-time)
4990 (list 0 (* 3600 org-extend-today-until) 0))))
4992 ;;;; Font-Lock stuff, including the activators
4994 (require 'font-lock)
4996 (defconst org-match-sexp-depth 3
4997 "Number of stacked braces for sub/superscript matching.")
4999 (defun org-create-multibrace-regexp (left right n)
5000 "Create a regular expression which will match a balanced sexp.
5001 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5002 as single character strings.
5003 The regexp returned will match the entire expression including the
5004 delimiters. It will also define a single group which contains the
5005 match except for the outermost delimiters. The maximum depth of
5006 stacked delimiters is N. Escaping delimiters is not possible."
5007 (let* ((nothing (concat "[^" left right "]*?"))
5008 (or "\\|")
5009 (re nothing)
5010 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5011 (while (> n 1)
5012 (setq n (1- n)
5013 re (concat re or next)
5014 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5015 (concat left "\\(" re "\\)" right)))
5017 (defconst org-match-substring-regexp
5018 (concat
5019 "\\(\\S-\\)\\([_^]\\)\\("
5020 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5021 "\\|"
5022 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5023 "\\|"
5024 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5025 "The regular expression matching a sub- or superscript.")
5027 (defconst org-match-substring-with-braces-regexp
5028 (concat
5029 "\\(\\S-\\)\\([_^]\\)"
5030 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5031 "The regular expression matching a sub- or superscript, forcing braces.")
5033 (defvar org-emph-face nil)
5035 (defun org-do-emphasis-faces (limit)
5036 "Run through the buffer and emphasize strings."
5037 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5038 (car org-emphasis-regexp-components))))
5039 (catch :exit
5040 (while (re-search-forward quick-re limit t)
5041 (let* ((marker (match-string 2))
5042 (verbatim? (member marker '("~" "="))))
5043 (when (save-excursion
5044 (goto-char (match-beginning 0))
5045 (and
5046 ;; Do not match table hlines.
5047 (not (and (equal marker "+")
5048 (org-match-line
5049 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5050 ;; Do not match headline stars. Do not consider
5051 ;; stars of a headline as closing marker for bold
5052 ;; markup either.
5053 (not (and (equal marker "*")
5054 (save-excursion
5055 (forward-char)
5056 (skip-chars-backward "*")
5057 (looking-at-p org-outline-regexp-bol))))
5058 ;; Match full emphasis markup regexp.
5059 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5060 ;; Do not span over paragraph boundaries.
5061 (not (string-match-p org-element-paragraph-separate
5062 (match-string 2)))
5063 ;; Do not span over cells in table rows.
5064 (not (and (save-match-data (org-match-line "[ \t]*|"))
5065 (string-match-p "|" (match-string 4))))))
5066 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5067 (font-lock-prepend-text-property
5068 (match-beginning 2) (match-end 2) 'face face)
5069 (when verbatim?
5070 (org-remove-flyspell-overlays-in
5071 (match-beginning 0) (match-end 0))
5072 (remove-text-properties (match-beginning 2) (match-end 2)
5073 '(display t invisible t intangible t)))
5074 (add-text-properties (match-beginning 2) (match-end 2)
5075 '(font-lock-multiline t org-emphasis t))
5076 (when org-hide-emphasis-markers
5077 (add-text-properties (match-end 4) (match-beginning 5)
5078 '(invisible org-link))
5079 (add-text-properties (match-beginning 3) (match-end 3)
5080 '(invisible org-link)))
5081 (throw :exit t))))))))
5083 (defun org-emphasize (&optional char)
5084 "Insert or change an emphasis, i.e. a font like bold or italic.
5085 If there is an active region, change that region to a new emphasis.
5086 If there is no region, just insert the marker characters and position
5087 the cursor between them.
5088 CHAR should be the marker character. If it is a space, it means to
5089 remove the emphasis of the selected region.
5090 If CHAR is not given (for example in an interactive call) it will be
5091 prompted for."
5092 (interactive)
5093 (let ((erc org-emphasis-regexp-components)
5094 (string "") beg end move s)
5095 (if (org-region-active-p)
5096 (setq beg (region-beginning)
5097 end (region-end)
5098 string (buffer-substring beg end))
5099 (setq move t))
5101 (unless char
5102 (message "Emphasis marker or tag: [%s]"
5103 (mapconcat #'car org-emphasis-alist ""))
5104 (setq char (read-char-exclusive)))
5105 (if (equal char ?\s)
5106 (setq s ""
5107 move nil)
5108 (unless (assoc (char-to-string char) org-emphasis-alist)
5109 (user-error "No such emphasis marker: \"%c\"" char))
5110 (setq s (char-to-string char)))
5111 (while (and (> (length string) 1)
5112 (equal (substring string 0 1) (substring string -1))
5113 (assoc (substring string 0 1) org-emphasis-alist))
5114 (setq string (substring string 1 -1)))
5115 (setq string (concat s string s))
5116 (when beg (delete-region beg end))
5117 (unless (or (bolp)
5118 (string-match (concat "[" (nth 0 erc) "\n]")
5119 (char-to-string (char-before (point)))))
5120 (insert " "))
5121 (unless (or (eobp)
5122 (string-match (concat "[" (nth 1 erc) "\n]")
5123 (char-to-string (char-after (point)))))
5124 (insert " ") (backward-char 1))
5125 (insert string)
5126 (and move (backward-char 1))))
5128 (defconst org-nonsticky-props
5129 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5131 (defsubst org-rear-nonsticky-at (pos)
5132 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5134 (defun org-activate-links (limit)
5135 "Add link properties to links.
5136 This includes angle, plain, and bracket links."
5137 (catch :exit
5138 (while (re-search-forward org-link-any-re limit t)
5139 (let* ((start (match-beginning 0))
5140 (end (match-end 0))
5141 (style (cond ((eq ?< (char-after start)) 'angle)
5142 ((eq ?\[ (char-after (1+ start))) 'bracket)
5143 (t 'plain))))
5144 (when (and (memq style org-highlight-links)
5145 ;; Do not span over paragraph boundaries.
5146 (not (string-match-p org-element-paragraph-separate
5147 (match-string 0)))
5148 ;; Do not confuse plain links with tags.
5149 (not (and (eq style 'plain)
5150 (let ((face (get-text-property
5151 (max (1- start) (point-min)) 'face)))
5152 (if (consp face) (memq 'org-tag face)
5153 (eq 'org-tag face))))))
5154 (let* ((link-object (save-excursion
5155 (goto-char start)
5156 (save-match-data (org-element-link-parser))))
5157 (link (org-element-property :raw-link link-object))
5158 (type (org-element-property :type link-object))
5159 (path (org-element-property :path link-object))
5160 (properties ;for link's visible part
5161 (list
5162 'face (pcase (org-link-get-parameter type :face)
5163 ((and (pred functionp) face) (funcall face path))
5164 ((and (pred facep) face) face)
5165 ((and (pred consp) face) face) ;anonymous
5166 (_ 'org-link))
5167 'mouse-face (or (org-link-get-parameter type :mouse-face)
5168 'highlight)
5169 'keymap (or (org-link-get-parameter type :keymap)
5170 org-mouse-map)
5171 'help-echo (pcase (org-link-get-parameter type :help-echo)
5172 ((and (pred stringp) echo) echo)
5173 ((and (pred functionp) echo) echo)
5174 (_ (concat "LINK: " link)))
5175 'htmlize-link (pcase (org-link-get-parameter type
5176 :htmlize-link)
5177 ((and (pred functionp) f) (funcall f))
5178 (_ `(:uri ,link)))
5179 'font-lock-multiline t)))
5180 (org-remove-flyspell-overlays-in start end)
5181 (org-rear-nonsticky-at end)
5182 (if (not (eq 'bracket style))
5183 (add-text-properties start end properties)
5184 ;; Handle invisible parts in bracket links.
5185 (remove-text-properties start end '(invisible nil))
5186 (let ((hidden
5187 (append `(invisible
5188 ,(or (org-link-get-parameter type :display)
5189 'org-link))
5190 properties))
5191 (visible-start (or (match-beginning 3) (match-beginning 2)))
5192 (visible-end (or (match-end 3) (match-end 2))))
5193 (add-text-properties start visible-start hidden)
5194 (add-text-properties visible-start visible-end properties)
5195 (add-text-properties visible-end end hidden)
5196 (org-rear-nonsticky-at visible-start)
5197 (org-rear-nonsticky-at visible-end)))
5198 (let ((f (org-link-get-parameter type :activate-func)))
5199 (when (functionp f)
5200 (funcall f start end path (eq style 'bracket))))
5201 (throw :exit t))))) ;signal success
5202 nil))
5204 (defun org-activate-code (limit)
5205 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5206 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5207 (remove-text-properties (match-beginning 0) (match-end 0)
5208 '(display t invisible t intangible t))
5211 (defcustom org-src-fontify-natively t
5212 "When non-nil, fontify code in code blocks.
5213 See also the `org-block' face."
5214 :type 'boolean
5215 :version "26.1"
5216 :package-version '(Org . "8.3")
5217 :group 'org-appearance
5218 :group 'org-babel)
5220 (defcustom org-allow-promoting-top-level-subtree nil
5221 "When non-nil, allow promoting a top level subtree.
5222 The leading star of the top level headline will be replaced
5223 by a #."
5224 :type 'boolean
5225 :version "24.1"
5226 :group 'org-appearance)
5228 (defun org-fontify-meta-lines-and-blocks (limit)
5229 (condition-case nil
5230 (org-fontify-meta-lines-and-blocks-1 limit)
5231 (error (message "Org mode fontification error in %S at %d"
5232 (current-buffer)
5233 (line-number-at-pos)))))
5235 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5236 "Fontify #+ lines and blocks."
5237 (let ((case-fold-search t))
5238 (when (re-search-forward
5239 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5240 limit t)
5241 (let ((beg (match-beginning 0))
5242 (block-start (match-end 0))
5243 (block-end nil)
5244 (lang (match-string 7))
5245 (beg1 (line-beginning-position 2))
5246 (dc1 (downcase (match-string 2)))
5247 (dc3 (downcase (match-string 3)))
5248 end end1 quoting block-type)
5249 (cond
5250 ((and (match-end 4) (equal dc3 "+begin"))
5251 ;; Truly a block
5252 (setq block-type (downcase (match-string 5))
5253 quoting (member block-type org-protecting-blocks))
5254 (when (re-search-forward
5255 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5256 nil t) ;; on purpose, we look further than LIMIT
5257 (setq end (min (point-max) (match-end 0))
5258 end1 (min (point-max) (1- (match-beginning 0))))
5259 (setq block-end (match-beginning 0))
5260 (when quoting
5261 (org-remove-flyspell-overlays-in beg1 end1)
5262 (remove-text-properties beg end
5263 '(display t invisible t intangible t)))
5264 (add-text-properties
5265 beg end '(font-lock-fontified t font-lock-multiline t))
5266 (add-text-properties beg beg1 '(face org-meta-line))
5267 (org-remove-flyspell-overlays-in beg beg1)
5268 (add-text-properties ; For end_src
5269 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5270 (org-remove-flyspell-overlays-in end1 end)
5271 (cond
5272 ((and lang (not (string= lang "")) org-src-fontify-natively)
5273 (org-src-font-lock-fontify-block lang block-start block-end)
5274 (add-text-properties beg1 block-end '(src-block t)))
5275 (quoting
5276 (add-text-properties beg1 (min (point-max) (1+ end1))
5277 (list 'face
5278 (list :inherit
5279 (let ((face-name
5280 (intern (format "org-block-%s" lang))))
5281 (append (and (facep face-name) (list face-name))
5282 '(org-block))))))) ; end of source block
5283 ((not org-fontify-quote-and-verse-blocks))
5284 ((string= block-type "quote")
5285 (add-face-text-property
5286 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5287 ((string= block-type "verse")
5288 (add-face-text-property
5289 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5290 (add-text-properties beg beg1 '(face org-block-begin-line))
5291 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5292 '(face org-block-end-line))
5294 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5295 (org-remove-flyspell-overlays-in
5296 (match-beginning 0)
5297 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5298 (add-text-properties
5299 beg (match-end 3)
5300 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5301 '(font-lock-fontified t invisible t)
5302 '(font-lock-fontified t face org-document-info-keyword)))
5303 (add-text-properties
5304 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5305 (if (string-equal dc1 "+title:")
5306 '(font-lock-fontified t face org-document-title)
5307 '(font-lock-fontified t face org-document-info))))
5308 ((string-prefix-p "+caption" dc1)
5309 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5310 (remove-text-properties (match-beginning 0) (match-end 0)
5311 '(display t invisible t intangible t))
5312 ;; Handle short captions.
5313 (save-excursion
5314 (beginning-of-line)
5315 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5316 (add-text-properties (line-beginning-position) (match-end 1)
5317 '(font-lock-fontified t face org-meta-line))
5318 (add-text-properties (match-end 0) (line-end-position)
5319 '(font-lock-fontified t face org-block))
5321 ((member dc3 '(" " ""))
5322 (org-remove-flyspell-overlays-in beg (match-end 0))
5323 (add-text-properties
5324 beg (match-end 0)
5325 '(font-lock-fontified t face font-lock-comment-face)))
5326 (t ;; just any other in-buffer setting, but not indented
5327 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5328 (remove-text-properties (match-beginning 0) (match-end 0)
5329 '(display t invisible t intangible t))
5330 (add-text-properties beg (match-end 0)
5331 '(font-lock-fontified t face org-meta-line))
5332 t))))))
5334 (defun org-fontify-drawers (limit)
5335 "Fontify drawers."
5336 (when (re-search-forward org-drawer-regexp limit t)
5337 (add-text-properties
5338 (match-beginning 0) (match-end 0)
5339 '(font-lock-fontified t face org-special-keyword))
5340 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5343 (defun org-fontify-macros (limit)
5344 "Fontify macros."
5345 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
5346 (let ((begin (match-beginning 0))
5347 (opening-end (match-beginning 1)))
5348 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
5349 (match-string 1))
5350 (let ((end (match-end 1))
5351 (closing-start (match-beginning 1)))
5352 (add-text-properties
5353 begin end
5354 '(font-lock-multiline t font-lock-fontified t face org-macro))
5355 (org-remove-flyspell-overlays-in begin end)
5356 (when org-hide-macro-markers
5357 (add-text-properties begin opening-end '(invisible t))
5358 (add-text-properties closing-start end '(invisible t)))
5359 t)))))
5361 (defun org-fontify-extend-region (beg end _old-len)
5362 (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
5363 (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
5364 (extend (lambda (r1 r2 dir)
5365 (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
5366 (replace-regexp-in-string "[][]" r2
5367 (match-string-no-properties 0)))))
5368 (re-search-forward (regexp-quote re) nil t dir)))))
5369 (save-match-data
5370 (save-excursion
5371 (goto-char beg)
5372 (back-to-indentation)
5373 (cond ((looking-at end-re)
5374 (cons (or (funcall extend "begin" "[" -1) beg) end))
5375 ((looking-at begin-re)
5376 (cons beg (or (funcall extend "end" "]" 1) end)))
5377 (t (cons beg end)))))))
5379 (defun org-activate-footnote-links (limit)
5380 "Add text properties for footnotes."
5381 (let ((fn (org-footnote-next-reference-or-definition limit)))
5382 (when fn
5383 (let* ((beg (nth 1 fn))
5384 (end (nth 2 fn))
5385 (label (car fn))
5386 (referencep (/= (line-beginning-position) beg)))
5387 (when (and referencep (nth 3 fn))
5388 (save-excursion
5389 (goto-char beg)
5390 (search-forward (or label "fn:"))
5391 (org-remove-flyspell-overlays-in beg (match-end 0))))
5392 (add-text-properties beg end
5393 (list 'mouse-face 'highlight
5394 'keymap org-mouse-map
5395 'help-echo
5396 (if referencep "Footnote reference"
5397 "Footnote definition")
5398 'font-lock-fontified t
5399 'font-lock-multiline t
5400 'face 'org-footnote))))))
5402 (defun org-activate-dates (limit)
5403 "Add text properties for dates."
5404 (when (and (re-search-forward org-tsr-regexp-both limit t)
5405 (not (equal (char-before (match-beginning 0)) 91)))
5406 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5407 (add-text-properties (match-beginning 0) (match-end 0)
5408 (list 'mouse-face 'highlight
5409 'keymap org-mouse-map))
5410 (org-rear-nonsticky-at (match-end 0))
5411 (when org-display-custom-times
5412 ;; If it's a date range, activate custom time for second date.
5413 (when (match-end 3)
5414 (org-display-custom-time (match-beginning 3) (match-end 3)))
5415 (org-display-custom-time (match-beginning 1) (match-end 1)))
5418 (defun org-activate-target-links (limit)
5419 "Add text properties for target matches."
5420 (when org-target-link-regexp
5421 (let ((case-fold-search t))
5422 ;; `org-target-link-regexp' matches one character before the
5423 ;; actual target.
5424 (unless (bolp) (forward-char -1))
5425 (when (re-search-forward org-target-link-regexp limit t)
5426 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5427 (add-text-properties (match-beginning 1) (match-end 1)
5428 (list 'mouse-face 'highlight
5429 'keymap org-mouse-map
5430 'help-echo "Radio target link"
5431 'org-linked-text t))
5432 (org-rear-nonsticky-at (match-end 1))
5433 t))))
5435 (defvar org-latex-and-related-regexp nil
5436 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5438 (defun org-compute-latex-and-related-regexp ()
5439 "Compute regular expression for LaTeX, entities and sub/superscript.
5440 Result depends on variable `org-highlight-latex-and-related'."
5441 (let ((re-sub
5442 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5443 ((eq org-use-sub-superscripts '{})
5444 (list org-match-substring-with-braces-regexp))
5445 (org-use-sub-superscripts (list org-match-substring-regexp))))
5446 (re-latex
5447 (when (or (memq 'latex org-highlight-latex-and-related)
5448 (memq 'native org-highlight-latex-and-related))
5449 (let ((matchers (plist-get org-format-latex-options :matchers)))
5450 (delq nil
5451 (mapcar (lambda (x)
5452 (and (member (car x) matchers) (nth 1 x)))
5453 org-latex-regexps)))))
5454 (re-entities
5455 (when (memq 'entities org-highlight-latex-and-related)
5456 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
5457 \\($\\|{}\\|[^[:alpha:]]\\)"))))
5458 (setq-local org-latex-and-related-regexp
5459 (mapconcat #'identity
5460 (append re-latex re-entities re-sub)
5461 "\\|"))))
5463 (defun org-do-latex-and-related (_limit)
5464 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5465 Stop at first highlighted object, if any. Return t if some
5466 highlighting was done, nil otherwise."
5467 (when (org-string-nw-p org-latex-and-related-regexp)
5468 (catch 'found
5469 (while (re-search-forward org-latex-and-related-regexp
5470 nil t) ;; on purpose, we ignore LIMIT
5471 (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
5472 org-special-keyword)))
5473 (save-excursion
5474 (goto-char (1+ (match-beginning 0)))
5475 (face-at-point nil t)))
5476 (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
5477 '(?_ ?^))
5480 (start (+ offset (match-beginning 0)))
5481 (end (match-end 0)))
5482 (if (memq 'native org-highlight-latex-and-related)
5483 (org-src-font-lock-fontify-block "latex" start end)
5484 (font-lock-prepend-text-property start end
5485 'face 'org-latex-and-related))
5486 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5487 '(font-lock-multiline t)))
5488 (throw 'found t)))
5489 nil)))
5491 (defun org-restart-font-lock ()
5492 "Restart `font-lock-mode', to force refontification."
5493 (when (and (boundp 'font-lock-mode) font-lock-mode)
5494 (font-lock-mode -1)
5495 (font-lock-mode 1)))
5497 (defun org-activate-tags (limit)
5498 (when (re-search-forward org-tag-line-re limit t)
5499 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5500 (add-text-properties (match-beginning 1) (match-end 1)
5501 (list 'mouse-face 'highlight
5502 'keymap org-mouse-map))
5503 (org-rear-nonsticky-at (match-end 1))
5506 (defun org-outline-level ()
5507 "Compute the outline level of the heading at point.
5509 If this is called at a normal headline, the level is the number
5510 of stars. Use `org-reduced-level' to remove the effect of
5511 `org-odd-levels'. Unlike to `org-current-level', this function
5512 takes into consideration inlinetasks."
5513 (org-with-wide-buffer
5514 (end-of-line)
5515 (if (re-search-backward org-outline-regexp-bol nil t)
5516 (1- (- (match-end 0) (match-beginning 0)))
5517 0)))
5519 (defvar org-font-lock-keywords nil)
5521 (defsubst org-re-property (property &optional literal allow-null value)
5522 "Return a regexp matching a PROPERTY line.
5524 When optional argument LITERAL is non-nil, do not quote PROPERTY.
5525 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
5526 non-nil, match properties even without a value.
5528 Match group 3 is set to the value when it exists. If there is no
5529 value and ALLOW-NULL is non-nil, it is set to the empty string.
5531 With optional argument VALUE, match only property lines with
5532 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
5533 unless LITERAL is non-nil."
5534 (concat
5535 "^\\(?4:[ \t]*\\)"
5536 (format "\\(?1::\\(?2:%s\\):\\)"
5537 (if literal property (regexp-quote property)))
5538 (cond (value
5539 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
5540 (if literal value (regexp-quote value))))
5541 (allow-null
5542 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
5544 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
5546 (defconst org-property-re
5547 (org-re-property "\\S-+" 'literal t)
5548 "Regular expression matching a property line.
5549 There are four matching groups:
5550 1: :PROPKEY: including the leading and trailing colon,
5551 2: PROPKEY without the leading and trailing colon,
5552 3: PROPVAL without leading or trailing spaces,
5553 4: the indentation of the current line,
5554 5: trailing whitespace.")
5556 (defvar org-font-lock-hook nil
5557 "Functions to be called for special font lock stuff.")
5559 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
5561 (defvar org-font-lock-set-keywords-hook nil
5562 "Functions that can manipulate `org-font-lock-extra-keywords'.
5563 This is called after `org-font-lock-extra-keywords' is defined, but before
5564 it is installed to be used by font lock. This can be useful if something
5565 needs to be inserted at a specific position in the font-lock sequence.")
5567 (defun org-font-lock-hook (limit)
5568 "Run `org-font-lock-hook' within LIMIT."
5569 (run-hook-with-args 'org-font-lock-hook limit))
5571 (defun org-set-font-lock-defaults ()
5572 "Set font lock defaults for the current buffer."
5573 (let* ((em org-fontify-emphasized-text)
5574 (lk org-highlight-links)
5575 (org-font-lock-extra-keywords
5576 (list
5577 ;; Call the hook
5578 '(org-font-lock-hook)
5579 ;; Headlines
5580 `(,(if org-fontify-whole-heading-line
5581 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5582 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5583 (1 (org-get-level-face 1))
5584 (2 (org-get-level-face 2))
5585 (3 (org-get-level-face 3)))
5586 ;; Table lines
5587 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5588 (1 'org-table t))
5589 ;; Table internals
5590 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5591 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5592 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5593 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5594 ;; Drawers
5595 '(org-fontify-drawers)
5596 ;; Properties
5597 (list org-property-re
5598 '(1 'org-special-keyword t)
5599 '(3 'org-property-value t))
5600 ;; Link related fontification.
5601 '(org-activate-links)
5602 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5603 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
5604 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5605 (when (memq 'footnote lk) '(org-activate-footnote-links))
5606 ;; Targets.
5607 (list org-radio-target-regexp '(0 'org-target t))
5608 (list org-target-regexp '(0 'org-target t))
5609 ;; Diary sexps.
5610 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5611 ;; Macro
5612 '(org-fontify-macros)
5613 ;; TODO keyword
5614 (list (format org-heading-keyword-regexp-format
5615 org-todo-regexp)
5616 '(2 (org-get-todo-face 2) t))
5617 ;; DONE
5618 (if org-fontify-done-headline
5619 (list (format org-heading-keyword-regexp-format
5620 (concat
5621 "\\(?:"
5622 (mapconcat 'regexp-quote org-done-keywords "\\|")
5623 "\\)"))
5624 '(2 'org-headline-done t))
5625 nil)
5626 ;; Priorities
5627 '(org-font-lock-add-priority-faces)
5628 ;; Tags
5629 '(org-font-lock-add-tag-faces)
5630 ;; Tags groups
5631 (when (and org-group-tags org-tag-groups-alist)
5632 (list (concat org-outline-regexp-bol ".+\\(:"
5633 (regexp-opt (mapcar 'car org-tag-groups-alist))
5634 ":\\).*$")
5635 '(1 'org-tag-group prepend)))
5636 ;; Special keywords
5637 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5638 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5639 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5640 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5641 ;; Emphasis
5642 (when em '(org-do-emphasis-faces))
5643 ;; Checkboxes
5644 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5645 1 'org-checkbox prepend)
5646 (when (cdr (assq 'checkbox org-list-automatic-rules))
5647 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5648 (0 (org-get-checkbox-statistics-face) t)))
5649 ;; Description list items
5650 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5651 1 'org-list-dt prepend)
5652 ;; ARCHIVEd headings
5653 (list (concat
5654 org-outline-regexp-bol
5655 "\\(.*:" org-archive-tag ":.*\\)")
5656 '(1 'org-archived prepend))
5657 ;; Specials
5658 '(org-do-latex-and-related)
5659 '(org-fontify-entities)
5660 '(org-raise-scripts)
5661 ;; Code
5662 '(org-activate-code (1 'org-code t))
5663 ;; COMMENT
5664 (list (format
5665 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
5666 org-todo-regexp
5667 org-comment-string)
5668 '(9 'org-special-keyword t))
5669 ;; Blocks and meta lines
5670 '(org-fontify-meta-lines-and-blocks))))
5671 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5672 (run-hooks 'org-font-lock-set-keywords-hook)
5673 ;; Now set the full font-lock-keywords
5674 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
5675 (setq-local font-lock-defaults
5676 '(org-font-lock-keywords t nil nil backward-paragraph))
5677 (setq-local font-lock-extend-after-change-region-function
5678 #'org-fontify-extend-region)
5679 (kill-local-variable 'font-lock-keywords)
5680 nil))
5682 (defun org-toggle-pretty-entities ()
5683 "Toggle the composition display of entities as UTF8 characters."
5684 (interactive)
5685 (setq-local org-pretty-entities (not org-pretty-entities))
5686 (org-restart-font-lock)
5687 (if org-pretty-entities
5688 (message "Entities are now displayed as UTF8 characters")
5689 (save-restriction
5690 (widen)
5691 (decompose-region (point-min) (point-max))
5692 (message "Entities are now displayed as plain text"))))
5694 (defvar-local org-custom-properties-overlays nil
5695 "List of overlays used for custom properties.")
5697 (defun org-toggle-custom-properties-visibility ()
5698 "Display or hide properties in `org-custom-properties'."
5699 (interactive)
5700 (if org-custom-properties-overlays
5701 (progn (mapc #'delete-overlay org-custom-properties-overlays)
5702 (setq org-custom-properties-overlays nil))
5703 (when org-custom-properties
5704 (org-with-wide-buffer
5705 (goto-char (point-min))
5706 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
5707 (while (re-search-forward regexp nil t)
5708 (let ((end (cdr (save-match-data (org-get-property-block)))))
5709 (when (and end (< (point) end))
5710 ;; Hide first custom property in current drawer.
5711 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5712 (overlay-put o 'invisible t)
5713 (overlay-put o 'org-custom-property t)
5714 (push o org-custom-properties-overlays))
5715 ;; Hide additional custom properties in the same drawer.
5716 (while (re-search-forward regexp end t)
5717 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5718 (overlay-put o 'invisible t)
5719 (overlay-put o 'org-custom-property t)
5720 (push o org-custom-properties-overlays)))))
5721 ;; Each entry is limited to a single property drawer.
5722 (outline-next-heading)))))))
5724 (defun org-fontify-entities (limit)
5725 "Find an entity to fontify."
5726 (let (ee)
5727 (when org-pretty-entities
5728 (catch 'match
5729 ;; "\_ "-family is left out on purpose. Only the first one,
5730 ;; i.e., "\_ ", could be fontified anyway, and it would be
5731 ;; confusing when adding a second white space character.
5732 (while (re-search-forward
5733 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5734 limit t)
5735 (when (and (not (org-at-comment-p))
5736 (setq ee (org-entity-get (match-string 1)))
5737 (= (length (nth 6 ee)) 1))
5738 (let* ((end (if (equal (match-string 2) "{}")
5739 (match-end 2)
5740 (match-end 1))))
5741 (add-text-properties
5742 (match-beginning 0) end
5743 (list 'font-lock-fontified t))
5744 (compose-region (match-beginning 0) end
5745 (nth 6 ee) nil)
5746 (backward-char 1)
5747 (throw 'match t))))
5748 nil))))
5750 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5751 "Fontify string S like in Org mode."
5752 (with-temp-buffer
5753 (insert s)
5754 (let ((org-odd-levels-only odd-levels))
5755 (org-mode)
5756 (org-font-lock-ensure)
5757 (buffer-string))))
5759 (defvar org-m nil)
5760 (defvar org-l nil)
5761 (defvar org-f nil)
5762 (defun org-get-level-face (n)
5763 "Get the right face for match N in font-lock matching of headlines."
5764 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5765 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5766 (if org-cycle-level-faces
5767 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5768 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5769 (cond
5770 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5771 ((eq n 2) org-f)
5772 (t (unless org-level-color-stars-only org-f))))
5774 (defun org-face-from-face-or-color (context inherit face-or-color)
5775 "Create a face list that inherits INHERIT, but sets the foreground color.
5776 When FACE-OR-COLOR is not a string, just return it."
5777 (if (stringp face-or-color)
5778 (list :inherit inherit
5779 (cdr (assoc context org-faces-easy-properties))
5780 face-or-color)
5781 face-or-color))
5783 (defun org-get-todo-face (kwd)
5784 "Get the right face for a TODO keyword KWD.
5785 If KWD is a number, get the corresponding match group."
5786 (when (numberp kwd) (setq kwd (match-string kwd)))
5787 (or (org-face-from-face-or-color
5788 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5789 (and (member kwd org-done-keywords) 'org-done)
5790 'org-todo))
5792 (defun org-get-priority-face (priority)
5793 "Get the right face for PRIORITY.
5794 PRIORITY is a character."
5795 (or (org-face-from-face-or-color
5796 'priority 'org-priority (cdr (assq priority org-priority-faces)))
5797 'org-priority))
5799 (defun org-get-tag-face (tag)
5800 "Get the right face for TAG.
5801 If TAG is a number, get the corresponding match group."
5802 (let ((tag (if (wholenump tag) (match-string tag) tag)))
5803 (or (org-face-from-face-or-color
5804 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
5805 'org-tag)))
5807 (defun org-font-lock-add-priority-faces (limit)
5808 "Add the special priority faces."
5809 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
5810 (add-text-properties
5811 (match-beginning 1) (match-end 1)
5812 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
5813 'font-lock-fontified t))))
5815 (defun org-font-lock-add-tag-faces (limit)
5816 "Add the special tag faces."
5817 (when (and org-tag-faces org-tags-special-faces-re)
5818 (while (re-search-forward org-tags-special-faces-re limit t)
5819 (add-text-properties (match-beginning 1) (match-end 1)
5820 (list 'face (org-get-tag-face 1)
5821 'font-lock-fontified t))
5822 (backward-char 1))))
5824 (defun org-unfontify-region (beg end &optional _maybe_loudly)
5825 "Remove fontification and activation overlays from links."
5826 (font-lock-default-unfontify-region beg end)
5827 (let* ((buffer-undo-list t)
5828 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5829 (inhibit-modification-hooks t)
5830 deactivate-mark buffer-file-name buffer-file-truename)
5831 (decompose-region beg end)
5832 (remove-text-properties beg end
5833 '(mouse-face t keymap t org-linked-text t
5834 invisible t intangible t
5835 org-emphasis t))
5836 (org-remove-font-lock-display-properties beg end)))
5838 (defconst org-script-display '(((raise -0.3) (height 0.7))
5839 ((raise 0.3) (height 0.7))
5840 ((raise -0.5))
5841 ((raise 0.5)))
5842 "Display properties for showing superscripts and subscripts.")
5844 (defun org-remove-font-lock-display-properties (beg end)
5845 "Remove specific display properties that have been added by font lock.
5846 The will remove the raise properties that are used to show superscripts
5847 and subscripts."
5848 (let (next prop)
5849 (while (< beg end)
5850 (setq next (next-single-property-change beg 'display nil end)
5851 prop (get-text-property beg 'display))
5852 (when (member prop org-script-display)
5853 (put-text-property beg next 'display nil))
5854 (setq beg next))))
5856 (defun org-raise-scripts (limit)
5857 "Add raise properties to sub/superscripts."
5858 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
5859 (re-search-forward
5860 (if (eq org-use-sub-superscripts t)
5861 org-match-substring-regexp
5862 org-match-substring-with-braces-regexp)
5863 limit t))
5864 (let* ((pos (point)) table-p comment-p
5865 (mpos (match-beginning 3))
5866 (emph-p (get-text-property mpos 'org-emphasis))
5867 (link-p (get-text-property mpos 'mouse-face))
5868 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5869 (goto-char (point-at-bol))
5870 (setq table-p (looking-at-p org-table-dataline-regexp)
5871 comment-p (looking-at-p "^[ \t]*#[ +]"))
5872 (goto-char pos)
5873 ;; Handle a_b^c
5874 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
5875 (unless (or comment-p emph-p link-p keyw-p)
5876 (put-text-property (match-beginning 3) (match-end 0)
5877 'display
5878 (if (equal (char-after (match-beginning 2)) ?^)
5879 (nth (if table-p 3 1) org-script-display)
5880 (nth (if table-p 2 0) org-script-display)))
5881 (add-text-properties (match-beginning 2) (match-end 2)
5882 (list 'invisible t))
5883 (when (and (eq (char-after (match-beginning 3)) ?{)
5884 (eq (char-before (match-end 3)) ?}))
5885 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
5886 (list 'invisible t))
5887 (add-text-properties (1- (match-end 3)) (match-end 3)
5888 (list 'invisible t))))
5889 t)))
5891 (defun org-remove-empty-overlays-at (pos)
5892 "Remove outline overlays that do not contain non-white stuff."
5893 (dolist (o (overlays-at pos))
5894 (and (eq 'outline (overlay-get o 'invisible))
5895 (not (string-match "\\S-" (buffer-substring (overlay-start o)
5896 (overlay-end o))))
5897 (delete-overlay o))))
5899 (defun org-show-empty-lines-in-parent ()
5900 "Move to the parent and re-show empty lines before visible headlines."
5901 (save-excursion
5902 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5903 (org-cycle-show-empty-lines context))))
5905 (defun org-files-list ()
5906 "Return `org-agenda-files' list, plus all open Org files.
5907 This is useful for operations that need to scan all of a user's
5908 open and agenda-wise Org files."
5909 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
5910 (dolist (buf (buffer-list))
5911 (with-current-buffer buf
5912 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
5913 (cl-pushnew (expand-file-name (buffer-file-name)) files
5914 :test #'equal))))
5915 files))
5917 (defsubst org-entry-beginning-position ()
5918 "Return the beginning position of the current entry."
5919 (save-excursion (org-back-to-heading t) (point)))
5921 (defsubst org-entry-end-position ()
5922 "Return the end position of the current entry."
5923 (save-excursion (outline-next-heading) (point)))
5925 (defun org-subtree-end-visible-p ()
5926 "Is the end of the current subtree visible?"
5927 (pos-visible-in-window-p
5928 (save-excursion (org-end-of-subtree t) (point))))
5930 (defun org-first-headline-recenter ()
5931 "Move cursor to the first headline and recenter the headline."
5932 (let ((window (get-buffer-window)))
5933 (when window
5934 (goto-char (point-min))
5935 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
5936 (set-window-start window (line-beginning-position))))))
5939 ;;; Visibility (headlines, blocks, drawers)
5941 ;;;; Headlines visibility
5943 (defun org-show-entry ()
5944 "Show the body directly following this heading.
5945 Show the heading too, if it is currently invisible."
5946 (interactive)
5947 (save-excursion
5948 (ignore-errors
5949 (org-back-to-heading t)
5950 (org-flag-region
5951 (line-end-position 0)
5952 (save-excursion
5953 (if (re-search-forward
5954 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
5955 (match-beginning 1)
5956 (point-max)))
5958 'outline))))
5960 (defun org-show-children (&optional level)
5961 "Show all direct subheadings of this heading.
5962 Prefix arg LEVEL is how many levels below the current level
5963 should be shown. Default is enough to cause the following
5964 heading to appear."
5965 (interactive "p")
5966 (save-excursion
5967 (org-back-to-heading t)
5968 (let* ((current-level (funcall outline-level))
5969 (max-level (org-get-valid-level
5970 current-level
5971 (if level (prefix-numeric-value level) 1)))
5972 (end (save-excursion (org-end-of-subtree t t)))
5973 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
5974 (past-first-child nil)
5975 ;; Make sure to skip inlinetasks.
5976 (re (format regexp-fmt
5977 current-level
5978 (cond
5979 ((not (featurep 'org-inlinetask)) "")
5980 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
5982 (t (1- org-inlinetask-min-level))))))
5983 ;; Display parent heading.
5984 (org-flag-heading nil)
5985 (forward-line)
5986 ;; Display children. First child may be deeper than expected
5987 ;; MAX-LEVEL. Since we want to display it anyway, adjust
5988 ;; MAX-LEVEL accordingly.
5989 (while (re-search-forward re end t)
5990 (unless past-first-child
5991 (setq re (format regexp-fmt
5992 current-level
5993 (max (funcall outline-level) max-level)))
5994 (setq past-first-child t))
5995 (org-flag-heading nil)))))
5997 (defun org-show-subtree ()
5998 "Show everything after this heading at deeper levels."
5999 (interactive)
6000 (org-flag-region
6001 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6003 ;;;; Blocks visibility
6005 (defun org-hide-block-toggle-maybe ()
6006 "Toggle visibility of block at point.
6007 Unlike to `org-hide-block-toggle', this function does not throw
6008 an error. Return a non-nil value when toggling is successful."
6009 (interactive)
6010 (ignore-errors (org-hide-block-toggle)))
6012 (defun org-hide-block-toggle (&optional force)
6013 "Toggle the visibility of the current block.
6014 When optional argument FORCE is `off', make block visible. If it
6015 is non-nil, hide it unconditionally. Throw an error when not at
6016 a block. Return a non-nil value when toggling is successful."
6017 (interactive)
6018 (let ((element (org-element-at-point)))
6019 (unless (memq (org-element-type element)
6020 '(center-block comment-block dynamic-block example-block
6021 export-block quote-block special-block
6022 src-block verse-block))
6023 (user-error "Not at a block"))
6024 (let* ((post (org-element-property :post-affiliated element))
6025 (start (save-excursion
6026 (goto-char post)
6027 (line-end-position)))
6028 (end (save-excursion
6029 (goto-char (org-element-property :end element))
6030 (skip-chars-backward " \t\n")
6031 (line-end-position))))
6032 ;; Do nothing when not before or at the block opening line or at
6033 ;; the block closing line.
6034 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6035 (cond ((eq force 'off)
6036 (org-flag-region start end nil 'org-hide-block))
6037 (force
6038 (org-flag-region start end t 'org-hide-block))
6039 ((eq (get-char-property start 'invisible) 'org-hide-block)
6040 (org-flag-region start end nil 'org-hide-block))
6042 (org-flag-region start end t 'org-hide-block)))
6043 ;; When the block is hidden away, make sure point is left in
6044 ;; a visible part of the buffer.
6045 (when (invisible-p (max (1- (point)) (point-min)))
6046 (goto-char post))
6047 ;; Signal success.
6048 t))))
6050 (defun org-hide-block-toggle-all ()
6051 "Toggle the visibility of all blocks in the current buffer."
6052 (org-block-map 'org-hide-block-toggle))
6054 (defun org-hide-block-all ()
6055 "Fold all blocks in the current buffer."
6056 (interactive)
6057 (org-show-all '(blocks))
6058 (org-block-map 'org-hide-block-toggle-maybe))
6060 ;;;; Drawers visibility
6062 (defun org-cycle-hide-drawers (state &optional exceptions)
6063 "Re-hide all drawers after a visibility state change.
6064 STATE should be one of the symbols listed in the docstring of
6065 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6066 a list of strings specifying which drawers should not be hidden."
6067 (when (and (derived-mode-p 'org-mode)
6068 (not (memq state '(overview folded contents))))
6069 (save-excursion
6070 (let* ((globalp (eq state 'all))
6071 (beg (if globalp (point-min) (point)))
6072 (end (if globalp (point-max)
6073 (if (eq state 'children)
6074 (save-excursion (outline-next-heading) (point))
6075 (org-end-of-subtree t)))))
6076 (goto-char beg)
6077 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6078 (unless (member-ignore-case (match-string 1) exceptions)
6079 (let ((drawer (org-element-at-point)))
6080 (when (memq (org-element-type drawer) '(drawer property-drawer))
6081 (org-flag-drawer t drawer)
6082 ;; Make sure to skip drawer entirely or we might flag
6083 ;; it another time when matching its ending line with
6084 ;; `org-drawer-regexp'.
6085 (goto-char (org-element-property :end drawer))))))))))
6087 (defun org-flag-drawer (flag &optional element)
6088 "When FLAG is non-nil, hide the drawer we are at.
6089 Otherwise make it visible. When optional argument ELEMENT is
6090 a parsed drawer, as returned by `org-element-at-point', hide or
6091 show that drawer instead."
6092 (let ((drawer (or element
6093 (and (save-excursion
6094 (beginning-of-line)
6095 (looking-at-p org-drawer-regexp))
6096 (org-element-at-point)))))
6097 (when (memq (org-element-type drawer) '(drawer property-drawer))
6098 (let ((post (org-element-property :post-affiliated drawer)))
6099 (org-flag-region
6100 (save-excursion (goto-char post) (line-end-position))
6101 (save-excursion (goto-char (org-element-property :end drawer))
6102 (skip-chars-backward " \t\n")
6103 (line-end-position))
6104 flag 'org-hide-drawer)
6105 ;; When the drawer is hidden away, make sure point lies in
6106 ;; a visible part of the buffer.
6107 (when (invisible-p (max (1- (point)) (point-min)))
6108 (goto-char post))))))
6110 ;;;; Visibility cycling
6112 (defvar-local org-cycle-global-status nil)
6113 (put 'org-cycle-global-status 'org-state t)
6114 (defvar-local org-cycle-subtree-status nil)
6115 (put 'org-cycle-subtree-status 'org-state t)
6117 (defun org-show-all (&optional types)
6118 "Show all contents in the visible part of the buffer.
6119 By default, the function expands headings, blocks and drawers.
6120 When optional argument TYPE is a list of symbols among `blocks',
6121 `drawers' and `headings', to only expand one specific type."
6122 (interactive)
6123 (dolist (type (or types '(blocks drawers headings)))
6124 (org-flag-region (point-min) (point-max) nil
6125 (pcase type
6126 (`blocks 'org-hide-block)
6127 (`drawers 'org-hide-drawer)
6128 (`headings 'outline)
6129 (_ (error "Invalid type: %S" type))))))
6131 ;;;###autoload
6132 (defun org-cycle (&optional arg)
6133 "TAB-action and visibility cycling for Org mode.
6135 This is the command invoked in Org mode by the `TAB' key. Its main
6136 purpose is outline visibility cycling, but it also invokes other actions
6137 in special contexts.
6139 When this function is called with a `\\[universal-argument]' prefix, rotate \
6140 the entire
6141 buffer through 3 states (global cycling)
6142 1. OVERVIEW: Show only top-level headlines.
6143 2. CONTENTS: Show all headlines of all levels, but no body text.
6144 3. SHOW ALL: Show everything.
6146 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6147 switch to the startup visibility,
6148 determined by the variable `org-startup-folded', and by any VISIBILITY
6149 properties in the buffer.
6151 With a `\\[universal-argument] \\[universal-argument] \
6152 \\[universal-argument]' prefix argument, show the entire buffer, including
6153 any drawers.
6155 When inside a table, re-align the table and move to the next field.
6157 When point is at the beginning of a headline, rotate the subtree started
6158 by this line through 3 different states (local cycling)
6159 1. FOLDED: Only the main headline is shown.
6160 2. CHILDREN: The main headline and the direct children are shown.
6161 From this state, you can move to one of the children
6162 and zoom in further.
6163 3. SUBTREE: Show the entire subtree, including body text.
6164 If there is no subtree, switch directly from CHILDREN to FOLDED.
6166 When point is at the beginning of an empty headline and the variable
6167 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6168 of the headline by demoting and promoting it to likely levels. This
6169 speeds up creation document structure by pressing `TAB' once or several
6170 times right after creating a new headline.
6172 When there is a numeric prefix, go up to a heading with level ARG, do
6173 a `show-subtree' and return to the previous cursor position. If ARG
6174 is negative, go up that many levels.
6176 When point is not at the beginning of a headline, execute the global
6177 binding for `TAB', which is re-indenting the line. See the option
6178 `org-cycle-emulate-tab' for details.
6180 As a special case, if point is at the beginning of the buffer and there is
6181 no headline in line 1, this function will act as if called with prefix arg
6182 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6183 prefix arg, but only
6184 if the variable `org-cycle-global-at-bob' is t."
6185 (interactive "P")
6186 (org-load-modules-maybe)
6187 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6188 (and org-cycle-level-after-item/entry-creation
6189 (or (org-cycle-level)
6190 (org-cycle-item-indentation))))
6191 (let* ((limit-level
6192 (or org-cycle-max-level
6193 (and (boundp 'org-inlinetask-min-level)
6194 org-inlinetask-min-level
6195 (1- org-inlinetask-min-level))))
6196 (nstars (and limit-level
6197 (if org-odd-levels-only
6198 (and limit-level (1- (* limit-level 2)))
6199 limit-level)))
6200 (org-outline-regexp
6201 (if (not (derived-mode-p 'org-mode))
6202 outline-regexp
6203 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6204 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6205 (not (looking-at org-outline-regexp))))
6206 (org-cycle-hook
6207 (if bob-special
6208 (delq 'org-optimize-window-after-visibility-change
6209 (copy-sequence org-cycle-hook))
6210 org-cycle-hook))
6211 (pos (point)))
6213 (cond
6215 ((equal arg '(16))
6216 (setq last-command 'dummy)
6217 (org-set-startup-visibility)
6218 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6220 ((equal arg '(64))
6221 (org-show-all)
6222 (org-unlogged-message "Entire buffer visible, including drawers"))
6224 ((equal arg '(4)) (org-cycle-internal-global))
6226 ;; Try hiding block at point.
6227 ((org-hide-block-toggle-maybe))
6229 ;; Try cdlatex TAB completion
6230 ((org-try-cdlatex-tab))
6232 ;; Table: enter it or move to the next field.
6233 ((org-at-table-p 'any)
6234 (if (org-at-table.el-p)
6235 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6236 Use `\\[org-edit-special]' to edit table.el tables"))
6237 (if arg (org-table-edit-field t)
6238 (org-table-justify-field-maybe)
6239 (call-interactively 'org-table-next-field))))
6241 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6243 ;; Global cycling: delegate to `org-cycle-internal-global'.
6244 (bob-special (org-cycle-internal-global))
6246 ;; Drawers: delegate to `org-flag-drawer'.
6247 ((save-excursion
6248 (beginning-of-line 1)
6249 (looking-at org-drawer-regexp))
6250 (org-flag-drawer ; toggle block visibility
6251 (not (get-char-property (match-end 0) 'invisible))))
6253 ;; Show-subtree, ARG levels up from here.
6254 ((integerp arg)
6255 (save-excursion
6256 (org-back-to-heading)
6257 (outline-up-heading (if (< arg 0) (- arg)
6258 (- (funcall outline-level) arg)))
6259 (org-show-subtree)))
6261 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6262 ((and (featurep 'org-inlinetask)
6263 (org-inlinetask-at-task-p)
6264 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6265 (org-inlinetask-toggle-visibility))
6267 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6268 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6269 (save-excursion (move-beginning-of-line 1)
6270 (looking-at org-outline-regexp)))
6271 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6272 (org-cycle-internal-local))
6274 ;; From there: TAB emulation and template completion.
6275 (buffer-read-only (org-back-to-heading))
6277 ((run-hook-with-args-until-success
6278 'org-tab-after-check-for-cycling-hook))
6280 ((run-hook-with-args-until-success
6281 'org-tab-before-tab-emulation-hook))
6283 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6284 (or (not (bolp))
6285 (not (looking-at org-outline-regexp))))
6286 (call-interactively (global-key-binding "\t")))
6288 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6289 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6290 (or (and (eq org-cycle-emulate-tab 'white)
6291 (= (match-end 0) (point-at-eol)))
6292 (and (eq org-cycle-emulate-tab 'whitestart)
6293 (>= (match-end 0) pos))))
6295 (eq org-cycle-emulate-tab t))
6296 (call-interactively (global-key-binding "\t")))
6298 (t (save-excursion
6299 (org-back-to-heading)
6300 (org-cycle)))))))
6302 (defun org-cycle-internal-global ()
6303 "Do the global cycling action."
6304 ;; Hack to avoid display of messages for .org attachments in Gnus
6305 (let ((ga (string-match "\\*fontification" (buffer-name))))
6306 (cond
6307 ((and (eq last-command this-command)
6308 (eq org-cycle-global-status 'overview))
6309 ;; We just created the overview - now do table of contents
6310 ;; This can be slow in very large buffers, so indicate action
6311 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6312 (unless ga (org-unlogged-message "CONTENTS..."))
6313 (org-content)
6314 (unless ga (org-unlogged-message "CONTENTS...done"))
6315 (setq org-cycle-global-status 'contents)
6316 (run-hook-with-args 'org-cycle-hook 'contents))
6318 ((and (eq last-command this-command)
6319 (eq org-cycle-global-status 'contents))
6320 ;; We just showed the table of contents - now show everything
6321 (run-hook-with-args 'org-pre-cycle-hook 'all)
6322 (org-show-all '(headings blocks))
6323 (unless ga (org-unlogged-message "SHOW ALL"))
6324 (setq org-cycle-global-status 'all)
6325 (run-hook-with-args 'org-cycle-hook 'all))
6328 ;; Default action: go to overview
6329 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6330 (org-overview)
6331 (unless ga (org-unlogged-message "OVERVIEW"))
6332 (setq org-cycle-global-status 'overview)
6333 (run-hook-with-args 'org-cycle-hook 'overview)))))
6335 (defvar org-called-with-limited-levels nil
6336 "Non-nil when `org-with-limited-levels' is currently active.")
6338 (defun org-cycle-internal-local ()
6339 "Do the local cycling action."
6340 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6341 ;; First, determine end of headline (EOH), end of subtree or item
6342 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6343 (save-excursion
6344 (if (org-at-item-p)
6345 (progn
6346 (beginning-of-line)
6347 (setq struct (org-list-struct))
6348 (setq eoh (point-at-eol))
6349 (setq eos (org-list-get-item-end-before-blank (point) struct))
6350 (setq has-children (org-list-has-child-p (point) struct)))
6351 (org-back-to-heading)
6352 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6353 (setq eos (save-excursion (org-end-of-subtree t t)
6354 (when (bolp) (backward-char)) (point)))
6355 (setq has-children
6356 (or (save-excursion
6357 (let ((level (funcall outline-level)))
6358 (outline-next-heading)
6359 (and (org-at-heading-p t)
6360 (> (funcall outline-level) level))))
6361 (save-excursion
6362 (org-list-search-forward (org-item-beginning-re) eos t)))))
6363 ;; Determine end invisible part of buffer (EOL)
6364 (beginning-of-line 2)
6365 (while (and (not (eobp)) ;This is like `next-line'.
6366 (get-char-property (1- (point)) 'invisible))
6367 (goto-char (next-single-char-property-change (point) 'invisible))
6368 (and (eolp) (beginning-of-line 2)))
6369 (setq eol (point)))
6370 ;; Find out what to do next and set `this-command'
6371 (cond
6372 ((= eos eoh)
6373 ;; Nothing is hidden behind this heading
6374 (unless (org-before-first-heading-p)
6375 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6376 (org-unlogged-message "EMPTY ENTRY")
6377 (setq org-cycle-subtree-status nil)
6378 (save-excursion
6379 (goto-char eos)
6380 (outline-next-heading)
6381 (when (org-invisible-p) (org-flag-heading nil))))
6382 ((and (or (>= eol eos)
6383 (not (string-match "\\S-" (buffer-substring eol eos))))
6384 (or has-children
6385 (not (setq children-skipped
6386 org-cycle-skip-children-state-if-no-children))))
6387 ;; Entire subtree is hidden in one line: children view
6388 (unless (org-before-first-heading-p)
6389 (run-hook-with-args 'org-pre-cycle-hook 'children))
6390 (if (org-at-item-p)
6391 (org-list-set-item-visibility (point-at-bol) struct 'children)
6392 (org-show-entry)
6393 (org-with-limited-levels (org-show-children))
6394 (org-show-set-visibility 'canonical)
6395 ;; Fold every list in subtree to top-level items.
6396 (when (eq org-cycle-include-plain-lists 'integrate)
6397 (save-excursion
6398 (org-back-to-heading)
6399 (while (org-list-search-forward (org-item-beginning-re) eos t)
6400 (beginning-of-line 1)
6401 (let* ((struct (org-list-struct))
6402 (prevs (org-list-prevs-alist struct))
6403 (end (org-list-get-bottom-point struct)))
6404 (dolist (e (org-list-get-all-items (point) struct prevs))
6405 (org-list-set-item-visibility e struct 'folded))
6406 (goto-char (if (< end eos) end eos)))))))
6407 (org-unlogged-message "CHILDREN")
6408 (save-excursion
6409 (goto-char eos)
6410 (outline-next-heading)
6411 (when (org-invisible-p) (org-flag-heading nil)))
6412 (setq org-cycle-subtree-status 'children)
6413 (unless (org-before-first-heading-p)
6414 (run-hook-with-args 'org-cycle-hook 'children)))
6415 ((or children-skipped
6416 (and (eq last-command this-command)
6417 (eq org-cycle-subtree-status 'children)))
6418 ;; We just showed the children, or no children are there,
6419 ;; now show everything.
6420 (unless (org-before-first-heading-p)
6421 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6422 (org-flag-region eoh eos nil 'outline)
6423 (org-unlogged-message
6424 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6425 (setq org-cycle-subtree-status 'subtree)
6426 (unless (org-before-first-heading-p)
6427 (run-hook-with-args 'org-cycle-hook 'subtree)))
6429 ;; Default action: hide the subtree.
6430 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6431 (org-flag-region eoh eos t 'outline)
6432 (org-unlogged-message "FOLDED")
6433 (setq org-cycle-subtree-status 'folded)
6434 (unless (org-before-first-heading-p)
6435 (run-hook-with-args 'org-cycle-hook 'folded))))))
6437 ;;;###autoload
6438 (defun org-global-cycle (&optional arg)
6439 "Cycle the global visibility. For details see `org-cycle'.
6440 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6441 With a numeric prefix, show all headlines up to that level."
6442 (interactive "P")
6443 (let ((org-cycle-include-plain-lists
6444 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6445 (cond
6446 ((integerp arg)
6447 (org-show-all '(headings blocks))
6448 (outline-hide-sublevels arg)
6449 (setq org-cycle-global-status 'contents))
6450 ((equal arg '(4))
6451 (org-set-startup-visibility)
6452 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6454 (org-cycle '(4))))))
6456 (defun org-set-startup-visibility ()
6457 "Set the visibility required by startup options and properties."
6458 (cond
6459 ((eq org-startup-folded t)
6460 (org-overview))
6461 ((eq org-startup-folded 'content)
6462 (org-content))
6463 ((or (eq org-startup-folded 'showeverything)
6464 (eq org-startup-folded nil))
6465 (org-show-all)))
6466 (unless (eq org-startup-folded 'showeverything)
6467 (when org-hide-block-startup (org-hide-block-all))
6468 (org-set-visibility-according-to-property)
6469 (org-cycle-hide-archived-subtrees 'all)
6470 (org-cycle-hide-drawers 'all)
6471 (org-cycle-show-empty-lines t)))
6473 (defun org-set-visibility-according-to-property ()
6474 "Switch subtree visibility according to VISIBILITY property."
6475 (interactive)
6476 (let ((regexp (org-re-property "VISIBILITY")))
6477 (org-with-point-at 1
6478 (while (re-search-forward regexp nil t)
6479 (let ((state (match-string 3)))
6480 (if (not (org-at-property-p)) (outline-next-heading)
6481 (save-excursion
6482 (org-back-to-heading t)
6483 (outline-hide-subtree)
6484 (org-reveal)
6485 (pcase state
6486 ("folded"
6487 (outline-hide-subtree))
6488 ("children"
6489 (org-show-hidden-entry)
6490 (org-show-children))
6491 ("content"
6492 (save-excursion
6493 (save-restriction
6494 (org-narrow-to-subtree)
6495 (org-content))))
6496 ((or "all" "showall")
6497 (outline-show-subtree))
6498 (_ nil)))
6499 (org-end-of-subtree)))))))
6501 (defun org-overview ()
6502 "Switch to overview mode, showing only top-level headlines.
6503 This shows all headlines with a level equal or greater than the level
6504 of the first headline in the buffer. This is important, because if the
6505 first headline is not level one, then (hide-sublevels 1) gives confusing
6506 results."
6507 (interactive)
6508 (save-excursion
6509 (let ((level
6510 (save-excursion
6511 (goto-char (point-min))
6512 (when (re-search-forward org-outline-regexp-bol nil t)
6513 (goto-char (match-beginning 0))
6514 (funcall outline-level)))))
6515 (and level (outline-hide-sublevels level)))))
6517 (defun org-content (&optional arg)
6518 "Show all headlines in the buffer, like a table of contents.
6519 With numerical argument N, show content up to level N."
6520 (interactive "P")
6521 (org-overview)
6522 (save-excursion
6523 ;; Visit all headings and show their offspring
6524 (and (integerp arg) (org-overview))
6525 (goto-char (point-max))
6526 (catch 'exit
6527 (while (and (progn (condition-case nil
6528 (outline-previous-visible-heading 1)
6529 (error (goto-char (point-min))))
6531 (looking-at org-outline-regexp))
6532 (if (integerp arg)
6533 (org-show-children (1- arg))
6534 (outline-show-branches))
6535 (when (bobp) (throw 'exit nil))))))
6537 (defun org-optimize-window-after-visibility-change (state)
6538 "Adjust the window after a change in outline visibility.
6539 This function is the default value of the hook `org-cycle-hook'."
6540 (when (get-buffer-window (current-buffer))
6541 (cond
6542 ((eq state 'content) nil)
6543 ((eq state 'all) nil)
6544 ((eq state 'folded) nil)
6545 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6546 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6548 (defun org-clean-visibility-after-subtree-move ()
6549 "Fix visibility issues after moving a subtree."
6550 ;; First, find a reasonable region to look at:
6551 ;; Start two siblings above, end three below
6552 (let* ((beg (save-excursion
6553 (and (org-get-last-sibling)
6554 (org-get-last-sibling))
6555 (point)))
6556 (end (save-excursion
6557 (and (org-get-next-sibling)
6558 (org-get-next-sibling)
6559 (org-get-next-sibling))
6560 (if (org-at-heading-p)
6561 (point-at-eol)
6562 (point))))
6563 (level (looking-at "\\*+"))
6564 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
6565 (save-excursion
6566 (save-restriction
6567 (narrow-to-region beg end)
6568 (when re
6569 ;; Properly fold already folded siblings
6570 (goto-char (point-min))
6571 (while (re-search-forward re nil t)
6572 (when (and (not (org-invisible-p))
6573 (org-invisible-p (line-end-position)))
6574 (outline-hide-entry))))
6575 (org-cycle-hide-drawers 'all)
6576 (org-cycle-show-empty-lines 'overview)))))
6578 (defun org-cycle-show-empty-lines (state)
6579 "Show empty lines above all visible headlines.
6580 The region to be covered depends on STATE when called through
6581 `org-cycle-hook'. Lisp program can use t for STATE to get the
6582 entire buffer covered. Note that an empty line is only shown if there
6583 are at least `org-cycle-separator-lines' empty lines before the headline."
6584 (when (/= org-cycle-separator-lines 0)
6585 (save-excursion
6586 (let* ((n (abs org-cycle-separator-lines))
6587 (re (cond
6588 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6589 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6590 (t (let ((ns (number-to-string (- n 2))))
6591 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6592 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6593 beg end)
6594 (cond
6595 ((memq state '(overview contents t))
6596 (setq beg (point-min) end (point-max)))
6597 ((memq state '(children folded))
6598 (setq beg (point)
6599 end (progn (org-end-of-subtree t t)
6600 (line-beginning-position 2)))))
6601 (when beg
6602 (goto-char beg)
6603 (while (re-search-forward re end t)
6604 (unless (get-char-property (match-end 1) 'invisible)
6605 (let ((e (match-end 1))
6606 (b (if (>= org-cycle-separator-lines 0)
6607 (match-beginning 1)
6608 (save-excursion
6609 (goto-char (match-beginning 0))
6610 (skip-chars-backward " \t\n")
6611 (line-end-position)))))
6612 (org-flag-region b e nil 'outline))))))))
6613 ;; Never hide empty lines at the end of the file.
6614 (save-excursion
6615 (goto-char (point-max))
6616 (outline-previous-heading)
6617 (outline-end-of-heading)
6618 (when (and (looking-at "[ \t\n]+")
6619 (= (match-end 0) (point-max)))
6620 (org-flag-region (point) (match-end 0) nil 'outline))))
6622 ;;;; Reveal point location
6624 (defun org-show-context (&optional key)
6625 "Make sure point and context are visible.
6626 Optional argument KEY, when non-nil, is a symbol. See
6627 `org-show-context-detail' for allowed values and how much is to
6628 be shown."
6629 (org-show-set-visibility
6630 (cond ((symbolp org-show-context-detail) org-show-context-detail)
6631 ((cdr (assq key org-show-context-detail)))
6632 (t (cdr (assq 'default org-show-context-detail))))))
6634 (defun org-show-set-visibility (detail)
6635 "Set visibility around point according to DETAIL.
6636 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
6637 `tree', `canonical' or t. See `org-show-context-detail' for more
6638 information."
6639 ;; Show current heading and possibly its entry, following headline
6640 ;; or all children.
6641 (if (and (org-at-heading-p) (not (eq detail 'local)))
6642 (org-flag-heading nil)
6643 (org-show-entry)
6644 ;; If point is hidden within a drawer or a block, make sure to
6645 ;; expose it.
6646 (dolist (o (overlays-at (point)))
6647 (when (memq (overlay-get o 'invisible)
6648 '(org-hide-block org-hide-drawer outline))
6649 (delete-overlay o)))
6650 (unless (org-before-first-heading-p)
6651 (org-with-limited-levels
6652 (cl-case detail
6653 ((tree canonical t) (org-show-children))
6654 ((nil minimal ancestors))
6655 (t (save-excursion
6656 (outline-next-heading)
6657 (org-flag-heading nil)))))))
6658 ;; Show all siblings.
6659 (when (eq detail 'lineage) (org-show-siblings))
6660 ;; Show ancestors, possibly with their children.
6661 (when (memq detail '(ancestors lineage tree canonical t))
6662 (save-excursion
6663 (while (org-up-heading-safe)
6664 (org-flag-heading nil)
6665 (when (memq detail '(canonical t)) (org-show-entry))
6666 (when (memq detail '(tree canonical t)) (org-show-children))))))
6668 (defvar org-reveal-start-hook nil
6669 "Hook run before revealing a location.")
6671 (defun org-reveal (&optional siblings)
6672 "Show current entry, hierarchy above it, and the following headline.
6674 This can be used to show a consistent set of context around
6675 locations exposed with `org-show-context'.
6677 With optional argument SIBLINGS, on each level of the hierarchy all
6678 siblings are shown. This repairs the tree structure to what it would
6679 look like when opened with hierarchical calls to `org-cycle'.
6681 With a \\[universal-argument] \\[universal-argument] prefix, \
6682 go to the parent and show the entire tree."
6683 (interactive "P")
6684 (run-hooks 'org-reveal-start-hook)
6685 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
6686 ((equal siblings '(16))
6687 (save-excursion
6688 (when (org-up-heading-safe)
6689 (org-show-subtree)
6690 (run-hook-with-args 'org-cycle-hook 'subtree))))
6691 (t (org-show-set-visibility 'lineage))))
6694 ;;; Indirect buffer display of subtrees
6696 (defvar org-indirect-dedicated-frame nil
6697 "This is the frame being used for indirect tree display.")
6698 (defvar org-last-indirect-buffer nil)
6700 (defun org-tree-to-indirect-buffer (&optional arg)
6701 "Create indirect buffer and narrow it to current subtree.
6703 With a numerical prefix ARG, go up to this level and then take that tree.
6704 If ARG is negative, go up that many levels.
6706 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6707 indirect buffer previously made with this command, to avoid proliferation of
6708 indirect buffers. However, when you call the command with a \
6709 `\\[universal-argument]' prefix, or
6710 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
6711 so that you can work with several indirect buffers at the same time. If
6712 `org-indirect-buffer-display' is `dedicated-frame', the \
6713 `\\[universal-argument]' prefix also
6714 requests that a new frame be made for the new buffer, so that the dedicated
6715 frame is not changed."
6716 (interactive "P")
6717 (let ((cbuf (current-buffer))
6718 (cwin (selected-window))
6719 (pos (point))
6720 beg end level heading ibuf)
6721 (save-excursion
6722 (org-back-to-heading t)
6723 (when (numberp arg)
6724 (setq level (org-outline-level))
6725 (when (< arg 0) (setq arg (+ level arg)))
6726 (while (> (setq level (org-outline-level)) arg)
6727 (org-up-heading-safe)))
6728 (setq beg (point)
6729 heading (org-get-heading 'no-tags))
6730 (org-end-of-subtree t t)
6731 (when (org-at-heading-p) (backward-char 1))
6732 (setq end (point)))
6733 (when (and (buffer-live-p org-last-indirect-buffer)
6734 (not (eq org-indirect-buffer-display 'new-frame))
6735 (not arg))
6736 (kill-buffer org-last-indirect-buffer))
6737 (setq ibuf (org-get-indirect-buffer cbuf heading)
6738 org-last-indirect-buffer ibuf)
6739 (cond
6740 ((or (eq org-indirect-buffer-display 'new-frame)
6741 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6742 (select-frame (make-frame))
6743 (delete-other-windows)
6744 (pop-to-buffer-same-window ibuf)
6745 (org-set-frame-title heading))
6746 ((eq org-indirect-buffer-display 'dedicated-frame)
6747 (raise-frame
6748 (select-frame (or (and org-indirect-dedicated-frame
6749 (frame-live-p org-indirect-dedicated-frame)
6750 org-indirect-dedicated-frame)
6751 (setq org-indirect-dedicated-frame (make-frame)))))
6752 (delete-other-windows)
6753 (pop-to-buffer-same-window ibuf)
6754 (org-set-frame-title (concat "Indirect: " heading)))
6755 ((eq org-indirect-buffer-display 'current-window)
6756 (pop-to-buffer-same-window ibuf))
6757 ((eq org-indirect-buffer-display 'other-window)
6758 (pop-to-buffer ibuf))
6759 (t (error "Invalid value")))
6760 (narrow-to-region beg end)
6761 (org-show-all '(headings blocks))
6762 (goto-char pos)
6763 (run-hook-with-args 'org-cycle-hook 'all)
6764 (and (window-live-p cwin) (select-window cwin))))
6766 (defun org-get-indirect-buffer (&optional buffer heading)
6767 (setq buffer (or buffer (current-buffer)))
6768 (let ((n 1) (base (buffer-name buffer)) bname)
6769 (while (buffer-live-p
6770 (get-buffer
6771 (setq bname
6772 (concat base "-"
6773 (if heading (concat heading "-" (number-to-string n))
6774 (number-to-string n))))))
6775 (setq n (1+ n)))
6776 (condition-case nil
6777 (make-indirect-buffer buffer bname 'clone)
6778 (error (make-indirect-buffer buffer bname)))))
6780 (defun org-set-frame-title (title)
6781 "Set the title of the current frame to the string TITLE."
6782 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
6784 ;;;; Structure editing
6786 ;;; Inserting headlines
6788 (defun org--line-empty-p (n)
6789 "Is the Nth next line empty?
6791 Counts the current line as N = 1 and the previous line as N = 0;
6792 see `beginning-of-line'."
6793 (save-excursion
6794 (and (not (bobp))
6795 (or (beginning-of-line n) t)
6796 (save-match-data
6797 (looking-at "[ \t]*$")))))
6799 (defun org-previous-line-empty-p ()
6800 "Is the previous line a blank line?
6801 When NEXT is non-nil, check the next line instead."
6802 (org--line-empty-p 0))
6804 (defun org-next-line-empty-p ()
6805 "Is the previous line a blank line?
6806 When NEXT is non-nil, check the next line instead."
6807 (org--line-empty-p 2))
6809 (defun org--blank-before-heading-p (&optional parent)
6810 "Non-nil when an empty line should precede a new heading here.
6811 When optional argument PARENT is non-nil, consider parent
6812 headline instead of current one."
6813 (pcase (assq 'heading org-blank-before-new-entry)
6814 (`(heading . auto)
6815 (save-excursion
6816 (org-with-limited-levels
6817 (unless (and (org-before-first-heading-p)
6818 (not (outline-next-heading)))
6819 (org-back-to-heading t)
6820 (when parent (org-up-heading-safe))
6821 (cond ((not (bobp))
6822 (org-previous-line-empty-p))
6823 ((outline-next-heading)
6824 (org-previous-line-empty-p))
6825 ;; Ignore trailing spaces on last buffer line.
6826 ((progn (skip-chars-backward " \t") (bolp))
6827 (org-previous-line-empty-p))
6828 (t nil))))))
6829 (`(heading . ,value) value)
6830 (_ nil)))
6832 (defun org-insert-heading (&optional arg invisible-ok top)
6833 "Insert a new heading or an item with the same depth at point.
6835 If point is at the beginning of a heading, insert a new heading
6836 or a new headline above the current one. When at the beginning
6837 of a regular line of text, turn it into a heading.
6839 If point is in the middle of a line, split it and create a new
6840 headline with the text in the current line after point (see
6841 `org-M-RET-may-split-line' on how to modify this behavior). As
6842 a special case, on a headline, splitting can only happen on the
6843 title itself. E.g., this excludes breaking stars or tags.
6845 With a `\\[universal-argument]' prefix, set \
6846 `org-insert-heading-respect-content' to
6847 a non-nil value for the duration of the command. This forces the
6848 insertion of a heading after the current subtree, independently
6849 on the location of point.
6851 With a `\\[universal-argument] \\[universal-argument]' prefix, \
6852 insert the heading at the end of the tree
6853 above the current heading. For example, if point is within a
6854 2nd-level heading, then it will insert a 2nd-level heading at
6855 the end of the 1st-level parent subtree.
6857 When INVISIBLE-OK is set, stop at invisible headlines when going
6858 back. This is important for non-interactive uses of the
6859 command.
6861 When optional argument TOP is non-nil, insert a level 1 heading,
6862 unconditionally."
6863 (interactive "P")
6864 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
6865 (level (org-current-level))
6866 (stars (make-string (if (and level (not top)) level 1) ?*)))
6867 (cond
6868 ((or org-insert-heading-respect-content
6869 (member arg '((4) (16)))
6870 (and (not invisible-ok)
6871 (invisible-p (max (1- (point)) (point-min)))))
6872 ;; Position point at the location of insertion. Make sure we
6873 ;; end up on a visible headline if INVISIBLE-OK is nil.
6874 (org-with-limited-levels
6875 (if (not level) (outline-next-heading) ;before first headline
6876 (org-back-to-heading invisible-ok)
6877 (when (equal arg '(16)) (org-up-heading-safe))
6878 (org-end-of-subtree)))
6879 (unless (bolp) (insert "\n"))
6880 (unless (and blank? (org-previous-line-empty-p))
6881 (org-N-empty-lines-before-current (if blank? 1 0)))
6882 (insert stars " ")
6883 ;; When INVISIBLE-OK is non-nil, ensure newly created headline
6884 ;; is visible.
6885 (unless invisible-ok
6886 (pcase (get-char-property-and-overlay (point) 'invisible)
6887 (`(outline . ,o)
6888 (move-overlay o (overlay-start o) (line-end-position 0)))
6889 (_ nil))))
6890 ;; At a headline...
6891 ((org-at-heading-p)
6892 (cond ((bolp)
6893 (when blank? (save-excursion (insert "\n")))
6894 (save-excursion (insert stars " \n"))
6895 (unless (and blank? (org-previous-line-empty-p))
6896 (org-N-empty-lines-before-current (if blank? 1 0)))
6897 (end-of-line))
6898 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
6899 (org-match-line org-complex-heading-regexp)
6900 (org-pos-in-match-range (point) 4))
6901 ;; Grab the text that should moved to the new headline.
6902 ;; Preserve tags.
6903 (let ((split (delete-and-extract-region (point) (match-end 4))))
6904 (if (looking-at "[ \t]*$") (replace-match "")
6905 (org-align-tags))
6906 (end-of-line)
6907 (when blank? (insert "\n"))
6908 (insert "\n" stars " ")
6909 (when (org-string-nw-p split) (insert split))))
6911 (end-of-line)
6912 (when blank? (insert "\n"))
6913 (insert "\n" stars " "))))
6914 ;; On regular text, turn line into a headline or split, if
6915 ;; appropriate.
6916 ((bolp)
6917 (insert stars " ")
6918 (unless (and blank? (org-previous-line-empty-p))
6919 (org-N-empty-lines-before-current (if blank? 1 0))))
6921 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
6922 (end-of-line))
6923 (insert "\n" stars " ")
6924 (unless (and blank? (org-previous-line-empty-p))
6925 (org-N-empty-lines-before-current (if blank? 1 0))))))
6926 (run-hooks 'org-insert-heading-hook))
6928 (defun org-N-empty-lines-before-current (n)
6929 "Make the number of empty lines before current exactly N.
6930 So this will delete or add empty lines."
6931 (let ((column (current-column)))
6932 (beginning-of-line)
6933 (unless (bobp)
6934 (let ((start (save-excursion
6935 (skip-chars-backward " \r\t\n")
6936 (line-end-position))))
6937 (delete-region start (line-end-position 0))))
6938 (insert (make-string n ?\n))
6939 (move-to-column column)))
6941 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
6942 "Return the heading of the current entry, without the stars.
6943 When NO-TAGS is non-nil, don't include tags.
6944 When NO-TODO is non-nil, don't include TODO keywords.
6945 When NO-PRIORITY is non-nil, don't include priority cookie.
6946 When NO-COMMENT is non-nil, don't include COMMENT string.
6947 Return nil before first heading."
6948 (unless (org-before-first-heading-p)
6949 (save-excursion
6950 (org-back-to-heading t)
6951 (let ((case-fold-search nil))
6952 (looking-at org-complex-heading-regexp)
6953 (let ((todo (and (not no-todo) (match-string 2)))
6954 (priority (and (not no-priority) (match-string 3)))
6955 (headline (pcase (match-string 4)
6956 (`nil "")
6957 ((and (guard no-comment) h)
6958 (replace-regexp-in-string
6959 (eval-when-compile
6960 (format "\\`%s[ \t]+" org-comment-string))
6961 "" h))
6962 (h h)))
6963 (tags (and (not no-tags) (match-string 5))))
6964 (mapconcat #'identity
6965 (delq nil (list todo priority headline tags))
6966 " "))))))
6968 (defun org-heading-components ()
6969 "Return the components of the current heading.
6970 This is a list with the following elements:
6971 - the level as an integer
6972 - the reduced level, different if `org-odd-levels-only' is set.
6973 - the TODO keyword, or nil
6974 - the priority character, like ?A, or nil if no priority is given
6975 - the headline text itself, or the tags string if no headline text
6976 - the tags string, or nil."
6977 (save-excursion
6978 (org-back-to-heading t)
6979 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
6980 (list (length (match-string 1))
6981 (org-reduced-level (length (match-string 1)))
6982 (match-string-no-properties 2)
6983 (and (match-end 3) (aref (match-string 3) 2))
6984 (match-string-no-properties 4)
6985 (match-string-no-properties 5)))))
6987 (defun org-get-entry ()
6988 "Get the entry text, after heading, entire subtree."
6989 (save-excursion
6990 (org-back-to-heading t)
6991 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6993 (defun org-edit-headline (&optional heading)
6994 "Edit the current headline.
6995 Set it to HEADING when provided."
6996 (interactive)
6997 (org-with-wide-buffer
6998 (org-back-to-heading t)
6999 (let ((case-fold-search nil))
7000 (when (looking-at org-complex-heading-regexp)
7001 (let* ((old (match-string-no-properties 4))
7002 (new (save-match-data
7003 (org-trim (or heading (read-string "Edit: " old))))))
7004 (unless (equal old new)
7005 (if old (replace-match new t t nil 4)
7006 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7007 (insert " " new))
7008 (org-align-tags)
7009 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7011 (defun org-insert-heading-after-current ()
7012 "Insert a new heading with same level as current, after current subtree."
7013 (interactive)
7014 (org-back-to-heading)
7015 (org-insert-heading)
7016 (org-move-subtree-down)
7017 (end-of-line 1))
7019 (defun org-insert-heading-respect-content (&optional invisible-ok)
7020 "Insert heading with `org-insert-heading-respect-content' set to t."
7021 (interactive)
7022 (org-insert-heading '(4) invisible-ok))
7024 (defun org-insert-todo-heading-respect-content (&optional force-state)
7025 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7026 (interactive)
7027 (org-insert-todo-heading force-state '(4)))
7029 (defun org-insert-todo-heading (arg &optional force-heading)
7030 "Insert a new heading with the same level and TODO state as current heading.
7032 If the heading has no TODO state, or if the state is DONE, use
7033 the first state (TODO by default). Also with one prefix arg,
7034 force first state. With two prefix args, force inserting at the
7035 end of the parent subtree.
7037 When called at a plain list item, insert a new item with an
7038 unchecked check box."
7039 (interactive "P")
7040 (when (or force-heading (not (org-insert-item 'checkbox)))
7041 (org-insert-heading (or (and (equal arg '(16)) '(16))
7042 force-heading))
7043 (save-excursion
7044 (org-forward-heading-same-level -1)
7045 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7046 (let* ((new-mark-x
7047 (if (or (equal arg '(4))
7048 (not (match-beginning 2))
7049 (member (match-string 2) org-done-keywords))
7050 (car org-todo-keywords-1)
7051 (match-string 2)))
7052 (new-mark
7054 (run-hook-with-args-until-success
7055 'org-todo-get-default-hook new-mark-x nil)
7056 new-mark-x)))
7057 (beginning-of-line 1)
7058 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7059 (if org-treat-insert-todo-heading-as-state-change
7060 (org-todo new-mark)
7061 (insert new-mark " "))))
7062 (when org-provide-todo-statistics
7063 (org-update-parent-todo-statistics))))
7065 (defun org-insert-subheading (arg)
7066 "Insert a new subheading and demote it.
7067 Works for outline headings and for plain lists alike."
7068 (interactive "P")
7069 (org-insert-heading arg)
7070 (cond
7071 ((org-at-heading-p) (org-do-demote))
7072 ((org-at-item-p) (org-indent-item))))
7074 (defun org-insert-todo-subheading (arg)
7075 "Insert a new subheading with TODO keyword or checkbox and demote it.
7076 Works for outline headings and for plain lists alike."
7077 (interactive "P")
7078 (org-insert-todo-heading arg)
7079 (cond
7080 ((org-at-heading-p) (org-do-demote))
7081 ((org-at-item-p) (org-indent-item))))
7083 ;;; Promotion and Demotion
7085 (defvar org-after-demote-entry-hook nil
7086 "Hook run after an entry has been demoted.
7087 The cursor will be at the beginning of the entry.
7088 When a subtree is being demoted, the hook will be called for each node.")
7090 (defvar org-after-promote-entry-hook nil
7091 "Hook run after an entry has been promoted.
7092 The cursor will be at the beginning of the entry.
7093 When a subtree is being promoted, the hook will be called for each node.")
7095 (defun org-promote-subtree ()
7096 "Promote the entire subtree.
7097 See also `org-promote'."
7098 (interactive)
7099 (save-excursion
7100 (org-with-limited-levels (org-map-tree 'org-promote)))
7101 (org-fix-position-after-promote))
7103 (defun org-demote-subtree ()
7104 "Demote the entire subtree.
7105 See `org-demote' and `org-promote'."
7106 (interactive)
7107 (save-excursion
7108 (org-with-limited-levels (org-map-tree 'org-demote)))
7109 (org-fix-position-after-promote))
7111 (defun org-do-promote ()
7112 "Promote the current heading higher up the tree.
7113 If the region is active in `transient-mark-mode', promote all
7114 headings in the region."
7115 (interactive)
7116 (save-excursion
7117 (if (org-region-active-p)
7118 (org-map-region 'org-promote (region-beginning) (region-end))
7119 (org-promote)))
7120 (org-fix-position-after-promote))
7122 (defun org-do-demote ()
7123 "Demote the current heading lower down the tree.
7124 If the region is active in `transient-mark-mode', demote all
7125 headings in the region."
7126 (interactive)
7127 (save-excursion
7128 (if (org-region-active-p)
7129 (org-map-region 'org-demote (region-beginning) (region-end))
7130 (org-demote)))
7131 (org-fix-position-after-promote))
7133 (defun org-fix-position-after-promote ()
7134 "Fix cursor position and indentation after demoting/promoting."
7135 (let ((pos (point)))
7136 (when (save-excursion
7137 (beginning-of-line)
7138 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7139 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7140 (cond ((eobp) (insert " "))
7141 ((eolp) (insert " "))
7142 ((equal (char-after) ?\s) (forward-char 1))))))
7144 (defun org-current-level ()
7145 "Return the level of the current entry, or nil if before the first headline.
7146 The level is the number of stars at the beginning of the
7147 headline. Use `org-reduced-level' to remove the effect of
7148 `org-odd-levels'. Unlike to `org-outline-level', this function
7149 ignores inlinetasks."
7150 (let ((level (org-with-limited-levels (org-outline-level))))
7151 (and (> level 0) level)))
7153 (defun org-get-previous-line-level ()
7154 "Return the outline depth of the last headline before the current line.
7155 Returns 0 for the first headline in the buffer, and nil if before the
7156 first headline."
7157 (and (org-current-level)
7158 (or (and (/= (line-beginning-position) (point-min))
7159 (save-excursion (beginning-of-line 0) (org-current-level)))
7160 0)))
7162 (defun org-reduced-level (l)
7163 "Compute the effective level of a heading.
7164 This takes into account the setting of `org-odd-levels-only'."
7165 (cond
7166 ((zerop l) 0)
7167 (org-odd-levels-only (1+ (floor (/ l 2))))
7168 (t l)))
7170 (defun org-level-increment ()
7171 "Return the number of stars that will be added or removed at a
7172 time to headlines when structure editing, based on the value of
7173 `org-odd-levels-only'."
7174 (if org-odd-levels-only 2 1))
7176 (defun org-get-valid-level (level &optional change)
7177 "Rectify a level change under the influence of `org-odd-levels-only'.
7178 LEVEL is a current level, CHANGE is by how much the level should
7179 be modified. Even if CHANGE is nil, LEVEL may be returned
7180 modified because even level numbers will become the next higher
7181 odd number. Returns values greater than 0."
7182 (if org-odd-levels-only
7183 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7184 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7185 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7186 (max 1 (+ level (or change 0)))))
7188 (defun org-promote ()
7189 "Promote the current heading higher up the tree."
7190 (org-with-wide-buffer
7191 (org-back-to-heading t)
7192 (let* ((after-change-functions (remq 'flyspell-after-change-function
7193 after-change-functions))
7194 (level (save-match-data (funcall outline-level)))
7195 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7196 (diff (abs (- level (length up-head) -1))))
7197 (cond
7198 ((and (= level 1) org-allow-promoting-top-level-subtree)
7199 (replace-match "# " nil t))
7200 ((= level 1)
7201 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7202 (t (replace-match up-head nil t)))
7203 (unless (= level 1)
7204 (when org-auto-align-tags (org-align-tags))
7205 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7206 (run-hooks 'org-after-promote-entry-hook))))
7208 (defun org-demote ()
7209 "Demote the current heading lower down the tree."
7210 (org-with-wide-buffer
7211 (org-back-to-heading t)
7212 (let* ((after-change-functions (remq 'flyspell-after-change-function
7213 after-change-functions))
7214 (level (save-match-data (funcall outline-level)))
7215 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7216 (diff (abs (- level (length down-head) -1))))
7217 (replace-match down-head nil t)
7218 (when org-auto-align-tags (org-align-tags))
7219 (when org-adapt-indentation (org-fixup-indentation diff))
7220 (run-hooks 'org-after-demote-entry-hook))))
7222 (defun org-cycle-level ()
7223 "Cycle the level of an empty headline through possible states.
7224 This goes first to child, then to parent, level, then up the hierarchy.
7225 After top level, it switches back to sibling level."
7226 (interactive)
7227 (let ((org-adapt-indentation nil))
7228 (when (org-point-at-end-of-empty-headline)
7229 (setq this-command 'org-cycle-level) ; Only needed for caching
7230 (let ((cur-level (org-current-level))
7231 (prev-level (org-get-previous-line-level)))
7232 (cond
7233 ;; If first headline in file, promote to top-level.
7234 ((= prev-level 0)
7235 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7236 do (org-do-promote)))
7237 ;; If same level as prev, demote one.
7238 ((= prev-level cur-level)
7239 (org-do-demote))
7240 ;; If parent is top-level, promote to top level if not already.
7241 ((= prev-level 1)
7242 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7243 do (org-do-promote)))
7244 ;; If top-level, return to prev-level.
7245 ((= cur-level 1)
7246 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7247 do (org-do-demote)))
7248 ;; If less than prev-level, promote one.
7249 ((< cur-level prev-level)
7250 (org-do-promote))
7251 ;; If deeper than prev-level, promote until higher than
7252 ;; prev-level.
7253 ((> cur-level prev-level)
7254 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7255 do (org-do-promote))))
7256 t))))
7258 (defun org-map-tree (fun)
7259 "Call FUN for every heading underneath the current one."
7260 (org-back-to-heading t)
7261 (let ((level (funcall outline-level)))
7262 (save-excursion
7263 (funcall fun)
7264 (while (and (progn
7265 (outline-next-heading)
7266 (> (funcall outline-level) level))
7267 (not (eobp)))
7268 (funcall fun)))))
7270 (defun org-map-region (fun beg end)
7271 "Call FUN for every heading between BEG and END."
7272 (let ((org-ignore-region t))
7273 (save-excursion
7274 (setq end (copy-marker end))
7275 (goto-char beg)
7276 (when (and (re-search-forward org-outline-regexp-bol nil t)
7277 (< (point) end))
7278 (funcall fun))
7279 (while (and (progn
7280 (outline-next-heading)
7281 (< (point) end))
7282 (not (eobp)))
7283 (funcall fun)))))
7285 (defun org-fixup-indentation (diff)
7286 "Change the indentation in the current entry by DIFF.
7288 DIFF is an integer. Indentation is done according to the
7289 following rules:
7291 - Planning information and property drawers are always indented
7292 according to the new level of the headline;
7294 - Footnote definitions and their contents are ignored;
7296 - Inlinetasks' boundaries are not shifted;
7298 - Empty lines are ignored;
7300 - Other lines' indentation are shifted by DIFF columns, unless
7301 it would introduce a structural change in the document, in
7302 which case no shifting is done at all.
7304 Assume point is at a heading or an inlinetask beginning."
7305 (org-with-wide-buffer
7306 (narrow-to-region (line-beginning-position)
7307 (save-excursion
7308 (if (org-with-limited-levels (org-at-heading-p))
7309 (org-with-limited-levels (outline-next-heading))
7310 (org-inlinetask-goto-end))
7311 (point)))
7312 (forward-line)
7313 ;; Indent properly planning info and property drawer.
7314 (when (looking-at-p org-planning-line-re)
7315 (org-indent-line)
7316 (forward-line))
7317 (when (looking-at org-property-drawer-re)
7318 (goto-char (match-end 0))
7319 (forward-line)
7320 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7321 (catch 'no-shift
7322 (when (zerop diff) (throw 'no-shift nil))
7323 ;; If DIFF is negative, first check if a shift is possible at all
7324 ;; (e.g., it doesn't break structure). This can only happen if
7325 ;; some contents are not properly indented.
7326 (let ((case-fold-search t))
7327 (when (< diff 0)
7328 (let ((diff (- diff))
7329 (forbidden-re (concat org-outline-regexp
7330 "\\|"
7331 (substring org-footnote-definition-re 1))))
7332 (save-excursion
7333 (while (not (eobp))
7334 (cond
7335 ((looking-at-p "[ \t]*$") (forward-line))
7336 ((and (looking-at-p org-footnote-definition-re)
7337 (let ((e (org-element-at-point)))
7338 (and (eq (org-element-type e) 'footnote-definition)
7339 (goto-char (org-element-property :end e))))))
7340 ((looking-at-p org-outline-regexp) (forward-line))
7341 ;; Give up if shifting would move before column 0 or
7342 ;; if it would introduce a headline or a footnote
7343 ;; definition.
7345 (skip-chars-forward " \t")
7346 (let ((ind (current-column)))
7347 (when (or (< ind diff)
7348 (and (= ind diff) (looking-at-p forbidden-re)))
7349 (throw 'no-shift nil)))
7350 ;; Ignore contents of example blocks and source
7351 ;; blocks if their indentation is meant to be
7352 ;; preserved. Jump to block's closing line.
7353 (beginning-of-line)
7354 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
7355 (let ((e (org-element-at-point)))
7356 (and (memq (org-element-type e)
7357 '(example-block src-block))
7358 (or org-src-preserve-indentation
7359 (org-element-property :preserve-indent e))
7360 (goto-char (org-element-property :end e))
7361 (progn (skip-chars-backward " \r\t\n")
7362 (beginning-of-line)
7363 t))))
7364 (forward-line))))))))
7365 ;; Shift lines but footnote definitions, inlinetasks boundaries
7366 ;; by DIFF. Also skip contents of source or example blocks
7367 ;; when indentation is meant to be preserved.
7368 (while (not (eobp))
7369 (cond
7370 ((and (looking-at-p org-footnote-definition-re)
7371 (let ((e (org-element-at-point)))
7372 (and (eq (org-element-type e) 'footnote-definition)
7373 (goto-char (org-element-property :end e))))))
7374 ((looking-at-p org-outline-regexp) (forward-line))
7375 ((looking-at-p "[ \t]*$") (forward-line))
7377 (indent-line-to (+ (current-indentation) diff))
7378 (beginning-of-line)
7379 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
7380 (let ((e (org-element-at-point)))
7381 (and (memq (org-element-type e)
7382 '(example-block src-block))
7383 (or org-src-preserve-indentation
7384 (org-element-property :preserve-indent e))
7385 (goto-char (org-element-property :end e))
7386 (progn (skip-chars-backward " \r\t\n")
7387 (beginning-of-line)
7388 t))))
7389 (forward-line)))))))))
7391 (defun org-convert-to-odd-levels ()
7392 "Convert an Org file with all levels allowed to one with odd levels.
7393 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7394 level 5 etc."
7395 (interactive)
7396 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7397 (let ((outline-level 'org-outline-level)
7398 (org-odd-levels-only nil) n)
7399 (save-excursion
7400 (goto-char (point-min))
7401 (while (re-search-forward "^\\*\\*+ " nil t)
7402 (setq n (- (length (match-string 0)) 2))
7403 (while (>= (setq n (1- n)) 0)
7404 (org-demote))
7405 (end-of-line 1))))))
7407 (defun org-convert-to-oddeven-levels ()
7408 "Convert an Org file with only odd levels to one with odd/even levels.
7409 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7410 file contains a section with an even level, conversion would
7411 destroy the structure of the file. An error is signaled in this
7412 case."
7413 (interactive)
7414 (goto-char (point-min))
7415 ;; First check if there are no even levels
7416 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7417 (org-show-set-visibility 'canonical)
7418 (error "Not all levels are odd in this file. Conversion not possible"))
7419 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7420 (let ((outline-regexp org-outline-regexp)
7421 (outline-level 'org-outline-level)
7422 (org-odd-levels-only nil) n)
7423 (save-excursion
7424 (goto-char (point-min))
7425 (while (re-search-forward "^\\*\\*+ " nil t)
7426 (setq n (/ (1- (length (match-string 0))) 2))
7427 (while (>= (setq n (1- n)) 0)
7428 (org-promote))
7429 (end-of-line 1))))))
7431 (defun org-tr-level (n)
7432 "Make N odd if required."
7433 (if org-odd-levels-only (1+ (/ n 2)) n))
7435 ;;; Vertical tree motion, cutting and pasting of subtrees
7437 (defun org-move-subtree-up (&optional arg)
7438 "Move the current subtree up past ARG headlines of the same level."
7439 (interactive "p")
7440 (org-move-subtree-down (- (prefix-numeric-value arg))))
7442 (defun org-move-subtree-down (&optional arg)
7443 "Move the current subtree down past ARG headlines of the same level."
7444 (interactive "p")
7445 (setq arg (prefix-numeric-value arg))
7446 (org-preserve-local-variables
7447 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7448 'org-get-last-sibling))
7449 (ins-point (make-marker))
7450 (cnt (abs arg))
7451 (col (current-column))
7452 beg end txt folded)
7453 ;; Select the tree
7454 (org-back-to-heading)
7455 (setq beg (point))
7456 (save-match-data
7457 (save-excursion (outline-end-of-heading)
7458 (setq folded (org-invisible-p)))
7459 (progn (org-end-of-subtree nil t)
7460 (unless (eobp) (backward-char))))
7461 (outline-next-heading)
7462 (setq end (point))
7463 (goto-char beg)
7464 ;; Find insertion point, with error handling
7465 (while (> cnt 0)
7466 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
7467 (goto-char beg)
7468 (user-error "Cannot move past superior level or buffer limit"))
7469 (setq cnt (1- cnt)))
7470 (when (> arg 0)
7471 ;; Moving forward - still need to move over subtree
7472 (org-end-of-subtree t t)
7473 (save-excursion
7474 (org-back-over-empty-lines)
7475 (or (bolp) (newline))))
7476 (move-marker ins-point (point))
7477 (setq txt (buffer-substring beg end))
7478 (org-save-markers-in-region beg end)
7479 (delete-region beg end)
7480 (org-remove-empty-overlays-at beg)
7481 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
7482 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
7483 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7484 (let ((bbb (point)))
7485 (insert-before-markers txt)
7486 (org-reinstall-markers-in-region bbb)
7487 (move-marker ins-point bbb))
7488 (or (bolp) (insert "\n"))
7489 (goto-char ins-point)
7490 (org-skip-whitespace)
7491 (move-marker ins-point nil)
7492 (if folded
7493 (outline-hide-subtree)
7494 (org-show-entry)
7495 (org-show-children))
7496 (org-clean-visibility-after-subtree-move)
7497 ;; move back to the initial column we were at
7498 (move-to-column col))))
7500 (defvar org-subtree-clip ""
7501 "Clipboard for cut and paste of subtrees.
7502 This is actually only a copy of the kill, because we use the normal kill
7503 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7505 (defvar org-subtree-clip-folded nil
7506 "Was the last copied subtree folded?
7507 This is used to fold the tree back after pasting.")
7509 (defun org-cut-subtree (&optional n)
7510 "Cut the current subtree into the clipboard.
7511 With prefix arg N, cut this many sequential subtrees.
7512 This is a short-hand for marking the subtree and then cutting it."
7513 (interactive "p")
7514 (org-copy-subtree n 'cut))
7516 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7517 "Copy the current subtree into the clipboard.
7518 With prefix arg N, copy this many sequential subtrees.
7519 This is a short-hand for marking the subtree and then copying it.
7520 If CUT is non-nil, actually cut the subtree.
7521 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7522 of some markers in the region, even if CUT is non-nil. This is
7523 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7524 (interactive "p")
7525 (org-preserve-local-variables
7526 (let (beg end folded (beg0 (point)))
7527 (if (called-interactively-p 'any)
7528 (org-back-to-heading nil) ; take what looks like a subtree
7529 (org-back-to-heading t)) ; take what is really there
7530 (setq beg (point))
7531 (skip-chars-forward " \t\r\n")
7532 (save-match-data
7533 (if nosubtrees
7534 (outline-next-heading)
7535 (save-excursion (outline-end-of-heading)
7536 (setq folded (org-invisible-p)))
7537 (ignore-errors (org-forward-heading-same-level (1- n) t))
7538 (org-end-of-subtree t t)))
7539 ;; Include the end of an inlinetask
7540 (when (and (featurep 'org-inlinetask)
7541 (looking-at-p (concat (org-inlinetask-outline-regexp)
7542 "END[ \t]*$")))
7543 (end-of-line))
7544 (setq end (point))
7545 (goto-char beg0)
7546 (when (> end beg)
7547 (setq org-subtree-clip-folded folded)
7548 (when (or cut force-store-markers)
7549 (org-save-markers-in-region beg end))
7550 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7551 (setq org-subtree-clip (current-kill 0))
7552 (message "%s: Subtree(s) with %d characters"
7553 (if cut "Cut" "Copied")
7554 (length org-subtree-clip))))))
7556 (defun org-paste-subtree (&optional level tree for-yank remove)
7557 "Paste the clipboard as a subtree, with modification of headline level.
7559 The entire subtree is promoted or demoted in order to match a new headline
7560 level.
7562 If the cursor is at the beginning of a headline, the same level as
7563 that headline is used to paste the tree.
7565 If not, the new level is derived from the *visible* headings
7566 before and after the insertion point, and taken to be the inferior headline
7567 level of the two. So if the previous visible heading is level 3 and the
7568 next is level 4 (or vice versa), level 4 will be used for insertion.
7569 This makes sure that the subtree remains an independent subtree and does
7570 not swallow low level entries.
7572 You can also force a different level, either by using a numeric prefix
7573 argument, or by inserting the heading marker by hand. For example, if the
7574 cursor is after \"*****\", then the tree will be shifted to level 5.
7576 If optional TREE is given, use this text instead of the kill ring.
7578 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7579 move back over whitespace before inserting, and move point to the end of
7580 the inserted text when done.
7582 When REMOVE is non-nil, remove the subtree from the clipboard."
7583 (interactive "P")
7584 (setq tree (or tree (and kill-ring (current-kill 0))))
7585 (unless (org-kill-is-subtree-p tree)
7586 (user-error
7587 (substitute-command-keys
7588 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
7589 (org-with-limited-levels
7590 (let* ((visp (not (org-invisible-p)))
7591 (txt tree)
7592 (old-level (if (string-match org-outline-regexp-bol txt)
7593 (- (match-end 0) (match-beginning 0) 1)
7594 -1))
7595 (force-level
7596 (cond
7597 (level (prefix-numeric-value level))
7598 ;; When point is after the stars in an otherwise empty
7599 ;; headline, use the number of stars as the forced level.
7600 ((and (org-match-line "^\\*+[ \t]*$")
7601 (not (eq ?* (char-after))))
7602 (org-outline-level))
7603 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
7604 (previous-level
7605 (save-excursion
7606 (org-previous-visible-heading 1)
7607 (if (org-at-heading-p) (org-outline-level) 1)))
7608 (next-level
7609 (save-excursion
7610 (if (org-at-heading-p) (org-outline-level)
7611 (org-next-visible-heading 1)
7612 (if (org-at-heading-p) (org-outline-level) 1))))
7613 (new-level (or force-level (max previous-level next-level)))
7614 (shift (if (or (= old-level -1)
7615 (= new-level -1)
7616 (= old-level new-level))
7618 (- new-level old-level)))
7619 (delta (if (> shift 0) -1 1))
7620 (func (if (> shift 0) #'org-demote #'org-promote))
7621 (org-odd-levels-only nil)
7622 beg end newend)
7623 ;; Remove the forced level indicator.
7624 (when (and force-level (not level))
7625 (delete-region (line-beginning-position) (point)))
7626 ;; Paste before the next visible heading or at end of buffer,
7627 ;; unless point is at the beginning of a headline.
7628 (unless (and (bolp) (org-at-heading-p))
7629 (org-next-visible-heading 1)
7630 (unless (bolp) (insert "\n")))
7631 (setq beg (point))
7632 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7633 (insert-before-markers txt)
7634 (unless (string-suffix-p "\n" txt) (insert "\n"))
7635 (setq newend (point))
7636 (org-reinstall-markers-in-region beg)
7637 (setq end (point))
7638 (goto-char beg)
7639 (skip-chars-forward " \t\n\r")
7640 (setq beg (point))
7641 (when (and (org-invisible-p) visp)
7642 (save-excursion (outline-show-heading)))
7643 ;; Shift if necessary.
7644 (unless (= shift 0)
7645 (save-restriction
7646 (narrow-to-region beg end)
7647 (while (not (= shift 0))
7648 (org-map-region func (point-min) (point-max))
7649 (setq shift (+ delta shift)))
7650 (goto-char (point-min))
7651 (setq newend (point-max))))
7652 (when (or for-yank (called-interactively-p 'interactive))
7653 (message "Clipboard pasted as level %d subtree" new-level))
7654 (when (and (not for-yank) ; in this case, org-yank will decide about folding
7655 kill-ring
7656 (equal org-subtree-clip (current-kill 0))
7657 org-subtree-clip-folded)
7658 ;; The tree was folded before it was killed/copied
7659 (outline-hide-subtree))
7660 (when for-yank (goto-char newend))
7661 (when remove (pop kill-ring)))))
7663 (defun org-kill-is-subtree-p (&optional txt)
7664 "Check if the current kill is an outline subtree, or a set of trees.
7665 Returns nil if kill does not start with a headline, or if the first
7666 headline level is not the largest headline level in the tree.
7667 So this will actually accept several entries of equal levels as well,
7668 which is OK for `org-paste-subtree'.
7669 If optional TXT is given, check this string instead of the current kill."
7670 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7671 (re (org-get-limited-outline-regexp))
7672 (^re (concat "^" re))
7673 (start-level (and kill
7674 (string-match
7675 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7676 kill)
7677 (- (match-end 2) (match-beginning 2) 1)))
7678 (start (1+ (or (match-beginning 2) -1))))
7679 (if (not start-level)
7680 (progn
7681 nil) ;; does not even start with a heading
7682 (catch 'exit
7683 (while (setq start (string-match ^re kill (1+ start)))
7684 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7685 (throw 'exit nil)))
7686 t))))
7688 (defvar org-markers-to-move nil
7689 "Markers that should be moved with a cut-and-paste operation.
7690 Those markers are stored together with their positions relative to
7691 the start of the region.")
7693 (defun org-save-markers-in-region (beg end)
7694 "Check markers in region.
7695 If these markers are between BEG and END, record their position relative
7696 to BEG, so that after moving the block of text, we can put the markers back
7697 into place.
7698 This function gets called just before an entry or tree gets cut from the
7699 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7700 called immediately, to move the markers with the entries."
7701 (setq org-markers-to-move nil)
7702 (when (featurep 'org-clock)
7703 (org-clock-save-markers-for-cut-and-paste beg end))
7704 (when (featurep 'org-agenda)
7705 (org-agenda-save-markers-for-cut-and-paste beg end)))
7707 (defun org-check-and-save-marker (marker beg end)
7708 "Check if MARKER is between BEG and END.
7709 If yes, remember the marker and the distance to BEG."
7710 (when (and (marker-buffer marker)
7711 (equal (marker-buffer marker) (current-buffer))
7712 (>= marker beg) (< marker end))
7713 (push (cons marker (- marker beg)) org-markers-to-move)))
7715 (defun org-reinstall-markers-in-region (beg)
7716 "Move all remembered markers to their position relative to BEG."
7717 (dolist (x org-markers-to-move)
7718 (move-marker (car x) (+ beg (cdr x))))
7719 (setq org-markers-to-move nil))
7721 (defun org-narrow-to-subtree ()
7722 "Narrow buffer to the current subtree."
7723 (interactive)
7724 (save-excursion
7725 (save-match-data
7726 (org-with-limited-levels
7727 (narrow-to-region
7728 (progn (org-back-to-heading t) (point))
7729 (progn (org-end-of-subtree t t)
7730 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7731 (point)))))))
7733 (defun org-toggle-narrow-to-subtree ()
7734 "Narrow to the subtree at point or widen a narrowed buffer."
7735 (interactive)
7736 (if (buffer-narrowed-p)
7737 (widen)
7738 (org-narrow-to-subtree)))
7740 (defun org-narrow-to-block ()
7741 "Narrow buffer to the current block."
7742 (interactive)
7743 (let* ((case-fold-search t)
7744 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7745 "^[ \t]*#\\+end_.*")))
7746 (if blockp
7747 (narrow-to-region (car blockp) (cdr blockp))
7748 (user-error "Not in a block"))))
7750 (defun org-clone-subtree-with-time-shift (n &optional shift)
7751 "Clone the task (subtree) at point N times.
7752 The clones will be inserted as siblings.
7754 In interactive use, the user will be prompted for the number of
7755 clones to be produced. If the entry has a timestamp, the user
7756 will also be prompted for a time shift, which may be a repeater
7757 as used in time stamps, for example `+3d'. To disable this,
7758 you can call the function with a universal prefix argument.
7760 When a valid repeater is given and the entry contains any time
7761 stamps, the clones will become a sequence in time, with time
7762 stamps in the subtree shifted for each clone produced. If SHIFT
7763 is nil or the empty string, time stamps will be left alone. The
7764 ID property of the original subtree is removed.
7766 In each clone, all the CLOCK entries will be removed. This
7767 prevents Org from considering that the clocked times overlap.
7769 If the original subtree did contain time stamps with a repeater,
7770 the following will happen:
7771 - the repeater will be removed in each clone
7772 - an additional clone will be produced, with the current, unshifted
7773 date(s) in the entry.
7774 - the original entry will be placed *after* all the clones, with
7775 repeater intact.
7776 - the start days in the repeater in the original entry will be shifted
7777 to past the last clone.
7778 In this way you can spell out a number of instances of a repeating task,
7779 and still retain the repeater to cover future instances of the task.
7781 As described above, N+1 clones are produced when the original
7782 subtree has a repeater. Setting N to 0, then, can be used to
7783 remove the repeater from a subtree and create a shifted clone
7784 with the original repeater."
7785 (interactive "nNumber of clones to produce: ")
7786 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
7787 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
7788 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
7789 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
7790 (shift
7791 (or shift
7792 (if (and (not (equal current-prefix-arg '(4)))
7793 (save-excursion
7794 (goto-char beg)
7795 (re-search-forward org-ts-regexp-both end-of-tree t)))
7796 (read-from-minibuffer
7797 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
7798 ""))) ;No time shift
7799 (doshift
7800 (and (org-string-nw-p shift)
7801 (or (string-match "\\`[ \t]*\\([\\+\\-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7802 shift)
7803 (user-error "Invalid shift specification %s" shift)))))
7804 (goto-char end-of-tree)
7805 (unless (bolp) (insert "\n"))
7806 (let* ((end (point))
7807 (template (buffer-substring beg end))
7808 (shift-n (and doshift (string-to-number (match-string 1 shift))))
7809 (shift-what (pcase (and doshift (match-string 2 shift))
7810 (`nil nil)
7811 ("d" 'day)
7812 ("w" (setq shift-n (* 7 shift-n)) 'day)
7813 ("m" 'month)
7814 ("y" 'year)
7815 (_ (error "Unsupported time unit"))))
7816 (nmin 1)
7817 (nmax n)
7818 (n-no-remove -1)
7819 (idprop (org-entry-get nil "ID")))
7820 (when (and doshift
7821 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
7822 template))
7823 (delete-region beg end)
7824 (setq end beg)
7825 (setq nmin 0)
7826 (setq nmax (1+ nmax))
7827 (setq n-no-remove nmax))
7828 (goto-char end)
7829 (cl-loop for n from nmin to nmax do
7830 (insert
7831 ;; Prepare clone.
7832 (with-temp-buffer
7833 (insert template)
7834 (org-mode)
7835 (goto-char (point-min))
7836 (org-show-subtree)
7837 (and idprop (if org-clone-delete-id
7838 (org-entry-delete nil "ID")
7839 (org-id-get-create t)))
7840 (unless (= n 0)
7841 (while (re-search-forward org-clock-line-re nil t)
7842 (delete-region (line-beginning-position)
7843 (line-beginning-position 2)))
7844 (goto-char (point-min))
7845 (while (re-search-forward org-drawer-regexp nil t)
7846 (org-remove-empty-drawer-at (point))))
7847 (goto-char (point-min))
7848 (when doshift
7849 (while (re-search-forward org-ts-regexp-both nil t)
7850 (org-timestamp-change (* n shift-n) shift-what))
7851 (unless (= n n-no-remove)
7852 (goto-char (point-min))
7853 (while (re-search-forward org-ts-regexp nil t)
7854 (save-excursion
7855 (goto-char (match-beginning 0))
7856 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7857 (delete-region (match-beginning 1) (match-end 1)))))))
7858 (buffer-string)))))
7859 (goto-char beg)))
7861 ;;; Outline Sorting
7863 (defun org-sort (&optional with-case)
7864 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7865 Optional argument WITH-CASE means sort case-sensitively."
7866 (interactive "P")
7867 (org-call-with-arg
7868 (cond ((org-at-table-p) #'org-table-sort-lines)
7869 ((org-at-item-p) #'org-sort-list)
7870 (t #'org-sort-entries))
7871 with-case))
7873 (defun org-sort-remove-invisible (s)
7874 "Remove invisible part of links and emphasis markers from string S."
7875 (remove-text-properties 0 (length s) org-rm-props s)
7876 (replace-regexp-in-string
7877 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
7878 (replace-regexp-in-string
7879 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
7880 (org-link-display-format s)
7881 t t) t t))
7883 (defvar org-priority-regexp) ; defined later in the file
7885 (defvar org-after-sorting-entries-or-items-hook nil
7886 "Hook that is run after a bunch of entries or items have been sorted.
7887 When children are sorted, the cursor is in the parent line when this
7888 hook gets called. When a region or a plain list is sorted, the cursor
7889 will be in the first entry of the sorted region/list.")
7891 (defun org-sort-entries
7892 (&optional with-case sorting-type getkey-func compare-func property
7893 interactive?)
7894 "Sort entries on a certain level of an outline tree.
7895 If there is an active region, the entries in the region are sorted.
7896 Else, if the cursor is before the first entry, sort the top-level items.
7897 Else, the children of the entry at point are sorted.
7899 Sorting can be alphabetically, numerically, by date/time as given by
7900 a time stamp, by a property, by priority order, or by a custom function.
7902 The command prompts for the sorting type unless it has been given to the
7903 function through the SORTING-TYPE argument, which needs to be a character,
7904 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
7905 the precise meaning of each character:
7907 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7908 c By creation time, which is assumed to be the first inactive time stamp
7909 at the beginning of a line.
7910 d By deadline date/time.
7911 k By clocking time.
7912 n Numerically, by converting the beginning of the entry/item to a number.
7913 o By order of TODO keywords.
7914 p By priority according to the cookie.
7915 r By the value of a property.
7916 s By scheduled date/time.
7917 t By date/time, either the first active time stamp in the entry, or, if
7918 none exist, by the first inactive one.
7920 Capital letters will reverse the sort order.
7922 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7923 called with point at the beginning of the record. It must return a
7924 value that is compatible with COMPARE-FUNC, the function used to
7925 compare entries.
7927 Comparing entries ignores case by default. However, with an optional argument
7928 WITH-CASE, the sorting considers case as well.
7930 Sorting is done against the visible part of the headlines, it ignores hidden
7931 links.
7933 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
7935 A non-nil value for INTERACTIVE? is used to signal that this
7936 function is being called interactively."
7937 (interactive (list current-prefix-arg nil nil nil nil t))
7938 (let ((case-func (if with-case 'identity 'downcase))
7939 start beg end stars re re2
7940 txt what tmp)
7941 ;; Find beginning and end of region to sort
7942 (cond
7943 ((org-region-active-p)
7944 ;; we will sort the region
7945 (setq end (region-end)
7946 what "region")
7947 (goto-char (region-beginning))
7948 (unless (org-at-heading-p) (outline-next-heading))
7949 (setq start (point)))
7950 ((or (org-at-heading-p)
7951 (ignore-errors (progn (org-back-to-heading) t)))
7952 ;; we will sort the children of the current headline
7953 (org-back-to-heading)
7954 (setq start (point)
7955 end (progn (org-end-of-subtree t t)
7956 (or (bolp) (insert "\n"))
7957 (when (>= (org-back-over-empty-lines) 1)
7958 (forward-line 1))
7959 (point))
7960 what "children")
7961 (goto-char start)
7962 (outline-show-subtree)
7963 (outline-next-heading))
7965 ;; we will sort the top-level entries in this file
7966 (goto-char (point-min))
7967 (or (org-at-heading-p) (outline-next-heading))
7968 (setq start (point))
7969 (goto-char (point-max))
7970 (beginning-of-line 1)
7971 (when (looking-at ".*?\\S-")
7972 ;; File ends in a non-white line
7973 (end-of-line 1)
7974 (insert "\n"))
7975 (setq end (point-max))
7976 (setq what "top-level")
7977 (goto-char start)
7978 (org-show-all '(headings blocks))))
7980 (setq beg (point))
7981 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
7983 (looking-at "\\(\\*+\\)")
7984 (setq stars (match-string 1)
7985 re (concat "^" (regexp-quote stars) " +")
7986 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7987 txt (buffer-substring beg end))
7988 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
7989 (when (and (not (equal stars "*")) (string-match re2 txt))
7990 (user-error "Region to sort contains a level above the first entry"))
7992 (unless sorting-type
7993 (message
7994 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7995 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
7996 A/N/P/R/O/F/T/S/D/C/K means reversed:"
7997 what)
7998 (setq sorting-type (read-char-exclusive)))
8000 (unless getkey-func
8001 (and (= (downcase sorting-type) ?f)
8002 (setq getkey-func
8003 (or (and interactive?
8004 (org-read-function
8005 "Function for extracting keys: "))
8006 (error "Missing key extractor")))))
8008 (and (= (downcase sorting-type) ?r)
8009 (not property)
8010 (setq property
8011 (completing-read "Property: "
8012 (mapcar #'list (org-buffer-property-keys t))
8013 nil t)))
8015 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8016 (message "Sorting entries...")
8018 (save-restriction
8019 (narrow-to-region start end)
8020 (let ((restore-clock?
8021 ;; The clock marker is lost when using `sort-subr'; mark
8022 ;; the clock with temporary `:org-clock-marker-backup'
8023 ;; text property.
8024 (when (and (eq (org-clock-is-active) (current-buffer))
8025 (<= start (marker-position org-clock-marker))
8026 (>= end (marker-position org-clock-marker)))
8027 (with-silent-modifications
8028 (put-text-property (1- org-clock-marker) org-clock-marker
8029 :org-clock-marker-backup t))
8031 (dcst (downcase sorting-type))
8032 (case-fold-search nil)
8033 (now (current-time)))
8034 (org-preserve-local-variables
8035 (sort-subr
8036 (/= dcst sorting-type)
8037 ;; This function moves to the beginning character of the
8038 ;; "record" to be sorted.
8039 (lambda nil
8040 (if (re-search-forward re nil t)
8041 (goto-char (match-beginning 0))
8042 (goto-char (point-max))))
8043 ;; This function moves to the last character of the "record" being
8044 ;; sorted.
8045 (lambda nil
8046 (save-match-data
8047 (condition-case nil
8048 (outline-forward-same-level 1)
8049 (error
8050 (goto-char (point-max))))))
8051 ;; This function returns the value that gets sorted against.
8052 (lambda ()
8053 (cond
8054 ((= dcst ?n)
8055 (string-to-number
8056 (org-sort-remove-invisible (org-get-heading t t t t))))
8057 ((= dcst ?a)
8058 (funcall case-func
8059 (org-sort-remove-invisible (org-get-heading t t t t))))
8060 ((= dcst ?k)
8061 (or (get-text-property (point) :org-clock-minutes) 0))
8062 ((= dcst ?t)
8063 (let ((end (save-excursion (outline-next-heading) (point))))
8064 (if (or (re-search-forward org-ts-regexp end t)
8065 (re-search-forward org-ts-regexp-both end t))
8066 (org-time-string-to-seconds (match-string 0))
8067 (float-time now))))
8068 ((= dcst ?c)
8069 (let ((end (save-excursion (outline-next-heading) (point))))
8070 (if (re-search-forward
8071 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8072 end t)
8073 (org-time-string-to-seconds (match-string 0))
8074 (float-time now))))
8075 ((= dcst ?s)
8076 (let ((end (save-excursion (outline-next-heading) (point))))
8077 (if (re-search-forward org-scheduled-time-regexp end t)
8078 (org-time-string-to-seconds (match-string 1))
8079 (float-time now))))
8080 ((= dcst ?d)
8081 (let ((end (save-excursion (outline-next-heading) (point))))
8082 (if (re-search-forward org-deadline-time-regexp end t)
8083 (org-time-string-to-seconds (match-string 1))
8084 (float-time now))))
8085 ((= dcst ?p)
8086 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8087 (string-to-char (match-string 2))
8088 org-default-priority))
8089 ((= dcst ?r)
8090 (or (org-entry-get nil property) ""))
8091 ((= dcst ?o)
8092 (when (looking-at org-complex-heading-regexp)
8093 (let* ((m (match-string 2))
8094 (s (if (member m org-done-keywords) '- '+)))
8095 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8096 ((= dcst ?f)
8097 (if getkey-func
8098 (progn
8099 (setq tmp (funcall getkey-func))
8100 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8101 tmp)
8102 (error "Invalid key function `%s'" getkey-func)))
8103 (t (error "Invalid sorting type `%c'" sorting-type))))
8105 (cond
8106 ((= dcst ?a) 'org-string-collate-lessp)
8107 ((= dcst ?f)
8108 (or compare-func
8109 (and interactive?
8110 (org-read-function
8111 (concat "Function for comparing keys "
8112 "(empty for default `sort-subr' predicate): ")
8113 'allow-empty))))
8114 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8115 (when restore-clock?
8116 (move-marker org-clock-marker
8117 (1+ (next-single-property-change
8118 start :org-clock-marker-backup)))
8119 (remove-text-properties (1- org-clock-marker) org-clock-marker
8120 '(:org-clock-marker-backup t)))))
8121 (run-hooks 'org-after-sorting-entries-or-items-hook)
8122 (message "Sorting entries...done")))
8124 (defun org-contextualize-keys (alist contexts)
8125 "Return valid elements in ALIST depending on CONTEXTS.
8127 `org-agenda-custom-commands' or `org-capture-templates' are the
8128 values used for ALIST, and `org-agenda-custom-commands-contexts'
8129 or `org-capture-templates-contexts' are the associated contexts
8130 definitions."
8131 (let ((contexts
8132 ;; normalize contexts
8133 (mapcar
8134 (lambda(c) (cond ((listp (cadr c))
8135 (list (car c) (car c) (nth 1 c)))
8136 ((string= "" (cadr c))
8137 (list (car c) (car c) (nth 2 c)))
8138 (t c)))
8139 contexts))
8140 (a alist) r s)
8141 ;; loop over all commands or templates
8142 (dolist (c a)
8143 (let (vrules repl)
8144 (cond
8145 ((not (assoc (car c) contexts))
8146 (push c r))
8147 ((and (assoc (car c) contexts)
8148 (setq vrules (org-contextualize-validate-key
8149 (car c) contexts)))
8150 (mapc (lambda (vr)
8151 (unless (equal (car vr) (cadr vr))
8152 (setq repl vr)))
8153 vrules)
8154 (if (not repl) (push c r)
8155 (push (cadr repl) s)
8156 (push
8157 (cons (car c)
8158 (cdr (or (assoc (cadr repl) alist)
8159 (error "Undefined key `%s' as contextual replacement for `%s'"
8160 (cadr repl) (car c)))))
8161 r))))))
8162 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8163 (delq
8165 (delete-dups
8166 (mapcar (lambda (x)
8167 (let ((tpl (car x)))
8168 (unless (delq
8170 (mapcar (lambda (y)
8171 (equal y tpl))
8173 x)))
8174 (reverse r))))))
8176 (defun org-contextualize-validate-key (key contexts)
8177 "Check CONTEXTS for agenda or capture KEY."
8178 (let (res)
8179 (dolist (r contexts)
8180 (dolist (rr (car (last r)))
8181 (when
8182 (and (equal key (car r))
8183 (if (functionp rr) (funcall rr)
8184 (or (and (eq (car rr) 'in-file)
8185 (buffer-file-name)
8186 (string-match (cdr rr) (buffer-file-name)))
8187 (and (eq (car rr) 'in-mode)
8188 (string-match (cdr rr) (symbol-name major-mode)))
8189 (and (eq (car rr) 'in-buffer)
8190 (string-match (cdr rr) (buffer-name)))
8191 (when (and (eq (car rr) 'not-in-file)
8192 (buffer-file-name))
8193 (not (string-match (cdr rr) (buffer-file-name))))
8194 (when (eq (car rr) 'not-in-mode)
8195 (not (string-match (cdr rr) (symbol-name major-mode))))
8196 (when (eq (car rr) 'not-in-buffer)
8197 (not (string-match (cdr rr) (buffer-name)))))))
8198 (push r res))))
8199 (delete-dups (delq nil res))))
8201 ;; Defined to provide a value for defcustom, since there is no
8202 ;; string-collate-greaterp in Emacs.
8203 (defun org-string-collate-greaterp (s1 s2)
8204 "Return non-nil if S1 is greater than S2 in collation order."
8205 (not (org-string-collate-lessp s1 s2)))
8207 ;;;###autoload
8208 (defun org-run-like-in-org-mode (cmd)
8209 "Run a command, pretending that the current buffer is in Org mode.
8210 This will temporarily bind local variables that are typically bound in
8211 Org mode to the values they have in Org mode, and then interactively
8212 call CMD."
8213 (org-load-modules-maybe)
8214 (let (binds)
8215 (dolist (var (org-get-local-variables))
8216 (when (or (not (boundp (car var)))
8217 (eq (symbol-value (car var))
8218 (default-value (car var))))
8219 (push (list (car var) `(quote ,(cadr var))) binds)))
8220 (eval `(let ,binds
8221 (call-interactively (quote ,cmd))))))
8223 (defun org-get-category (&optional pos force-refresh)
8224 "Get the category applying to position POS."
8225 (save-match-data
8226 (when force-refresh (org-refresh-category-properties))
8227 (let ((pos (or pos (point))))
8228 (or (get-text-property pos 'org-category)
8229 (progn (org-refresh-category-properties)
8230 (get-text-property pos 'org-category))))))
8232 ;;; Refresh properties
8234 (defun org-refresh-properties (dprop tprop)
8235 "Refresh buffer text properties.
8236 DPROP is the drawer property and TPROP is either the
8237 corresponding text property to set, or an alist with each element
8238 being a text property (as a symbol) and a function to apply to
8239 the value of the drawer property."
8240 (let* ((case-fold-search t)
8241 (inhibit-read-only t)
8242 (inherit? (org-property-inherit-p dprop))
8243 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8244 (global (and inherit? (org--property-global-value dprop nil))))
8245 (with-silent-modifications
8246 (org-with-point-at 1
8247 ;; Set global values (e.g., values defined through
8248 ;; "#+PROPERTY:" keywords) to the whole buffer.
8249 (when global (put-text-property (point-min) (point-max) tprop global))
8250 ;; Set local values.
8251 (while (re-search-forward property-re nil t)
8252 (when (org-at-property-p)
8253 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8254 (outline-next-heading))))))
8256 (defun org-refresh-property (tprop p &optional inherit)
8257 "Refresh the buffer text property TPROP from the drawer property P.
8258 The refresh happens only for the current headline, or the whole
8259 sub-tree if optional argument INHERIT is non-nil."
8260 (unless (org-before-first-heading-p)
8261 (save-excursion
8262 (org-back-to-heading t)
8263 (let ((start (point))
8264 (end (save-excursion
8265 (if inherit (org-end-of-subtree t t)
8266 (or (outline-next-heading) (point-max))))))
8267 (if (symbolp tprop)
8268 ;; TPROP is a text property symbol.
8269 (put-text-property start end tprop p)
8270 ;; TPROP is an alist with (property . function) elements.
8271 (pcase-dolist (`(,prop . ,f) tprop)
8272 (put-text-property start end prop (funcall f p))))))))
8274 (defun org-refresh-category-properties ()
8275 "Refresh category text properties in the buffer."
8276 (let ((case-fold-search t)
8277 (inhibit-read-only t)
8278 (default-category
8279 (cond ((null org-category)
8280 (if buffer-file-name
8281 (file-name-sans-extension
8282 (file-name-nondirectory buffer-file-name))
8283 "???"))
8284 ((symbolp org-category) (symbol-name org-category))
8285 (t org-category))))
8286 (with-silent-modifications
8287 (org-with-wide-buffer
8288 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8289 ;; This is the default category for the buffer. If none is
8290 ;; found, fall-back to `org-category' or buffer file name.
8291 (put-text-property
8292 (point-min) (point-max)
8293 'org-category
8294 (catch 'buffer-category
8295 (goto-char (point-max))
8296 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
8297 (let ((element (org-element-at-point)))
8298 (when (eq (org-element-type element) 'keyword)
8299 (throw 'buffer-category
8300 (org-element-property :value element)))))
8301 default-category))
8302 ;; Set sub-tree specific categories.
8303 (goto-char (point-min))
8304 (let ((regexp (org-re-property "CATEGORY")))
8305 (while (re-search-forward regexp nil t)
8306 (let ((value (match-string-no-properties 3)))
8307 (when (org-at-property-p)
8308 (put-text-property
8309 (save-excursion (org-back-to-heading t) (point))
8310 (save-excursion (org-end-of-subtree t t) (point))
8311 'org-category
8312 value)))))))))
8314 (defun org-refresh-stats-properties ()
8315 "Refresh stats text properties in the buffer."
8316 (with-silent-modifications
8317 (org-with-point-at 1
8318 (let ((regexp (concat org-outline-regexp-bol
8319 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
8320 (while (re-search-forward regexp nil t)
8321 (let* ((numerator (string-to-number (match-string 1)))
8322 (denominator (and (match-end 2)
8323 (string-to-number (match-string 2))))
8324 (stats (cond ((not denominator) numerator) ;percent
8325 ((= denominator 0) 0)
8326 (t (/ (* numerator 100) denominator)))))
8327 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
8328 'org-stats stats)))))))
8330 (defun org-refresh-effort-properties ()
8331 "Refresh effort properties"
8332 (org-refresh-properties
8333 org-effort-property
8334 '((effort . identity)
8335 (effort-minutes . org-duration-to-minutes))))
8337 (defun org-find-file-at-mouse (ev)
8338 "Open file link or URL at mouse."
8339 (interactive "e")
8340 (mouse-set-point ev)
8341 (org-open-at-point 'in-emacs))
8343 (defun org-open-at-mouse (ev)
8344 "Open file link or URL at mouse.
8345 See the docstring of `org-open-file' for details."
8346 (interactive "e")
8347 (mouse-set-point ev)
8348 (when (eq major-mode 'org-agenda-mode)
8349 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8350 (org-open-at-point))
8352 (defvar org-window-config-before-follow-link nil
8353 "The window configuration before following a link.
8354 This is saved in case the need arises to restore it.")
8356 (defun org--file-default-apps ()
8357 "Return the default applications for this operating system."
8358 (pcase system-type
8359 (`darwin org-file-apps-macos)
8360 (`windows-nt org-file-apps-windowsnt)
8361 (_ org-file-apps-gnu)))
8363 (defun org--file-apps-entry-dlink-p (entry)
8364 "Non-nil if ENTRY should be matched against the link by `org-open-file'.
8366 It assumes that is the case when the entry uses a regular
8367 expression which has at least one grouping construct and the
8368 action is either a Lisp form or a command string containing
8369 \"%1\", i.e., using at least one subexpression match as
8370 a parameter."
8371 (pcase entry
8372 (`(,selector . ,action)
8373 (and (stringp selector)
8374 (> (regexp-opt-depth selector) 0)
8375 (or (and (stringp action)
8376 (string-match "%[0-9]" action))
8377 (consp action))))
8378 (_ nil)))
8380 (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
8381 "Convert extensions to regular expressions in the cars of LIST.
8383 Also, weed out any non-string entries, because the return value
8384 is used only for regexp matching.
8386 When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
8387 point to the symbol `emacs', indicating that the file should be
8388 opened in Emacs."
8389 (append
8390 (delq nil
8391 (mapcar (lambda (x)
8392 (unless (not (stringp (car x)))
8393 (if (string-match "\\W" (car x))
8395 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8396 list))
8397 (when add-auto-mode
8398 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8400 ;;;###autoload
8401 (defun org-open-file (path &optional in-emacs line search)
8402 "Open the file at PATH.
8403 First, this expands any special file name abbreviations. Then the
8404 configuration variable `org-file-apps' is checked if it contains an
8405 entry for this file type, and if yes, the corresponding command is launched.
8407 If no application is found, Emacs simply visits the file.
8409 With optional prefix argument IN-EMACS, Emacs will visit the file.
8410 With a double \\[universal-argument] \\[universal-argument] \
8411 prefix arg, Org tries to avoid opening in Emacs
8412 and to use an external application to visit the file.
8414 Optional LINE specifies a line to go to, optional SEARCH a string
8415 to search for. If LINE or SEARCH is given, the file will be
8416 opened in Emacs, unless an entry from `org-file-apps' that makes
8417 use of groups in a regexp matches.
8419 If you want to change the way frames are used when following a
8420 link, please customize `org-link-frame-setup'.
8422 If the file does not exist, throw an error."
8423 (let* ((file (if (equal path "") buffer-file-name
8424 (substitute-in-file-name (expand-file-name path))))
8425 (file-apps (append org-file-apps (org--file-default-apps)))
8426 (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
8427 (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
8428 file-apps))
8429 (remp (and (assq 'remote apps) (file-remote-p file)))
8430 (dirp (unless remp (file-directory-p file)))
8431 (file (if (and dirp org-open-directory-means-index-dot-org)
8432 (concat (file-name-as-directory file) "index.org")
8433 file))
8434 (a-m-a-p (assq 'auto-mode apps))
8435 (dfile (downcase file))
8436 ;; Reconstruct the original link from the PATH, LINE and
8437 ;; SEARCH args.
8438 (link (cond (line (concat file "::" (number-to-string line)))
8439 (search (concat file "::" search))
8440 (t file)))
8441 (dlink (downcase link))
8442 (ext
8443 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
8444 (match-string 1 dfile)))
8445 (save-position-maybe
8446 (let ((old-buffer (current-buffer))
8447 (old-pos (point))
8448 (old-mode major-mode))
8449 (lambda ()
8450 (and (derived-mode-p 'org-mode)
8451 (eq old-mode 'org-mode)
8452 (or (not (eq old-buffer (current-buffer)))
8453 (not (eq old-pos (point))))
8454 (org-mark-ring-push old-pos old-buffer)))))
8455 cmd link-match-data)
8456 (cond
8457 ((member in-emacs '((16) system))
8458 (setq cmd (cdr (assq 'system apps))))
8459 (in-emacs (setq cmd 'emacs))
8461 (setq cmd (or (and remp (cdr (assq 'remote apps)))
8462 (and dirp (cdr (assq 'directory apps)))
8463 ;; First, try matching against apps-dlink if we
8464 ;; get a match here, store the match data for
8465 ;; later.
8466 (let ((match (assoc-default dlink apps-dlink
8467 'string-match)))
8468 (if match
8469 (progn (setq link-match-data (match-data))
8470 match)
8471 (progn (setq in-emacs (or in-emacs line search))
8472 nil))) ; if we have no match in apps-dlink,
8473 ; always open the file in emacs if line or search
8474 ; is given (for backwards compatibility)
8475 (assoc-default dfile
8476 (org--file-apps-regexp-alist apps a-m-a-p)
8477 'string-match)
8478 (cdr (assoc ext apps))
8479 (cdr (assq t apps))))))
8480 (when (eq cmd 'system)
8481 (setq cmd (cdr (assq 'system apps))))
8482 (when (eq cmd 'default)
8483 (setq cmd (cdr (assoc t apps))))
8484 (when (eq cmd 'mailcap)
8485 (require 'mailcap)
8486 (mailcap-parse-mailcaps)
8487 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8488 (command (mailcap-mime-info mime-type)))
8489 (if (stringp command)
8490 (setq cmd command)
8491 (setq cmd 'emacs))))
8492 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8493 (not (file-exists-p file))
8494 (not org-open-non-existing-files))
8495 (user-error "No such file: %s" file))
8496 (cond
8497 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8498 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8499 (while (string-match "['\"]%s['\"]" cmd)
8500 (setq cmd (replace-match "%s" t t cmd)))
8501 (setq cmd (replace-regexp-in-string
8502 "%s"
8503 (shell-quote-argument (convert-standard-filename file))
8505 nil t))
8507 ;; Replace "%1", "%2" etc. in command with group matches from regex
8508 (save-match-data
8509 (let ((match-index 1)
8510 (number-of-groups (- (/ (length link-match-data) 2) 1)))
8511 (set-match-data link-match-data)
8512 (while (<= match-index number-of-groups)
8513 (let ((regex (concat "%" (number-to-string match-index)))
8514 (replace-with (match-string match-index dlink)))
8515 (while (string-match regex cmd)
8516 (setq cmd (replace-match replace-with t t cmd))))
8517 (setq match-index (+ match-index 1)))))
8519 (save-window-excursion
8520 (message "Running %s...done" cmd)
8521 (start-process-shell-command cmd nil cmd)
8522 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
8523 ((or (stringp cmd)
8524 (eq cmd 'emacs))
8525 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8526 (widen)
8527 (cond (line (org-goto-line line)
8528 (when (derived-mode-p 'org-mode) (org-reveal)))
8529 (search (condition-case err
8530 (org-link-search search)
8531 ;; Save position before error-ing out so user
8532 ;; can easily move back to the original buffer.
8533 (error (funcall save-position-maybe)
8534 (error (nth 1 err)))))))
8535 ((functionp cmd)
8536 (save-match-data
8537 (set-match-data link-match-data)
8538 (condition-case nil
8539 (funcall cmd file link)
8540 ;; FIXME: Remove this check when most default installations
8541 ;; of Emacs have at least Org 9.0.
8542 ((debug wrong-number-of-arguments wrong-type-argument
8543 invalid-function)
8544 (user-error "Please see Org News for version 9.0 about \
8545 `org-file-apps'--Lisp error: %S" cmd)))))
8546 ((consp cmd)
8547 ;; FIXME: Remove this check when most default installations of
8548 ;; Emacs have at least Org 9.0. Heads-up instead of silently
8549 ;; fall back to `org-link-frame-setup' for an old usage of
8550 ;; `org-file-apps' with sexp instead of a function for `cmd'.
8551 (user-error "Please see Org News for version 9.0 about \
8552 `org-file-apps'--Error: Deprecated usage of %S" cmd))
8553 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8554 (funcall save-position-maybe)))
8556 ;;;###autoload
8557 (defun org-open-at-point-global ()
8558 "Follow a link or a time-stamp like Org mode does.
8559 Also follow links and emails as seen by `thing-at-point'.
8560 This command can be called in any mode to follow an external
8561 link or a time-stamp that has Org mode syntax. Its behavior
8562 is undefined when called on internal links like fuzzy links.
8563 Raise a user error when there is nothing to follow."
8564 (interactive)
8565 (let ((tap-url (thing-at-point 'url))
8566 (tap-email (thing-at-point 'email)))
8567 (cond ((org-in-regexp org-link-any-re)
8568 (org-link-open-from-string (match-string-no-properties 0)))
8569 ((or (org-in-regexp org-ts-regexp-both nil t)
8570 (org-in-regexp org-tsr-regexp-both nil t))
8571 (org-follow-timestamp-link))
8572 (tap-url (org-link-open-from-string tap-url))
8573 (tap-email (org-link-open-from-string
8574 (concat "mailto:" tap-email)))
8575 (t (user-error "No link found")))))
8577 (defvar org-open-at-point-functions nil
8578 "Hook that is run when following a link at point.
8580 Functions in this hook must return t if they identify and follow
8581 a link at point. If they don't find anything interesting at point,
8582 they must return nil.")
8584 (defun org-open-at-point (&optional arg)
8585 "Open link, timestamp, footnote or tags at point.
8587 When point is on a link, follow it. Normally, files will be
8588 opened by an appropriate application. If the optional prefix
8589 argument ARG is non-nil, Emacs will visit the file. With
8590 a double prefix argument, try to open outside of Emacs, in the
8591 application the system uses for this file type.
8593 When point is on a timestamp, open the agenda at the day
8594 specified.
8596 When point is a footnote definition, move to the first reference
8597 found. If it is on a reference, move to the associated
8598 definition.
8600 When point is on a headline, display a list of every link in the
8601 entry, so it is possible to pick one, or all, of them. If point
8602 is on a tag, call `org-tags-view' instead.
8604 On top of syntactically correct links, this function also tries
8605 to open links and time-stamps in comments, node properties, and
8606 keywords if point is on something looking like a timestamp or
8607 a link."
8608 (interactive "P")
8609 (org-load-modules-maybe)
8610 (setq org-window-config-before-follow-link (current-window-configuration))
8611 (org-remove-occur-highlights nil nil t)
8612 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
8613 (let* ((context
8614 ;; Only consider supported types, even if they are not the
8615 ;; closest one.
8616 (org-element-lineage
8617 (org-element-context)
8618 '(clock comment comment-block footnote-definition
8619 footnote-reference headline inline-src-block inlinetask
8620 keyword link node-property planning src-block timestamp)
8622 (type (org-element-type context))
8623 (value (org-element-property :value context)))
8624 (cond
8625 ((not type) (user-error "No link found"))
8626 ;; No valid link at point. For convenience, look if something
8627 ;; looks like a link under point in some specific places.
8628 ((memq type '(comment comment-block node-property keyword))
8629 (call-interactively #'org-open-at-point-global))
8630 ;; On a headline or an inlinetask, but not on a timestamp,
8631 ;; a link, a footnote reference.
8632 ((memq type '(headline inlinetask))
8633 (org-match-line org-complex-heading-regexp)
8634 (if (and (match-beginning 5)
8635 (>= (point) (match-beginning 5))
8636 (< (point) (match-end 5)))
8637 ;; On tags.
8638 (org-tags-view
8640 (save-excursion
8641 (let* ((beg (match-beginning 5))
8642 (end (match-end 5))
8643 (beg-tag (or (search-backward ":" beg 'at-limit) (point)))
8644 (end-tag (search-forward ":" end nil 2)))
8645 (buffer-substring (1+ beg-tag) (1- end-tag)))))
8646 ;; Not on tags.
8647 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
8648 (`(nil . ,_)
8649 (require 'org-attach)
8650 (org-attach-reveal 'if-exists))
8651 (`(,links . ,links-end)
8652 (dolist (link (if (stringp links) (list links) links))
8653 (search-forward link nil links-end)
8654 (goto-char (match-beginning 0))
8655 (org-open-at-point))))))
8656 ;; On a footnote reference or at definition's label.
8657 ((or (eq type 'footnote-reference)
8658 (and (eq type 'footnote-definition)
8659 (save-excursion
8660 ;; Do not validate action when point is on the
8661 ;; spaces right after the footnote label, in order
8662 ;; to be on par with behavior on links.
8663 (skip-chars-forward " \t")
8664 (let ((begin
8665 (org-element-property :contents-begin context)))
8666 (if begin (< (point) begin)
8667 (= (org-element-property :post-affiliated context)
8668 (line-beginning-position)))))))
8669 (org-footnote-action))
8670 ;; On a planning line. Check if we are really on a timestamp.
8671 ((and (eq type 'planning)
8672 (org-in-regexp org-ts-regexp-both nil t))
8673 (org-follow-timestamp-link))
8674 ;; On a clock line, make sure point is on the timestamp
8675 ;; before opening it.
8676 ((and (eq type 'clock)
8677 value
8678 (>= (point) (org-element-property :begin value))
8679 (<= (point) (org-element-property :end value)))
8680 (org-follow-timestamp-link))
8681 ((eq type 'src-block) (org-babel-open-src-block-result))
8682 ;; Do nothing on white spaces after an object.
8683 ((>= (point)
8684 (save-excursion
8685 (goto-char (org-element-property :end context))
8686 (skip-chars-backward " \t")
8687 (point)))
8688 (user-error "No link found"))
8689 ((eq type 'inline-src-block) (org-babel-open-src-block-result))
8690 ((eq type 'timestamp) (org-follow-timestamp-link))
8691 ((eq type 'link) (org-link-open context arg))
8692 (t (user-error "No link found")))))
8693 (run-hook-with-args 'org-follow-link-hook))
8695 ;;;###autoload
8696 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
8697 "Offer links in the current entry and return the selected link.
8698 If there is only one link, return it.
8699 If NTH is an integer, return the NTH link found.
8700 If ZERO is a string, check also this string for a link, and if
8701 there is one, return it."
8702 (with-current-buffer buffer
8703 (org-with-wide-buffer
8704 (goto-char marker)
8705 (let ((cnt ?0)
8706 have-zero end links link c)
8707 (when (and (stringp zero) (string-match org-link-bracket-re zero))
8708 (push (match-string 0 zero) links)
8709 (setq cnt (1- cnt) have-zero t))
8710 (save-excursion
8711 (org-back-to-heading t)
8712 (setq end (save-excursion (outline-next-heading) (point)))
8713 (while (re-search-forward org-link-any-re end t)
8714 (push (match-string 0) links))
8715 (setq links (org-uniquify (reverse links))))
8716 (cond
8717 ((null links)
8718 (message "No links"))
8719 ((equal (length links) 1)
8720 (setq link (car links)))
8721 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8722 (setq link (nth (if have-zero nth (1- nth)) links)))
8723 (t ; we have to select a link
8724 (save-excursion
8725 (save-window-excursion
8726 (delete-other-windows)
8727 (with-output-to-temp-buffer "*Select Link*"
8728 (dolist (l links)
8729 (cond
8730 ((not (string-match org-link-bracket-re l))
8731 (princ (format "[%c] %s\n" (cl-incf cnt)
8732 (org-unbracket-string "<" ">" l))))
8733 ((match-end 2)
8734 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
8735 (match-string 2 l) (match-string 1 l))))
8736 (t (princ (format "[%c] %s\n" (cl-incf cnt)
8737 (match-string 1 l)))))))
8738 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8739 (message "Select link to open, RET to open all:")
8740 (setq c (read-char-exclusive))
8741 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8742 (when (equal c ?q) (user-error "Abort"))
8743 (if (equal c ?\C-m)
8744 (setq link links)
8745 (setq nth (- c ?0))
8746 (when have-zero (setq nth (1+ nth)))
8747 (unless (and (integerp nth) (>= (length links) nth))
8748 (user-error "Invalid link selection"))
8749 (setq link (nth (1- nth) links)))))
8750 (cons link end)))))
8752 ;;; File search
8754 (defun org-do-occur (regexp &optional cleanup)
8755 "Call the Emacs command `occur'.
8756 If CLEANUP is non-nil, remove the printout of the regular expression
8757 in the *Occur* buffer. This is useful if the regex is long and not useful
8758 to read."
8759 (occur regexp)
8760 (when cleanup
8761 (let ((cwin (selected-window)) win beg end)
8762 (when (setq win (get-buffer-window "*Occur*"))
8763 (select-window win))
8764 (goto-char (point-min))
8765 (when (re-search-forward "match[a-z]+" nil t)
8766 (setq beg (match-end 0))
8767 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
8768 (setq end (1- (match-beginning 0)))))
8769 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8770 (goto-char (point-min))
8771 (select-window cwin))))
8774 ;;; The Mark Ring
8776 (defvar org-mark-ring nil
8777 "Mark ring for positions before jumps in Org mode.")
8779 (defvar org-mark-ring-last-goto nil
8780 "Last position in the mark ring used to go back.")
8782 ;; Fill and close the ring
8783 (setq org-mark-ring nil)
8784 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
8786 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
8787 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8788 org-mark-ring)
8790 (defun org-mark-ring-push (&optional pos buffer)
8791 "Put the current position into the mark ring and rotate it.
8792 Also push position into the Emacs mark ring. If optional
8793 argument POS and BUFFER are not nil, mark this location instead."
8794 (interactive)
8795 (let ((pos (or pos (point)))
8796 (buffer (or buffer (current-buffer))))
8797 (with-current-buffer buffer
8798 (org-with-point-at pos (push-mark nil t)))
8799 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8800 (move-marker (car org-mark-ring) pos buffer))
8801 (message
8802 (substitute-command-keys
8803 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
8805 (defun org-mark-ring-goto (&optional n)
8806 "Jump to the previous position in the mark ring.
8807 With prefix arg N, jump back that many stored positions. When
8808 called several times in succession, walk through the entire ring.
8809 Org mode commands jumping to a different position in the current file,
8810 or to another Org file, automatically push the old position onto the ring."
8811 (interactive "p")
8812 (let (p m)
8813 (if (eq last-command this-command)
8814 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8815 (setq p org-mark-ring))
8816 (setq org-mark-ring-last-goto p)
8817 (setq m (car p))
8818 (pop-to-buffer-same-window (marker-buffer m))
8819 (goto-char m)
8820 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8822 ;;; Following specific links
8824 (defvar org-agenda-buffer-tmp-name)
8825 (defvar org-agenda-start-on-weekday)
8826 (defun org-follow-timestamp-link ()
8827 "Open an agenda view for the time-stamp date/range at point."
8828 (cond
8829 ((org-at-date-range-p t)
8830 (let ((org-agenda-start-on-weekday)
8831 (t1 (match-string 1))
8832 (t2 (match-string 2)) tt1 tt2)
8833 (setq tt1 (time-to-days (org-time-string-to-time t1))
8834 tt2 (time-to-days (org-time-string-to-time t2)))
8835 (let ((org-agenda-buffer-tmp-name
8836 (format "*Org Agenda(a:%s)"
8837 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
8838 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
8839 ((org-at-timestamp-p 'lax)
8840 (let ((org-agenda-buffer-tmp-name
8841 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
8842 (org-agenda-list nil (time-to-days (org-time-string-to-time
8843 (substring (match-string 1) 0 10)))
8844 1)))
8845 (t (error "This should not happen"))))
8848 ;;; Following file links
8849 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
8850 (declare-function mailcap-extension-to-mime "mailcap" (extn))
8851 (declare-function mailcap-mime-info
8852 "mailcap" (string &optional request no-decode))
8853 (defvar org-wait nil)
8855 ;;;; Refiling
8857 (defun org-get-org-file ()
8858 "Read a filename, with default directory `org-directory'."
8859 (let ((default (or org-default-notes-file remember-data-file)))
8860 (read-file-name (format "File name [%s]: " default)
8861 (file-name-as-directory org-directory)
8862 default)))
8864 (defun org-notes-order-reversed-p ()
8865 "Check if the current file should receive notes in reversed order."
8866 (cond
8867 ((not org-reverse-note-order) nil)
8868 ((eq t org-reverse-note-order) t)
8869 ((not (listp org-reverse-note-order)) nil)
8870 (t (catch 'exit
8871 (dolist (entry org-reverse-note-order)
8872 (when (string-match (car entry) buffer-file-name)
8873 (throw 'exit (cdr entry))))))))
8875 (defvar org-refile-target-table nil
8876 "The list of refile targets, created by `org-refile'.")
8878 (defvar org-agenda-new-buffers nil
8879 "Buffers created to visit agenda files.")
8881 (defvar org-refile-cache nil
8882 "Cache for refile targets.")
8884 (defvar org-refile-markers nil
8885 "All the markers used for caching refile locations.")
8887 (defun org-refile-marker (pos)
8888 "Get a new refile marker, but only if caching is in use."
8889 (if (not org-refile-use-cache)
8891 (let ((m (make-marker)))
8892 (move-marker m pos)
8893 (push m org-refile-markers)
8894 m)))
8896 (defun org-refile-cache-clear ()
8897 "Clear the refile cache and disable all the markers."
8898 (dolist (m org-refile-markers) (move-marker m nil))
8899 (setq org-refile-markers nil)
8900 (setq org-refile-cache nil)
8901 (message "Refile cache has been cleared"))
8903 (defun org-refile-cache-check-set (set)
8904 "Check if all the markers in the cache still have live buffers."
8905 (let (marker)
8906 (catch 'exit
8907 (while (and set (setq marker (nth 3 (pop set))))
8908 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
8909 (when (and marker (null (marker-buffer marker)))
8910 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
8911 (sit-for 3)
8912 (throw 'exit nil)))
8913 t)))
8915 (defun org-refile-cache-put (set &rest identifiers)
8916 "Push the refile targets SET into the cache, under IDENTIFIERS."
8917 (let* ((key (sha1 (prin1-to-string identifiers)))
8918 (entry (assoc key org-refile-cache)))
8919 (if entry
8920 (setcdr entry set)
8921 (push (cons key set) org-refile-cache))))
8923 (defun org-refile-cache-get (&rest identifiers)
8924 "Retrieve the cached value for refile targets given by IDENTIFIERS."
8925 (cond
8926 ((not org-refile-cache) nil)
8927 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
8929 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
8930 org-refile-cache))))
8931 (and set (org-refile-cache-check-set set) set)))))
8933 (defvar org-outline-path-cache nil
8934 "Alist between buffer positions and outline paths.
8935 It value is an alist (POSITION . PATH) where POSITION is the
8936 buffer position at the beginning of an entry and PATH is a list
8937 of strings describing the outline path for that entry, in reverse
8938 order.")
8940 (defun org-refile-get-targets (&optional default-buffer)
8941 "Produce a table with refile targets."
8942 (let ((case-fold-search nil)
8943 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8944 (entries (or org-refile-targets '((nil . (:level . 1)))))
8945 targets tgs files desc descre)
8946 (message "Getting targets...")
8947 (with-current-buffer (or default-buffer (current-buffer))
8948 (dolist (entry entries)
8949 (setq files (car entry) desc (cdr entry))
8950 (cond
8951 ((null files) (setq files (list (current-buffer))))
8952 ((eq files 'org-agenda-files)
8953 (setq files (org-agenda-files 'unrestricted)))
8954 ((and (symbolp files) (fboundp files))
8955 (setq files (funcall files)))
8956 ((and (symbolp files) (boundp files))
8957 (setq files (symbol-value files))))
8958 (when (stringp files) (setq files (list files)))
8959 (cond
8960 ((eq (car desc) :tag)
8961 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8962 ((eq (car desc) :todo)
8963 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8964 ((eq (car desc) :regexp)
8965 (setq descre (cdr desc)))
8966 ((eq (car desc) :level)
8967 (setq descre (concat "^\\*\\{" (number-to-string
8968 (if org-odd-levels-only
8969 (1- (* 2 (cdr desc)))
8970 (cdr desc)))
8971 "\\}[ \t]")))
8972 ((eq (car desc) :maxlevel)
8973 (setq descre (concat "^\\*\\{1," (number-to-string
8974 (if org-odd-levels-only
8975 (1- (* 2 (cdr desc)))
8976 (cdr desc)))
8977 "\\}[ \t]")))
8978 (t (error "Bad refiling target description %s" desc)))
8979 (dolist (f files)
8980 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
8982 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
8983 (progn
8984 (when (bufferp f)
8985 (setq f (buffer-file-name (buffer-base-buffer f))))
8986 (setq f (and f (expand-file-name f)))
8987 (when (eq org-refile-use-outline-path 'file)
8988 (push (list (file-name-nondirectory f) f nil nil) tgs))
8989 (when (eq org-refile-use-outline-path 'buffer-name)
8990 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
8991 (when (eq org-refile-use-outline-path 'full-file-path)
8992 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
8993 (org-with-wide-buffer
8994 (goto-char (point-min))
8995 (setq org-outline-path-cache nil)
8996 (while (re-search-forward descre nil t)
8997 (beginning-of-line)
8998 (let ((case-fold-search nil))
8999 (looking-at org-complex-heading-regexp))
9000 (let ((begin (point))
9001 (heading (match-string-no-properties 4)))
9002 (unless (or (and
9003 org-refile-target-verify-function
9004 (not
9005 (funcall org-refile-target-verify-function)))
9006 (not heading))
9007 (let ((re (format org-complex-heading-regexp-format
9008 (regexp-quote heading)))
9009 (target
9010 (if (not org-refile-use-outline-path) heading
9011 (mapconcat
9012 #'identity
9013 (append
9014 (pcase org-refile-use-outline-path
9015 (`file (list (file-name-nondirectory
9016 (buffer-file-name
9017 (buffer-base-buffer)))))
9018 (`full-file-path
9019 (list (buffer-file-name
9020 (buffer-base-buffer))))
9021 (`buffer-name
9022 (list (buffer-name
9023 (buffer-base-buffer))))
9024 (_ nil))
9025 (mapcar (lambda (s) (replace-regexp-in-string
9026 "/" "\\/" s nil t))
9027 (org-get-outline-path t t)))
9028 "/"))))
9029 (push (list target f re (org-refile-marker (point)))
9030 tgs)))
9031 (when (= (point) begin)
9032 ;; Verification function has not moved point.
9033 (end-of-line)))))))
9034 (when org-refile-use-cache
9035 (org-refile-cache-put tgs (buffer-file-name) descre))
9036 (setq targets (append tgs targets))))))
9037 (message "Getting targets...done")
9038 (delete-dups (nreverse targets))))
9040 (defun org--get-outline-path-1 (&optional use-cache)
9041 "Return outline path to current headline.
9043 Outline path is a list of strings, in reverse order. When
9044 optional argument USE-CACHE is non-nil, make use of a cache. See
9045 `org-get-outline-path' for details.
9047 Assume buffer is widened and point is on a headline."
9048 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
9049 (let ((p (point))
9050 (heading (let ((case-fold-search nil))
9051 (looking-at org-complex-heading-regexp)
9052 (if (not (match-end 4)) ""
9053 ;; Remove statistics cookies.
9054 (org-trim
9055 (org-link-display-format
9056 (replace-regexp-in-string
9057 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
9058 (match-string-no-properties 4))))))))
9059 (if (org-up-heading-safe)
9060 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
9061 (when use-cache
9062 (push (cons p path) org-outline-path-cache))
9063 path)
9064 ;; This is a new root node. Since we assume we are moving
9065 ;; forward, we can drop previous cache so as to limit number
9066 ;; of associations there.
9067 (let ((path (list heading)))
9068 (when use-cache (setq org-outline-path-cache (list (cons p path))))
9069 path)))))
9071 (defun org-get-outline-path (&optional with-self use-cache)
9072 "Return the outline path to the current entry.
9074 An outline path is a list of ancestors for current headline, as
9075 a list of strings. Statistics cookies are removed and links are
9076 replaced with their description, if any, or their path otherwise.
9078 When optional argument WITH-SELF is non-nil, the path also
9079 includes the current headline.
9081 When optional argument USE-CACHE is non-nil, cache outline paths
9082 between calls to this function so as to avoid backtracking. This
9083 argument is useful when planning to find more than one outline
9084 path in the same document. In that case, there are two
9085 conditions to satisfy:
9086 - `org-outline-path-cache' is set to nil before starting the
9087 process;
9088 - outline paths are computed by increasing buffer positions."
9089 (org-with-wide-buffer
9090 (and (or (and with-self (org-back-to-heading t))
9091 (org-up-heading-safe))
9092 (reverse (org--get-outline-path-1 use-cache)))))
9094 (defun org-format-outline-path (path &optional width prefix separator)
9095 "Format the outline path PATH for display.
9096 WIDTH is the maximum number of characters that is available.
9097 PREFIX is a prefix to be included in the returned string,
9098 such as the file name.
9099 SEPARATOR is inserted between the different parts of the path,
9100 the default is \"/\"."
9101 (setq width (or width 79))
9102 (setq path (delq nil path))
9103 (unless (> width 0)
9104 (user-error "Argument `width' must be positive"))
9105 (setq separator (or separator "/"))
9106 (let* ((org-odd-levels-only nil)
9107 (fpath (concat
9108 prefix (and prefix path separator)
9109 (mapconcat
9110 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
9111 (cl-loop for head in path
9112 for n from 0
9113 collect (org-add-props
9114 head nil 'face
9115 (nth (% n org-n-level-faces) org-level-faces)))
9116 separator))))
9117 (when (> (length fpath) width)
9118 (if (< width 7)
9119 ;; It's unlikely that `width' will be this small, but don't
9120 ;; waste characters by adding ".." if it is.
9121 (setq fpath (substring fpath 0 width))
9122 (setf (substring fpath (- width 2)) "..")))
9123 fpath))
9125 (defun org-display-outline-path (&optional file current separator just-return-string)
9126 "Display the current outline path in the echo area.
9128 If FILE is non-nil, prepend the output with the file name.
9129 If CURRENT is non-nil, append the current heading to the output.
9130 SEPARATOR is passed through to `org-format-outline-path'. It separates
9131 the different parts of the path and defaults to \"/\".
9132 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
9133 (interactive "P")
9134 (let* (case-fold-search
9135 (bfn (buffer-file-name (buffer-base-buffer)))
9136 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
9137 res)
9138 (when current (setq path (append path
9139 (save-excursion
9140 (org-back-to-heading t)
9141 (when (looking-at org-complex-heading-regexp)
9142 (list (match-string 4)))))))
9143 (setq res
9144 (org-format-outline-path
9145 path
9146 (1- (frame-width))
9147 (and file bfn (concat (file-name-nondirectory bfn) separator))
9148 separator))
9149 (if just-return-string
9150 (org-no-properties res)
9151 (org-unlogged-message "%s" res))))
9153 (defvar org-refile-history nil
9154 "History for refiling operations.")
9156 (defvar org-after-refile-insert-hook nil
9157 "Hook run after `org-refile' has inserted its stuff at the new location.
9158 Note that this is still *before* the stuff will be removed from
9159 the *old* location.")
9161 (defvar org-capture-last-stored-marker)
9162 (defvar org-refile-keep nil
9163 "Non-nil means `org-refile' will copy instead of refile.")
9165 (defun org-copy ()
9166 "Like `org-refile', but copy."
9167 (interactive)
9168 (let ((org-refile-keep t))
9169 (org-refile nil nil nil "Copy")))
9171 (defun org-refile (&optional arg default-buffer rfloc msg)
9172 "Move the entry or entries at point to another heading.
9174 The list of target headings is compiled using the information in
9175 `org-refile-targets', which see.
9177 At the target location, the entry is filed as a subitem of the
9178 target heading. Depending on `org-reverse-note-order', the new
9179 subitem will either be the first or the last subitem.
9181 If there is an active region, all entries in that region will be
9182 refiled. However, the region must fulfill the requirement that
9183 the first heading sets the top-level of the moved text.
9185 With a `\\[universal-argument]' ARG, the command will only visit the target \
9186 location
9187 and not actually move anything.
9189 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
9190 location where the last
9191 refiling operation has put the subtree.
9193 With a numeric prefix argument of `2', refile to the running clock.
9195 With a numeric prefix argument of `3', emulate `org-refile-keep'
9196 being set to t and copy to the target location, don't move it.
9197 Beware that keeping refiled entries may result in duplicated ID
9198 properties.
9200 RFLOC can be a refile location obtained in a different way.
9202 MSG is a string to replace \"Refile\" in the default prompt with
9203 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
9205 See also `org-refile-use-outline-path'.
9207 If you are using target caching (see `org-refile-use-cache'), you
9208 have to clear the target cache in order to find new targets.
9209 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
9210 prefix argument (`C-u C-u C-u C-c C-w')."
9211 (interactive "P")
9212 (if (member arg '(0 (64)))
9213 (org-refile-cache-clear)
9214 (let* ((actionmsg (cond (msg msg)
9215 ((equal arg 3) "Refile (and keep)")
9216 (t "Refile")))
9217 (regionp (org-region-active-p))
9218 (region-start (and regionp (region-beginning)))
9219 (region-end (and regionp (region-end)))
9220 (org-refile-keep (if (equal arg 3) t org-refile-keep))
9221 pos it nbuf file level reversed)
9222 (setq last-command nil)
9223 (when regionp
9224 (goto-char region-start)
9225 (beginning-of-line)
9226 (setq region-start (point))
9227 (unless (or (org-kill-is-subtree-p
9228 (buffer-substring region-start region-end))
9229 (prog1 org-refile-active-region-within-subtree
9230 (let ((s (point-at-eol)))
9231 (org-toggle-heading)
9232 (setq region-end (+ (- (point-at-eol) s) region-end)))))
9233 (user-error "The region is not a (sequence of) subtree(s)")))
9234 (if (equal arg '(16))
9235 (org-refile-goto-last-stored)
9236 (when (or
9237 (and (equal arg 2)
9238 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9239 (prog1
9240 (setq it (list (or org-clock-heading "running clock")
9241 (buffer-file-name
9242 (marker-buffer org-clock-hd-marker))
9244 (marker-position org-clock-hd-marker)))
9245 (setq arg nil)))
9246 (setq it
9247 (or rfloc
9248 (let (heading-text)
9249 (save-excursion
9250 (unless (and arg (listp arg))
9251 (org-back-to-heading t)
9252 (setq heading-text
9253 (replace-regexp-in-string
9254 org-link-bracket-re
9255 "\\2"
9256 (or (nth 4 (org-heading-components))
9257 ""))))
9258 (org-refile-get-location
9259 (cond ((and arg (listp arg)) "Goto")
9260 (regionp (concat actionmsg " region to"))
9261 (t (concat actionmsg " subtree \""
9262 heading-text "\" to")))
9263 default-buffer
9264 (and (not (equal '(4) arg))
9265 org-refile-allow-creating-parent-nodes)))))))
9266 (setq file (nth 1 it)
9267 pos (nth 3 it))
9268 (when (and (not arg)
9270 (equal (buffer-file-name) file)
9271 (if regionp
9272 (and (>= pos region-start)
9273 (<= pos region-end))
9274 (and (>= pos (point))
9275 (< pos (save-excursion
9276 (org-end-of-subtree t t))))))
9277 (error "Cannot refile to position inside the tree or region"))
9278 (setq nbuf (or (find-buffer-visiting file)
9279 (find-file-noselect file)))
9280 (if (and arg (not (equal arg 3)))
9281 (progn
9282 (pop-to-buffer-same-window nbuf)
9283 (goto-char (cond (pos)
9284 ((org-notes-order-reversed-p) (point-min))
9285 (t (point-max))))
9286 (org-show-context 'org-goto))
9287 (if regionp
9288 (progn
9289 (org-kill-new (buffer-substring region-start region-end))
9290 (org-save-markers-in-region region-start region-end))
9291 (org-copy-subtree 1 nil t))
9292 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9293 (find-file-noselect file)))
9294 (setq reversed (org-notes-order-reversed-p))
9295 (org-with-wide-buffer
9296 (if pos
9297 (progn
9298 (goto-char pos)
9299 (setq level (org-get-valid-level (funcall outline-level) 1))
9300 (goto-char
9301 (if reversed
9302 (or (outline-next-heading) (point-max))
9303 (or (save-excursion (org-get-next-sibling))
9304 (org-end-of-subtree t t)
9305 (point-max)))))
9306 (setq level 1)
9307 (if (not reversed)
9308 (goto-char (point-max))
9309 (goto-char (point-min))
9310 (or (outline-next-heading) (goto-char (point-max)))))
9311 (unless (bolp) (newline))
9312 (org-paste-subtree level nil nil t)
9313 ;; Record information, according to `org-log-refile'.
9314 ;; Do not prompt for a note when refiling multiple
9315 ;; headlines, however. Simply add a time stamp.
9316 (cond
9317 ((not org-log-refile))
9318 (regionp
9319 (org-map-region
9320 (lambda () (org-add-log-setup 'refile nil nil 'time))
9321 (point)
9322 (+ (point) (- region-end region-start))))
9324 (org-add-log-setup 'refile nil nil org-log-refile)))
9325 (and org-auto-align-tags
9326 (let ((org-loop-over-headlines-in-active-region nil))
9327 (org-align-tags)))
9328 (let ((bookmark-name (plist-get org-bookmark-names-plist
9329 :last-refile)))
9330 (when bookmark-name
9331 (with-demoted-errors
9332 (bookmark-set bookmark-name))))
9333 ;; If we are refiling for capture, make sure that the
9334 ;; last-capture pointers point here
9335 (when (bound-and-true-p org-capture-is-refiling)
9336 (let ((bookmark-name (plist-get org-bookmark-names-plist
9337 :last-capture-marker)))
9338 (when bookmark-name
9339 (with-demoted-errors
9340 (bookmark-set bookmark-name))))
9341 (move-marker org-capture-last-stored-marker (point)))
9342 (when (fboundp 'deactivate-mark) (deactivate-mark))
9343 (run-hooks 'org-after-refile-insert-hook)))
9344 (unless org-refile-keep
9345 (if regionp
9346 (delete-region (point) (+ (point) (- region-end region-start)))
9347 (org-preserve-local-variables
9348 (delete-region
9349 (and (org-back-to-heading t) (point))
9350 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
9351 (when (featurep 'org-inlinetask)
9352 (org-inlinetask-remove-END-maybe))
9353 (setq org-markers-to-move nil)
9354 (message "%s to \"%s\" in file %s: done" actionmsg
9355 (car it) file)))))))
9357 (defun org-refile-goto-last-stored ()
9358 "Go to the location where the last refile was stored."
9359 (interactive)
9360 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
9361 (message "This is the location of the last refile"))
9363 (defun org-refile--get-location (refloc tbl)
9364 "When user refile to REFLOC, find the associated target in TBL.
9365 Also check `org-refile-target-table'."
9366 (car (delq
9368 (mapcar
9369 (lambda (r) (or (assoc r tbl)
9370 (assoc r org-refile-target-table)))
9371 (list (replace-regexp-in-string "/$" "" refloc)
9372 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
9374 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9375 "Prompt the user for a refile location, using PROMPT.
9376 PROMPT should not be suffixed with a colon and a space, because
9377 this function appends the default value from
9378 `org-refile-history' automatically, if that is not empty."
9379 (let ((org-refile-targets org-refile-targets)
9380 (org-refile-use-outline-path org-refile-use-outline-path))
9381 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
9382 (unless org-refile-target-table
9383 (user-error "No refile targets"))
9384 (let* ((cbuf (current-buffer))
9385 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9386 (cfunc (if (and org-refile-use-outline-path
9387 org-outline-path-complete-in-steps)
9388 #'org-olpath-completing-read
9389 #'completing-read))
9390 (extra (if org-refile-use-outline-path "/" ""))
9391 (cbnex (concat (buffer-name) extra))
9392 (filename (and cfn (expand-file-name cfn)))
9393 (tbl (mapcar
9394 (lambda (x)
9395 (if (and (not (member org-refile-use-outline-path
9396 '(file full-file-path)))
9397 (not (equal filename (nth 1 x))))
9398 (cons (concat (car x) extra " ("
9399 (file-name-nondirectory (nth 1 x)) ")")
9400 (cdr x))
9401 (cons (concat (car x) extra) (cdr x))))
9402 org-refile-target-table))
9403 (completion-ignore-case t)
9404 cdef
9405 (prompt (concat prompt
9406 (or (and (car org-refile-history)
9407 (concat " (default " (car org-refile-history) ")"))
9408 (and (assoc cbnex tbl) (setq cdef cbnex)
9409 (concat " (default " cbnex ")"))) ": "))
9410 pa answ parent-target child parent old-hist)
9411 (setq old-hist org-refile-history)
9412 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9413 nil 'org-refile-history (or cdef (car org-refile-history))))
9414 (if (setq pa (org-refile--get-location answ tbl))
9415 (progn
9416 (org-refile-check-position pa)
9417 (when (or (not org-refile-history)
9418 (not (eq old-hist org-refile-history))
9419 (not (equal (car pa) (car org-refile-history))))
9420 (setq org-refile-history
9421 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9422 org-refile-history
9423 (cdr org-refile-history))))
9424 (when (equal (car org-refile-history) (nth 1 org-refile-history))
9425 (pop org-refile-history)))
9427 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9428 (progn
9429 (setq parent (match-string 1 answ)
9430 child (match-string 2 answ))
9431 (setq parent-target (org-refile--get-location parent tbl))
9432 (when (and parent-target
9433 (or (eq new-nodes t)
9434 (and (eq new-nodes 'confirm)
9435 (y-or-n-p (format "Create new node \"%s\"? "
9436 child)))))
9437 (org-refile-new-child parent-target child)))
9438 (user-error "Invalid target location")))))
9440 (declare-function org-string-nw-p "org-macs" (s))
9441 (defun org-refile-check-position (refile-pointer)
9442 "Check if the refile pointer matches the headline to which it points."
9443 (let* ((file (nth 1 refile-pointer))
9444 (re (nth 2 refile-pointer))
9445 (pos (nth 3 refile-pointer))
9446 buffer)
9447 (if (and (not (markerp pos)) (not file))
9448 (user-error "Please indicate a target file in the refile path")
9449 (when (org-string-nw-p re)
9450 (setq buffer (if (markerp pos)
9451 (marker-buffer pos)
9452 (or (find-buffer-visiting file)
9453 (find-file-noselect file))))
9454 (with-current-buffer buffer
9455 (org-with-wide-buffer
9456 (goto-char pos)
9457 (beginning-of-line 1)
9458 (unless (looking-at-p re)
9459 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
9461 (defun org-refile-new-child (parent-target child)
9462 "Use refile target PARENT-TARGET to add new CHILD below it."
9463 (unless parent-target
9464 (error "Cannot find parent for new node"))
9465 (let ((file (nth 1 parent-target))
9466 (pos (nth 3 parent-target))
9467 level)
9468 (with-current-buffer (or (find-buffer-visiting file)
9469 (find-file-noselect file))
9470 (org-with-wide-buffer
9471 (if pos
9472 (goto-char pos)
9473 (goto-char (point-max))
9474 (unless (bolp) (newline)))
9475 (when (looking-at org-outline-regexp)
9476 (setq level (funcall outline-level))
9477 (org-end-of-subtree t t))
9478 (org-back-over-empty-lines)
9479 (insert "\n" (make-string
9480 (if pos (org-get-valid-level level 1) 1) ?*)
9481 " " child "\n")
9482 (beginning-of-line 0)
9483 (list (concat (car parent-target) "/" child) file "" (point))))))
9485 (defun org-olpath-completing-read (prompt collection &rest args)
9486 "Read an outline path like a file name."
9487 (let ((thetable collection))
9488 (apply #'completing-read
9489 prompt
9490 (lambda (string predicate &optional flag)
9491 (cond
9492 ((eq flag nil) (try-completion string thetable))
9493 ((eq flag t)
9494 (let ((l (length string)))
9495 (mapcar (lambda (x)
9496 (let ((r (substring x l))
9497 (f (if (string-match " ([^)]*)$" x)
9498 (match-string 0 x)
9499 "")))
9500 (if (string-match "/" r)
9501 (concat string (substring r 0 (match-end 0)) f)
9502 x)))
9503 (all-completions string thetable predicate))))
9504 ;; Exact match?
9505 ((eq flag 'lambda) (assoc string thetable))))
9506 args)))
9508 ;;;; Dynamic blocks
9510 (defun org-find-dblock (name)
9511 "Find the first dynamic block with name NAME in the buffer.
9512 If not found, stay at current position and return nil."
9513 (let ((case-fold-search t) pos)
9514 (save-excursion
9515 (goto-char (point-min))
9516 (setq pos (and (re-search-forward
9517 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
9518 (match-beginning 0))))
9519 (when pos (goto-char pos))
9520 pos))
9522 (defun org-create-dblock (plist)
9523 "Create a dynamic block section, with parameters taken from PLIST.
9524 PLIST must contain a :name entry which is used as the name of the block."
9525 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9526 (end-of-line 1)
9527 (newline))
9528 (let ((col (current-column))
9529 (name (plist-get plist :name)))
9530 (insert "#+BEGIN: " name)
9531 (while plist
9532 (if (eq (car plist) :name)
9533 (setq plist (cddr plist))
9534 (insert " " (prin1-to-string (pop plist)))))
9535 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9536 (beginning-of-line -2)))
9538 (defun org-prepare-dblock ()
9539 "Prepare dynamic block for refresh.
9540 This empties the block, puts the cursor at the insert position and returns
9541 the property list including an extra property :name with the block name."
9542 (unless (looking-at org-dblock-start-re)
9543 (user-error "Not at a dynamic block"))
9544 (let* ((begdel (1+ (match-end 0)))
9545 (name (org-no-properties (match-string 1)))
9546 (params (append (list :name name)
9547 (read (concat "(" (match-string 3) ")")))))
9548 (save-excursion
9549 (beginning-of-line 1)
9550 (skip-chars-forward " \t")
9551 (setq params (plist-put params :indentation-column (current-column))))
9552 (unless (re-search-forward org-dblock-end-re nil t)
9553 (error "Dynamic block not terminated"))
9554 (setq params
9555 (append params
9556 (list :content (buffer-substring
9557 begdel (match-beginning 0)))))
9558 (delete-region begdel (match-beginning 0))
9559 (goto-char begdel)
9560 (open-line 1)
9561 params))
9563 (defun org-map-dblocks (&optional command)
9564 "Apply COMMAND to all dynamic blocks in the current buffer.
9565 If COMMAND is not given, use `org-update-dblock'."
9566 (let ((cmd (or command 'org-update-dblock)))
9567 (save-excursion
9568 (goto-char (point-min))
9569 (while (re-search-forward org-dblock-start-re nil t)
9570 (goto-char (match-beginning 0))
9571 (save-excursion
9572 (condition-case nil
9573 (funcall cmd)
9574 (error (message "Error during update of dynamic block"))))
9575 (unless (re-search-forward org-dblock-end-re nil t)
9576 (error "Dynamic block not terminated"))))))
9578 (defcustom org-dynamic-block-alist nil
9579 "Alist defining all the Org dynamic blocks.
9580 The key is the dynamic block type name, as a string. The value
9581 is the function used to insert the dynamic block."
9582 :group 'org-block
9583 :package-version '(Org . "9.3")
9584 :type '(alist :tag "Dynamic block name"
9585 :key-type string
9586 :value-type function)
9587 :safe #'listp)
9589 (defun org-dynamic-block-function (type)
9590 "Return function associated to a given dynamic block type.
9591 TYPE is the dynamic block type, as a string."
9592 (cdr (assoc type org-dynamic-block-alist)))
9594 (defun org-dynamic-block-types ()
9595 "List all defined dynamic block types."
9596 (mapcar #'car org-dynamic-block-alist))
9598 (defun org-dynamic-block-define (type func)
9599 "Define dynamic block TYPE with FUNC."
9600 (push (cons type func) org-dynamic-block-alist))
9602 (defun org-dynamic-block-insert-dblock (type)
9603 "Insert a dynamic block of type TYPE.
9604 When used interactively, select the dynamic block types among
9605 defined types, per `org-dynamic-block-define'."
9606 (interactive (list (completing-read "Dynamic block: "
9607 (org-dynamic-block-types))))
9608 (pcase (org-dynamic-block-function type)
9609 (`nil (error "No such dynamic block: %S" type))
9610 ((and f (pred functionp)) (funcall f))
9611 (_ (error "Invalid function for dynamic block %S" type))))
9613 (defun org-dblock-update (&optional arg)
9614 "User command for updating dynamic blocks.
9615 Update the dynamic block at point. With prefix ARG, update all dynamic
9616 blocks in the buffer."
9617 (interactive "P")
9618 (if arg
9619 (org-update-all-dblocks)
9620 (or (looking-at org-dblock-start-re)
9621 (org-beginning-of-dblock))
9622 (org-update-dblock)))
9624 (defun org-update-dblock ()
9625 "Update the dynamic block at point.
9626 This means to empty the block, parse for parameters and then call
9627 the correct writing function."
9628 (interactive)
9629 (save-excursion
9630 (let* ((win (selected-window))
9631 (pos (point))
9632 (line (org-current-line))
9633 (params (org-prepare-dblock))
9634 (name (plist-get params :name))
9635 (indent (plist-get params :indentation-column))
9636 (cmd (intern (concat "org-dblock-write:" name))))
9637 (message "Updating dynamic block `%s' at line %d..." name line)
9638 (funcall cmd params)
9639 (message "Updating dynamic block `%s' at line %d...done" name line)
9640 (goto-char pos)
9641 (when (and indent (> indent 0))
9642 (setq indent (make-string indent ?\ ))
9643 (save-excursion
9644 (select-window win)
9645 (org-beginning-of-dblock)
9646 (forward-line 1)
9647 (while (not (looking-at org-dblock-end-re))
9648 (insert indent)
9649 (beginning-of-line 2))
9650 (when (looking-at org-dblock-end-re)
9651 (and (looking-at "[ \t]+")
9652 (replace-match ""))
9653 (insert indent)))))))
9655 (defun org-beginning-of-dblock ()
9656 "Find the beginning of the dynamic block at point.
9657 Error if there is no such block at point."
9658 (let ((pos (point))
9659 beg)
9660 (end-of-line 1)
9661 (if (and (re-search-backward org-dblock-start-re nil t)
9662 (setq beg (match-beginning 0))
9663 (re-search-forward org-dblock-end-re nil t)
9664 (> (match-end 0) pos))
9665 (goto-char beg)
9666 (goto-char pos)
9667 (error "Not in a dynamic block"))))
9669 (defun org-update-all-dblocks ()
9670 "Update all dynamic blocks in the buffer.
9671 This function can be used in a hook."
9672 (interactive)
9673 (when (derived-mode-p 'org-mode)
9674 (org-map-dblocks 'org-update-dblock)))
9677 ;;;; Completion
9679 (declare-function org-export-backend-options "ox" (cl-x) t)
9680 (defun org-get-export-keywords ()
9681 "Return a list of all currently understood export keywords.
9682 Export keywords include options, block names, attributes and
9683 keywords relative to each registered export back-end."
9684 (let (keywords)
9685 (dolist (backend
9686 (bound-and-true-p org-export-registered-backends)
9687 (delq nil keywords))
9688 ;; Back-end name (for keywords, like #+LATEX:)
9689 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
9690 (dolist (option-entry (org-export-backend-options backend))
9691 ;; Back-end options.
9692 (push (nth 1 option-entry) keywords)))))
9694 (defconst org-options-keywords
9695 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
9696 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
9697 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
9698 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
9699 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
9701 (defcustom org-structure-template-alist
9702 '(("a" . "export ascii")
9703 ("c" . "center")
9704 ("C" . "comment")
9705 ("e" . "example")
9706 ("E" . "export")
9707 ("h" . "export html")
9708 ("l" . "export latex")
9709 ("q" . "quote")
9710 ("s" . "src")
9711 ("v" . "verse"))
9712 "An alist of keys and block types.
9713 `org-insert-structure-template' will display a menu with this
9714 list of templates to choose from. The block type is inserted,
9715 with \"#+BEGIN_\" and \"#+END_\" added automatically.
9717 The menu keys are defined by the car of each entry in this alist.
9718 If two entries have the keys \"a\" and \"aa\" respectively, the
9719 former will be inserted by typing \"a TAB/RET/SPC\" and the
9720 latter will be inserted by typing \"aa\". If an entry with the
9721 key \"aab\" is later added, it can be inserted by typing \"ab\".
9723 If loaded, Org Tempo also uses `org-structure-template-alist'. A
9724 block can be inserted by pressing TAB after the string \"<KEY\"."
9725 :group 'org-edit-structure
9726 :type '(repeat
9727 (cons (string :tag "Key")
9728 (string :tag "Template")))
9729 :package-version '(Org . "9.2"))
9731 (defun org--check-org-structure-template-alist (&optional checklist)
9732 "Check whether `org-structure-template-alist' is set up correctly.
9733 In particular, check if the Org 9.2 format is used as opposed to
9734 previous format.
9736 (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
9737 (or (eval checklist)
9738 org-structure-template-alist))))
9739 (when elm
9740 (org-display-warning
9741 (format "
9742 Please update the entries of `%s'.
9744 In Org 9.2 the format was changed from something like
9746 (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
9748 to something like
9750 (\"s\" . \"src\")
9752 Please refer to the documentation of `org-structure-template-alist'.
9754 The following entries must be updated:
9757 (or checklist 'org-structure-template-alist)
9758 (pp-to-string elm))))))
9760 (defun org--insert-structure-template-mks ()
9761 "Present `org-structure-template-alist' with `org-mks'.
9763 Menus are added if keys require more than one keystroke. Tabs
9764 are added to single key entries when more than one stroke is
9765 needed. Keys longer than two characters are reduced to two
9766 characters."
9767 (org--check-org-structure-template-alist)
9768 (let* (case-fold-search
9769 (templates (append org-structure-template-alist
9770 '(("\t" . "Press TAB, RET or SPC to write block name"))))
9771 (keys (mapcar #'car templates))
9772 (start-letters
9773 (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
9774 ;; Sort each element of `org-structure-template-alist' into
9775 ;; sublists according to the first letter.
9776 (superlist
9777 (mapcar (lambda (letter)
9778 (list letter
9779 (cl-remove-if-not
9780 (apply-partially #'string-match-p (concat "^" letter))
9781 templates :key #'car)))
9782 start-letters)))
9783 (org-mks
9784 (apply #'append
9785 ;; Make an `org-mks' table. If only one element is
9786 ;; present in a sublist, make it part of the top-menu,
9787 ;; otherwise make a submenu according to the starting
9788 ;; letter and populate it.
9789 (mapcar (lambda (sublist)
9790 (if (eq 1 (length (cadr sublist)))
9791 (mapcar (lambda (elm)
9792 (list (substring (car elm) 0 1)
9793 (cdr elm) ""))
9794 (cadr sublist))
9795 ;; Create submenu.
9796 (let* ((topkey (car sublist))
9797 (elms (cadr sublist))
9798 (keys (mapcar #'car elms))
9799 (long (> (length elms) 3)))
9800 (append
9801 (list
9802 ;; Make a description of the submenu.
9803 (list topkey
9804 (concat
9805 (mapconcat #'cdr
9806 (cl-subseq elms 0 (if long 3 (length elms)))
9807 ", ")
9808 (when long ", ..."))))
9809 ;; List of entries in submenu.
9810 (cl-mapcar #'list
9811 (org--insert-structure-template-unique-keys keys)
9812 (mapcar #'cdr elms)
9813 (make-list (length elms) ""))))))
9814 superlist))
9815 "Select a key\n============"
9816 "Key: ")))
9818 (defun org--insert-structure-template-unique-keys (keys)
9819 "Make a list of unique, two characters long elements from KEYS.
9821 Elements of length one have a tab appended. Elements of length
9822 two are kept as is. Longer elements are truncated to length two.
9824 If an element cannot be made unique, an error is raised."
9825 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
9826 menu-keys)
9827 (dolist (key orderd-keys)
9828 (let ((potential-key
9829 (cl-case (length key)
9830 (1 (concat key "\t"))
9831 (2 key)
9832 (otherwise
9833 (cl-find-if-not (lambda (k) (assoc k menu-keys))
9834 (mapcar (apply-partially #'concat (substring key 0 1))
9835 (split-string (substring key 1) "" t)))))))
9836 (if (or (not potential-key) (assoc potential-key menu-keys))
9837 (user-error "Could not make unique key for %s." key)
9838 (push (cons potential-key key) menu-keys))))
9839 (mapcar #'car
9840 (cl-sort menu-keys #'<
9841 :key (lambda (elm) (cl-position (cdr elm) keys))))))
9843 (defun org-insert-structure-template (type)
9844 "Insert a block structure of the type #+begin_foo/#+end_foo.
9845 Select a block from `org-structure-template-alist' then type
9846 either RET, TAB or SPC to write the block type. With an active
9847 region, wrap the region in the block. Otherwise, insert an empty
9848 block."
9849 (interactive
9850 (list (pcase (org--insert-structure-template-mks)
9851 (`("\t" . ,_) (read-string "Structure type: "))
9852 (`(,_ ,choice . ,_) choice))))
9853 (let* ((region? (use-region-p))
9854 (region-start (and region? (region-beginning)))
9855 (region-end (and region? (copy-marker (region-end))))
9856 (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
9857 (verbatim? (string-match-p
9858 (concat "\\`" (regexp-opt '("example" "export" "src")))
9859 type)))
9860 (when region? (goto-char region-start))
9861 (let ((column (current-indentation)))
9862 (if (save-excursion (skip-chars-backward " \t") (bolp))
9863 (beginning-of-line)
9864 (insert "\n"))
9865 (save-excursion
9866 (indent-to column)
9867 (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
9868 (when region?
9869 (when verbatim? (org-escape-code-in-region (point) region-end))
9870 (goto-char region-end)
9871 ;; Ignore empty lines at the end of the region.
9872 (skip-chars-backward " \r\t\n")
9873 (end-of-line))
9874 (unless (bolp) (insert "\n"))
9875 (indent-to column)
9876 (insert (format "#+end_%s" (car (split-string type))))
9877 (if (looking-at "[ \t]*$") (replace-match "")
9878 (insert "\n"))
9879 (when (and (eobp) (not (bolp))) (insert "\n")))
9880 (if extended? (end-of-line)
9881 (forward-line)
9882 (skip-chars-forward " \t")))))
9885 ;;;; TODO, DEADLINE, Comments
9887 (defun org-toggle-comment ()
9888 "Change the COMMENT state of an entry."
9889 (interactive)
9890 (save-excursion
9891 (org-back-to-heading)
9892 (let ((case-fold-search nil))
9893 (looking-at org-complex-heading-regexp))
9894 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
9895 (skip-chars-forward " \t")
9896 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
9897 (if (org-in-commented-heading-p t)
9898 (delete-region (point)
9899 (progn (search-forward " " (line-end-position) 'move)
9900 (skip-chars-forward " \t")
9901 (point)))
9902 (insert org-comment-string)
9903 (unless (eolp) (insert " ")))))
9905 (defvar org-last-todo-state-is-todo nil
9906 "This is non-nil when the last TODO state change led to a TODO state.
9907 If the last change removed the TODO tag or switched to DONE, then
9908 this is nil.")
9910 (defvar org-todo-setup-filter-hook nil
9911 "Hook for functions that pre-filter todo specs.
9912 Each function takes a todo spec and returns either nil or the spec
9913 transformed into canonical form." )
9915 (defvar org-todo-get-default-hook nil
9916 "Hook for functions that get a default item for todo.
9917 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9918 nil or a string to be used for the todo mark." )
9920 (defvar org-agenda-headline-snapshot-before-repeat)
9922 (defun org-current-effective-time ()
9923 "Return current time adjusted for `org-extend-today-until' variable."
9924 (let* ((ct (org-current-time))
9925 (dct (decode-time ct))
9926 (ct1
9927 (cond
9928 (org-use-last-clock-out-time-as-effective-time
9929 (or (org-clock-get-last-clock-out-time) ct))
9930 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
9931 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
9932 (t ct))))
9933 ct1))
9935 (defun org-todo-yesterday (&optional arg)
9936 "Like `org-todo' but the time of change will be 23:59 of yesterday."
9937 (interactive "P")
9938 (if (eq major-mode 'org-agenda-mode)
9939 (apply 'org-agenda-todo-yesterday arg)
9940 (let* ((org-use-effective-time t)
9941 (hour (nth 2 (decode-time (org-current-time))))
9942 (org-extend-today-until (1+ hour)))
9943 (org-todo arg))))
9945 (defvar org-block-entry-blocking ""
9946 "First entry preventing the TODO state change.")
9948 (defun org-cancel-repeater ()
9949 "Cancel a repeater by setting its numeric value to zero."
9950 (interactive)
9951 (save-excursion
9952 (org-back-to-heading t)
9953 (let ((bound1 (point))
9954 (bound0 (save-excursion (outline-next-heading) (point))))
9955 (when (and (re-search-forward
9956 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9957 org-deadline-time-regexp "\\)\\|\\("
9958 org-ts-regexp "\\)")
9959 bound0 t)
9960 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
9961 bound1 t))
9962 (replace-match "0" t nil nil 1)))))
9964 (defvar org-state)
9965 (defvar org-blocked-by-checkboxes)
9966 (defun org-todo (&optional arg)
9967 "Change the TODO state of an item.
9969 The state of an item is given by a keyword at the start of the heading,
9970 like
9971 *** TODO Write paper
9972 *** DONE Call mom
9974 The different keywords are specified in the variable `org-todo-keywords'.
9975 By default the available states are \"TODO\" and \"DONE\". So, for this
9976 example: when the item starts with TODO, it is changed to DONE.
9977 When it starts with DONE, the DONE is removed. And when neither TODO nor
9978 DONE are present, add TODO at the beginning of the heading.
9980 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
9981 state.
9982 With numeric prefix ARG, switch to that state.
9983 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
9984 next set of TODO \
9985 keywords (nextset).
9986 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9987 prefix, circumvent any state blocking.
9988 With a numeric prefix arg of 0, inhibit note taking for the change.
9989 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
9991 When called through ELisp, arg is also interpreted in the following way:
9992 `none' -> empty state
9993 \"\" -> switch to empty state
9994 `done' -> switch to DONE
9995 `nextset' -> switch to the next set of keywords
9996 `previousset' -> switch to the previous set of keywords
9997 \"WAITING\" -> switch to the specified keyword, but only if it
9998 really is a member of `org-todo-keywords'."
9999 (interactive "P")
10000 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
10001 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
10002 'region-start-level 'region))
10003 org-loop-over-headlines-in-active-region)
10004 (org-map-entries
10005 `(org-todo ,arg)
10006 org-loop-over-headlines-in-active-region
10007 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
10008 (when (equal arg '(16)) (setq arg 'nextset))
10009 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
10010 (let ((org-blocker-hook org-blocker-hook)
10011 commentp
10012 case-fold-search)
10013 (when (equal arg '(64))
10014 (setq arg nil org-blocker-hook nil))
10015 (when (and org-blocker-hook
10016 (or org-inhibit-blocking
10017 (org-entry-get nil "NOBLOCKING")))
10018 (setq org-blocker-hook nil))
10019 (save-excursion
10020 (catch 'exit
10021 (org-back-to-heading t)
10022 (when (org-in-commented-heading-p t)
10023 (org-toggle-comment)
10024 (setq commentp t))
10025 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
10026 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
10027 (looking-at "\\(?: *\\|[ \t]*$\\)"))
10028 (let* ((match-data (match-data))
10029 (startpos (copy-marker (line-beginning-position)))
10030 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10031 (org-log-done org-log-done)
10032 (org-log-repeat org-log-repeat)
10033 (org-todo-log-states org-todo-log-states)
10034 (org-inhibit-logging
10035 (if (equal arg 0)
10036 (progn (setq arg nil) 'note) org-inhibit-logging))
10037 (this (match-string 1))
10038 (hl-pos (match-beginning 0))
10039 (head (org-get-todo-sequence-head this))
10040 (ass (assoc head org-todo-kwd-alist))
10041 (interpret (nth 1 ass))
10042 (done-word (nth 3 ass))
10043 (final-done-word (nth 4 ass))
10044 (org-last-state (or this ""))
10045 (completion-ignore-case t)
10046 (member (member this org-todo-keywords-1))
10047 (tail (cdr member))
10048 (org-state (cond
10049 ((and org-todo-key-trigger
10050 (or (and (equal arg '(4))
10051 (eq org-use-fast-todo-selection 'prefix))
10052 (and (not arg) org-use-fast-todo-selection
10053 (not (eq org-use-fast-todo-selection
10054 'prefix)))))
10055 ;; Use fast selection.
10056 (org-fast-todo-selection))
10057 ((and (equal arg '(4))
10058 (or (not org-use-fast-todo-selection)
10059 (not org-todo-key-trigger)))
10060 ;; Read a state with completion.
10061 (completing-read
10062 "State: " (mapcar #'list org-todo-keywords-1)
10063 nil t))
10064 ((eq arg 'right)
10065 (if this
10066 (if tail (car tail) nil)
10067 (car org-todo-keywords-1)))
10068 ((eq arg 'left)
10069 (unless (equal member org-todo-keywords-1)
10070 (if this
10071 (nth (- (length org-todo-keywords-1)
10072 (length tail) 2)
10073 org-todo-keywords-1)
10074 (org-last org-todo-keywords-1))))
10075 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10076 (setq arg nil))) ;hack to fall back to cycling
10077 (arg
10078 ;; User or caller requests a specific state.
10079 (cond
10080 ((equal arg "") nil)
10081 ((eq arg 'none) nil)
10082 ((eq arg 'done) (or done-word (car org-done-keywords)))
10083 ((eq arg 'nextset)
10084 (or (car (cdr (member head org-todo-heads)))
10085 (car org-todo-heads)))
10086 ((eq arg 'previousset)
10087 (let ((org-todo-heads (reverse org-todo-heads)))
10088 (or (car (cdr (member head org-todo-heads)))
10089 (car org-todo-heads))))
10090 ((car (member arg org-todo-keywords-1)))
10091 ((stringp arg)
10092 (user-error "State `%s' not valid in this file" arg))
10093 ((nth (1- (prefix-numeric-value arg))
10094 org-todo-keywords-1))))
10095 ((null member) (or head (car org-todo-keywords-1)))
10096 ((equal this final-done-word) nil) ;-> make empty
10097 ((null tail) nil) ;-> first entry
10098 ((memq interpret '(type priority))
10099 (if (eq this-command last-command)
10100 (car tail)
10101 (if (> (length tail) 0)
10102 (or done-word (car org-done-keywords))
10103 nil)))
10105 (car tail))))
10106 (org-state (or
10107 (run-hook-with-args-until-success
10108 'org-todo-get-default-hook org-state org-last-state)
10109 org-state))
10110 (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
10111 (change-plist (list :type 'todo-state-change :from this :to org-state
10112 :position startpos))
10113 dolog now-done-p)
10114 (when org-blocker-hook
10115 (let (org-blocked-by-checkboxes block-reason)
10116 (setq org-last-todo-state-is-todo
10117 (not (member this org-done-keywords)))
10118 (unless (save-excursion
10119 (save-match-data
10120 (org-with-wide-buffer
10121 (run-hook-with-args-until-failure
10122 'org-blocker-hook change-plist))))
10123 (setq block-reason (if org-blocked-by-checkboxes
10124 "contained checkboxes"
10125 (format "\"%s\"" org-block-entry-blocking)))
10126 (if (called-interactively-p 'interactive)
10127 (user-error "TODO state change from %s to %s blocked (by %s)"
10128 this org-state block-reason)
10129 ;; Fail silently.
10130 (message "TODO state change from %s to %s blocked (by %s)"
10131 this org-state block-reason)
10132 (throw 'exit nil)))))
10133 (store-match-data match-data)
10134 (replace-match next t t)
10135 (cond ((equal this org-state)
10136 (message "TODO state was already %s" (org-trim next)))
10137 ((not (pos-visible-in-window-p hl-pos))
10138 (message "TODO state changed to %s" (org-trim next))))
10139 (unless head
10140 (setq head (org-get-todo-sequence-head org-state)
10141 ass (assoc head org-todo-kwd-alist)
10142 interpret (nth 1 ass)
10143 done-word (nth 3 ass)
10144 final-done-word (nth 4 ass)))
10145 (when (memq arg '(nextset previousset))
10146 (message "Keyword-Set %d/%d: %s"
10147 (- (length org-todo-sets) -1
10148 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
10149 (length org-todo-sets)
10150 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
10151 (setq org-last-todo-state-is-todo
10152 (not (member org-state org-done-keywords)))
10153 (setq now-done-p (and (member org-state org-done-keywords)
10154 (not (member this org-done-keywords))))
10155 (and logging (org-local-logging logging))
10156 (when (and (or org-todo-log-states org-log-done)
10157 (not (eq org-inhibit-logging t))
10158 (not (memq arg '(nextset previousset))))
10159 ;; We need to look at recording a time and note.
10160 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
10161 (nth 2 (assoc this org-todo-log-states))))
10162 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10163 (setq dolog 'time))
10164 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
10165 (and org-state
10166 (member org-state org-not-done-keywords)
10167 (not (member this org-not-done-keywords))))
10168 ;; This is now a todo state and was not one before
10169 ;; If there was a CLOSED time stamp, get rid of it.
10170 (org-add-planning-info nil nil 'closed))
10171 (when (and now-done-p org-log-done)
10172 ;; It is now done, and it was not done before.
10173 (org-add-planning-info 'closed (org-current-effective-time))
10174 (when (and (not dolog) (eq 'note org-log-done))
10175 (org-add-log-setup 'done org-state this 'note)))
10176 (when (and org-state dolog)
10177 ;; This is a non-nil state, and we need to log it.
10178 (org-add-log-setup 'state org-state this dolog)))
10179 ;; Fixup tag positioning.
10180 (org-todo-trigger-tag-changes org-state)
10181 (when org-auto-align-tags (org-align-tags))
10182 (when org-provide-todo-statistics
10183 (org-update-parent-todo-statistics))
10184 (when (bound-and-true-p org-clock-out-when-done)
10185 (org-clock-out-if-current))
10186 (run-hooks 'org-after-todo-state-change-hook)
10187 (when (and arg (not (member org-state org-done-keywords)))
10188 (setq head (org-get-todo-sequence-head org-state)))
10189 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10190 ;; Do we need to trigger a repeat?
10191 (when now-done-p
10192 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10193 ;; This is for the agenda, take a snapshot of the headline.
10194 (save-match-data
10195 (setq org-agenda-headline-snapshot-before-repeat
10196 (org-get-heading))))
10197 (org-auto-repeat-maybe org-state))
10198 ;; Fixup cursor location if close to the keyword.
10199 (when (and (outline-on-heading-p)
10200 (not (bolp))
10201 (save-excursion (beginning-of-line 1)
10202 (looking-at org-todo-line-regexp))
10203 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10204 (goto-char (or (match-end 2) (match-end 1)))
10205 (and (looking-at " ") (just-one-space)))
10206 (when org-trigger-hook
10207 (save-excursion
10208 (run-hook-with-args 'org-trigger-hook change-plist)))
10209 (when commentp (org-toggle-comment))))))))
10211 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10212 "Block turning an entry into a TODO, using the hierarchy.
10213 This checks whether the current task should be blocked from state
10214 changes. Such blocking occurs when:
10216 1. The task has children which are not all in a completed state.
10218 2. A task has a parent with the property :ORDERED:, and there
10219 are siblings prior to the current task with incomplete
10220 status.
10222 3. The parent of the task is blocked because it has siblings that should
10223 be done first, or is child of a block grandparent TODO entry."
10225 (if (not org-enforce-todo-dependencies)
10226 t ; if locally turned off don't block
10227 (catch 'dont-block
10228 ;; If this is not a todo state change, or if this entry is already DONE,
10229 ;; do not block
10230 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10231 (member (plist-get change-plist :from)
10232 (cons 'done org-done-keywords))
10233 (member (plist-get change-plist :to)
10234 (cons 'todo org-not-done-keywords))
10235 (not (plist-get change-plist :to)))
10236 (throw 'dont-block t))
10237 ;; If this task has children, and any are undone, it's blocked
10238 (save-excursion
10239 (org-back-to-heading t)
10240 (let ((this-level (funcall outline-level)))
10241 (outline-next-heading)
10242 (let ((child-level (funcall outline-level)))
10243 (while (and (not (eobp))
10244 (> child-level this-level))
10245 ;; this todo has children, check whether they are all
10246 ;; completed
10247 (when (and (not (org-entry-is-done-p))
10248 (org-entry-is-todo-p))
10249 (setq org-block-entry-blocking (org-get-heading))
10250 (throw 'dont-block nil))
10251 (outline-next-heading)
10252 (setq child-level (funcall outline-level))))))
10253 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10254 ;; any previous siblings are undone, it's blocked
10255 (save-excursion
10256 (org-back-to-heading t)
10257 (let* ((pos (point))
10258 (parent-pos (and (org-up-heading-safe) (point)))
10259 (case-fold-search nil))
10260 (unless parent-pos (throw 'dont-block t)) ; no parent
10261 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10262 (forward-line 1)
10263 (re-search-forward org-not-done-heading-regexp pos t))
10264 (setq org-block-entry-blocking (match-string 0))
10265 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10266 ;; Search further up the hierarchy, to see if an ancestor is blocked
10267 (while t
10268 (goto-char parent-pos)
10269 (unless (looking-at org-not-done-heading-regexp)
10270 (throw 'dont-block t)) ; do not block, parent is not a TODO
10271 (setq pos (point))
10272 (setq parent-pos (and (org-up-heading-safe) (point)))
10273 (unless parent-pos (throw 'dont-block t)) ; no parent
10274 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10275 (forward-line 1)
10276 (re-search-forward org-not-done-heading-regexp pos t)
10277 (setq org-block-entry-blocking (org-get-heading)))
10278 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10280 (defcustom org-track-ordered-property-with-tag nil
10281 "Should the ORDERED property also be shown as a tag?
10282 The ORDERED property decides if an entry should require subtasks to be
10283 completed in sequence. Since a property is not very visible, setting
10284 this option means that toggling the ORDERED property with the command
10285 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10286 not relevant for the behavior, but it makes things more visible.
10288 Note that toggling the tag with tags commands will not change the property
10289 and therefore not influence behavior!
10291 This can be t, meaning the tag ORDERED should be used, It can also be a
10292 string to select a different tag for this task."
10293 :group 'org-todo
10294 :type '(choice
10295 (const :tag "No tracking" nil)
10296 (const :tag "Track with ORDERED tag" t)
10297 (string :tag "Use other tag")))
10299 (defun org-toggle-ordered-property ()
10300 "Toggle the ORDERED property of the current entry.
10301 For better visibility, you can track the value of this property with a tag.
10302 See variable `org-track-ordered-property-with-tag'."
10303 (interactive)
10304 (let* ((t1 org-track-ordered-property-with-tag)
10305 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10306 (save-excursion
10307 (org-back-to-heading)
10308 (if (org-entry-get nil "ORDERED")
10309 (progn
10310 (org-delete-property "ORDERED")
10311 (and tag (org-toggle-tag tag 'off))
10312 (message "Subtasks can be completed in arbitrary order"))
10313 (org-entry-put nil "ORDERED" "t")
10314 (and tag (org-toggle-tag tag 'on))
10315 (message "Subtasks must be completed in sequence")))))
10317 (defun org-block-todo-from-checkboxes (change-plist)
10318 "Block turning an entry into a TODO, using checkboxes.
10319 This checks whether the current task should be blocked from state
10320 changes because there are unchecked boxes in this entry."
10321 (if (not org-enforce-todo-checkbox-dependencies)
10322 t ; if locally turned off don't block
10323 (catch 'dont-block
10324 ;; If this is not a todo state change, or if this entry is already DONE,
10325 ;; do not block
10326 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10327 (member (plist-get change-plist :from)
10328 (cons 'done org-done-keywords))
10329 (member (plist-get change-plist :to)
10330 (cons 'todo org-not-done-keywords))
10331 (not (plist-get change-plist :to)))
10332 (throw 'dont-block t))
10333 ;; If this task has checkboxes that are not checked, it's blocked
10334 (save-excursion
10335 (org-back-to-heading t)
10336 (let ((beg (point)) end)
10337 (outline-next-heading)
10338 (setq end (point))
10339 (goto-char beg)
10340 (when (org-list-search-forward
10341 (concat (org-item-beginning-re)
10342 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
10343 "\\[[- ]\\]")
10344 end t)
10345 (when (boundp 'org-blocked-by-checkboxes)
10346 (setq org-blocked-by-checkboxes t))
10347 (throw 'dont-block nil))))
10348 t))) ; do not block
10350 (defun org-entry-blocked-p ()
10351 "Non-nil if entry at point is blocked."
10352 (and (not (org-entry-get nil "NOBLOCKING"))
10353 (member (org-entry-get nil "TODO") org-not-done-keywords)
10354 (not (run-hook-with-args-until-failure
10355 'org-blocker-hook
10356 (list :type 'todo-state-change
10357 :position (point)
10358 :from 'todo
10359 :to 'done)))))
10361 (defun org-update-statistics-cookies (all)
10362 "Update the statistics cookie, either from TODO or from checkboxes.
10363 This should be called with the cursor in a line with a statistics
10364 cookie. When called with a \\[universal-argument] prefix, update
10365 all statistics cookies in the buffer."
10366 (interactive "P")
10367 (if all
10368 (progn
10369 (org-update-checkbox-count 'all)
10370 (org-map-entries 'org-update-parent-todo-statistics))
10371 (if (not (org-at-heading-p))
10372 (org-update-checkbox-count)
10373 (let ((pos (point-marker))
10374 end l1 l2)
10375 (ignore-errors (org-back-to-heading t))
10376 (if (not (org-at-heading-p))
10377 (org-update-checkbox-count)
10378 (setq l1 (org-outline-level))
10379 (setq end (save-excursion
10380 (outline-next-heading)
10381 (when (org-at-heading-p) (setq l2 (org-outline-level)))
10382 (point)))
10383 (if (and (save-excursion
10384 (re-search-forward
10385 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10386 (not (save-excursion (re-search-forward
10387 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10388 (org-update-checkbox-count)
10389 (if (and l2 (> l2 l1))
10390 (progn
10391 (goto-char end)
10392 (org-update-parent-todo-statistics))
10393 (goto-char pos)
10394 (beginning-of-line 1)
10395 (while (re-search-forward
10396 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10397 (point-at-eol) t)
10398 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10399 (goto-char pos)
10400 (move-marker pos nil)))))
10402 (defvar org-entry-property-inherited-from) ;; defined below
10403 (defun org-update-parent-todo-statistics ()
10404 "Update any statistics cookie in the parent of the current headline.
10405 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10406 the entire subtree and this will travel up the hierarchy and update
10407 statistics everywhere."
10408 (let* ((prop (save-excursion (org-up-heading-safe)
10409 (org-entry-get nil "COOKIE_DATA" 'inherit)))
10410 (recursive (or (not org-hierarchical-todo-statistics)
10411 (and prop (string-match "\\<recursive\\>" prop))))
10412 (lim (or (and prop (marker-position org-entry-property-inherited-from))
10414 (first t)
10415 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10416 level ltoggle l1 new ndel
10417 (cnt-all 0) (cnt-done 0) is-percent kwd
10418 checkbox-beg cookie-present)
10419 (catch 'exit
10420 (save-excursion
10421 (beginning-of-line 1)
10422 (setq ltoggle (funcall outline-level))
10423 ;; Three situations are to consider:
10425 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
10426 ;; to the top-level ancestor on the headline;
10428 ;; 2. If parent has "recursive" property, repeat up to the
10429 ;; headline setting that property, taking inheritance into
10430 ;; account;
10432 ;; 3. Else, move up to direct parent and proceed only once.
10433 (while (and (setq level (org-up-heading-safe))
10434 (or recursive first)
10435 (>= (point) lim))
10436 (setq first nil cookie-present nil)
10437 (unless (and level
10438 (not (string-match
10439 "\\<checkbox\\>"
10440 (downcase (or (org-entry-get nil "COOKIE_DATA")
10441 "")))))
10442 (throw 'exit nil))
10443 (while (re-search-forward box-re (point-at-eol) t)
10444 (setq cnt-all 0 cnt-done 0 cookie-present t)
10445 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
10446 (save-match-data
10447 (unless (outline-next-heading) (throw 'exit nil))
10448 (while (and (looking-at org-complex-heading-regexp)
10449 (> (setq l1 (length (match-string 1))) level))
10450 (setq kwd (and (or recursive (= l1 ltoggle))
10451 (match-string 2)))
10452 (if (or (eq org-provide-todo-statistics 'all-headlines)
10453 (and (eq org-provide-todo-statistics t)
10454 (or (member kwd org-done-keywords)))
10455 (and (listp org-provide-todo-statistics)
10456 (stringp (car org-provide-todo-statistics))
10457 (or (member kwd org-provide-todo-statistics)
10458 (member kwd org-done-keywords)))
10459 (and (listp org-provide-todo-statistics)
10460 (listp (car org-provide-todo-statistics))
10461 (or (member kwd (car org-provide-todo-statistics))
10462 (and (member kwd org-done-keywords)
10463 (member kwd (cadr org-provide-todo-statistics))))))
10464 (setq cnt-all (1+ cnt-all))
10465 (and (eq org-provide-todo-statistics t)
10467 (setq cnt-all (1+ cnt-all))))
10468 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
10469 (member kwd org-done-keywords))
10470 (and (listp org-provide-todo-statistics)
10471 (listp (car org-provide-todo-statistics))
10472 (member kwd org-done-keywords)
10473 (member kwd (cadr org-provide-todo-statistics)))
10474 (and (listp org-provide-todo-statistics)
10475 (stringp (car org-provide-todo-statistics))
10476 (member kwd org-done-keywords)))
10477 (setq cnt-done (1+ cnt-done)))
10478 (outline-next-heading)))
10479 (setq new
10480 (if is-percent
10481 (format "[%d%%]" (floor (* 100.0 cnt-done)
10482 (max 1 cnt-all)))
10483 (format "[%d/%d]" cnt-done cnt-all))
10484 ndel (- (match-end 0) checkbox-beg))
10485 (goto-char checkbox-beg)
10486 (insert new)
10487 (delete-region (point) (+ (point) ndel))
10488 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
10489 (when cookie-present
10490 (run-hook-with-args 'org-after-todo-statistics-hook
10491 cnt-done (- cnt-all cnt-done))))))
10492 (run-hooks 'org-todo-statistics-hook)))
10494 (defvar org-after-todo-statistics-hook nil
10495 "Hook that is called after a TODO statistics cookie has been updated.
10496 Each function is called with two arguments: the number of not-done entries
10497 and the number of done entries.
10499 For example, the following function, when added to this hook, will switch
10500 an entry to DONE when all children are done, and back to TODO when new
10501 entries are set to a TODO status. Note that this hook is only called
10502 when there is a statistics cookie in the headline!
10504 (defun org-summary-todo (n-done n-not-done)
10505 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10506 (let (org-log-done org-log-states) ; turn off logging
10507 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10510 (defvar org-todo-statistics-hook nil
10511 "Hook that is run whenever Org thinks TODO statistics should be updated.
10512 This hook runs even if there is no statistics cookie present, in which case
10513 `org-after-todo-statistics-hook' would not run.")
10515 (defun org-todo-trigger-tag-changes (state)
10516 "Apply the changes defined in `org-todo-state-tags-triggers'."
10517 (let ((l org-todo-state-tags-triggers)
10518 changes)
10519 (when (or (not state) (equal state ""))
10520 (setq changes (append changes (cdr (assoc "" l)))))
10521 (when (and (stringp state) (> (length state) 0))
10522 (setq changes (append changes (cdr (assoc state l)))))
10523 (when (member state org-not-done-keywords)
10524 (setq changes (append changes (cdr (assq 'todo l)))))
10525 (when (member state org-done-keywords)
10526 (setq changes (append changes (cdr (assq 'done l)))))
10527 (dolist (c changes)
10528 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10530 (defun org-local-logging (value)
10531 "Get logging settings from a property VALUE."
10532 ;; Directly set the variables, they are already local.
10533 (setq org-log-done nil
10534 org-log-repeat nil
10535 org-todo-log-states nil)
10536 (dolist (w (split-string value))
10537 (let (a)
10538 (cond
10539 ((setq a (assoc w org-startup-options))
10540 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10541 (set (nth 1 a) (nth 2 a))))
10542 ((setq a (org-extract-log-state-settings w))
10543 (and (member (car a) org-todo-keywords-1)
10544 (push a org-todo-log-states)))))))
10546 (defun org-get-todo-sequence-head (kwd)
10547 "Return the head of the TODO sequence to which KWD belongs.
10548 If KWD is not set, check if there is a text property remembering the
10549 right sequence."
10550 (let (p)
10551 (cond
10552 ((not kwd)
10553 (or (get-text-property (point-at-bol) 'org-todo-head)
10554 (progn
10555 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10556 nil (point-at-eol)))
10557 (get-text-property p 'org-todo-head))))
10558 ((not (member kwd org-todo-keywords-1))
10559 (car org-todo-keywords-1))
10560 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10562 (defun org-fast-todo-selection ()
10563 "Fast TODO keyword selection with single keys.
10564 Returns the new TODO keyword, or nil if no state change should occur."
10565 (let* ((fulltable org-todo-key-alist)
10566 (done-keywords org-done-keywords) ;; needed for the faces.
10567 (maxlen (apply 'max (mapcar
10568 (lambda (x)
10569 (if (stringp (car x)) (string-width (car x)) 0))
10570 fulltable)))
10571 (expert nil)
10572 (fwidth (+ maxlen 3 1 3))
10573 (ncol (/ (- (window-width) 4) fwidth))
10574 tg cnt e c tbl
10575 groups ingroup)
10576 (save-excursion
10577 (save-window-excursion
10578 (if expert
10579 (set-buffer (get-buffer-create " *Org todo*"))
10580 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10581 (erase-buffer)
10582 (setq-local org-done-keywords done-keywords)
10583 (setq tbl fulltable cnt 0)
10584 (while (setq e (pop tbl))
10585 (cond
10586 ((equal e '(:startgroup))
10587 (push '() groups) (setq ingroup t)
10588 (unless (= cnt 0)
10589 (setq cnt 0)
10590 (insert "\n"))
10591 (insert "{ "))
10592 ((equal e '(:endgroup))
10593 (setq ingroup nil cnt 0)
10594 (insert "}\n"))
10595 ((equal e '(:newline))
10596 (unless (= cnt 0)
10597 (setq cnt 0)
10598 (insert "\n")
10599 (setq e (car tbl))
10600 (while (equal (car tbl) '(:newline))
10601 (insert "\n")
10602 (setq tbl (cdr tbl)))))
10604 (setq tg (car e) c (cdr e))
10605 (when ingroup (push tg (car groups)))
10606 (setq tg (org-add-props tg nil 'face
10607 (org-get-todo-face tg)))
10608 (when (and (= cnt 0) (not ingroup)) (insert " "))
10609 (insert "[" c "] " tg (make-string
10610 (- fwidth 4 (length tg)) ?\ ))
10611 (when (and (= (setq cnt (1+ cnt)) ncol)
10612 ;; Avoid lines with just a closing delimiter.
10613 (not (equal (car tbl) '(:endgroup))))
10614 (insert "\n")
10615 (when ingroup (insert " "))
10616 (setq cnt 0)))))
10617 (insert "\n")
10618 (goto-char (point-min))
10619 (unless expert (org-fit-window-to-buffer))
10620 (message "[a-z..]:Set [SPC]:clear")
10621 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10622 (cond
10623 ((or (= c ?\C-g)
10624 (and (= c ?q) (not (rassoc c fulltable))))
10625 (setq quit-flag t))
10626 ((= c ?\ ) nil)
10627 ((setq e (rassoc c fulltable) tg (car e))
10629 (t (setq quit-flag t)))))))
10631 (defun org-entry-is-todo-p ()
10632 (member (org-get-todo-state) org-not-done-keywords))
10634 (defun org-entry-is-done-p ()
10635 (member (org-get-todo-state) org-done-keywords))
10637 (defun org-get-todo-state ()
10638 "Return the TODO keyword of the current subtree."
10639 (save-excursion
10640 (org-back-to-heading t)
10641 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
10642 (match-end 2)
10643 (match-string 2))))
10645 (defun org-at-date-range-p (&optional inactive-ok)
10646 "Non-nil if point is inside a date range.
10648 When optional argument INACTIVE-OK is non-nil, also consider
10649 inactive time ranges.
10651 When this function returns a non-nil value, match data is set
10652 according to `org-tr-regexp-both' or `org-tr-regexp', depending
10653 on INACTIVE-OK."
10654 (interactive)
10655 (save-excursion
10656 (catch 'exit
10657 (let ((pos (point)))
10658 (skip-chars-backward "^[<\r\n")
10659 (skip-chars-backward "<[")
10660 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10661 (>= (match-end 0) pos)
10662 (throw 'exit t))
10663 (skip-chars-backward "^<[\r\n")
10664 (skip-chars-backward "<[")
10665 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10666 (>= (match-end 0) pos)
10667 (throw 'exit t)))
10668 nil)))
10670 (defun org-get-repeat (&optional timestamp)
10671 "Check if there is a time-stamp with repeater in this entry.
10673 Return the repeater, as a string, or nil. Also return nil when
10674 this function is called before first heading.
10676 When optional argument TIMESTAMP is a string, extract the
10677 repeater from there instead."
10678 (save-match-data
10679 (cond (timestamp
10680 (and (string-match org-repeat-re timestamp)
10681 (match-string-no-properties 1 timestamp)))
10682 ((org-before-first-heading-p) nil)
10684 (save-excursion
10685 (org-back-to-heading t)
10686 (let ((end (org-entry-end-position)))
10687 (catch :repeat
10688 (while (re-search-forward org-repeat-re end t)
10689 (when (save-match-data (org-at-timestamp-p 'agenda))
10690 (throw :repeat (match-string-no-properties 1)))))))))))
10692 (defvar org-last-changed-timestamp)
10693 (defvar org-last-inserted-timestamp)
10694 (defvar org-log-post-message)
10695 (defvar org-log-note-purpose)
10696 (defvar org-log-note-how nil)
10697 (defvar org-log-note-extra)
10698 (defun org-auto-repeat-maybe (done-word)
10699 "Check if the current headline contains a repeated time-stamp.
10701 If yes, set TODO state back to what it was and change the base date
10702 of repeating deadline/scheduled time stamps to new date.
10704 This function is run automatically after each state change to a DONE state."
10705 (let* ((repeat (org-get-repeat))
10706 (aa (assoc org-last-state org-todo-kwd-alist))
10707 (interpret (nth 1 aa))
10708 (head (nth 2 aa))
10709 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
10710 (msg "Entry repeats: ")
10711 (org-log-done nil)
10712 (org-todo-log-states nil)
10713 (end (copy-marker (org-entry-end-position))))
10714 (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
10715 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
10716 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
10717 (and (stringp org-todo-repeat-to-state)
10718 org-todo-repeat-to-state)
10719 (and org-todo-repeat-to-state org-last-state))))
10720 (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
10721 to-state)
10722 ((eq interpret 'type) org-last-state)
10723 (head)
10724 (t 'none))))
10725 (org-back-to-heading t)
10726 (org-add-planning-info nil nil 'closed)
10727 ;; When `org-log-repeat' is non-nil or entry contains
10728 ;; a clock, set LAST_REPEAT property.
10729 (when (or org-log-repeat
10730 (catch :clock
10731 (save-excursion
10732 (while (re-search-forward org-clock-line-re end t)
10733 (when (org-at-clock-log-p) (throw :clock t))))))
10734 (org-entry-put nil "LAST_REPEAT" (format-time-string
10735 (org-time-stamp-format t t))))
10736 (when org-log-repeat
10737 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10738 (memq 'org-add-log-note post-command-hook))
10739 ;; We are already setup for some record.
10740 (when (eq org-log-repeat 'note)
10741 ;; Make sure we take a note, not only a time stamp.
10742 (setq org-log-note-how 'note))
10743 ;; Set up for taking a record.
10744 (org-add-log-setup 'state
10745 (or done-word (car org-done-keywords))
10746 org-last-state
10747 org-log-repeat)))
10748 ;; Time-stamps without a repeater are usually skipped. However,
10749 ;; a SCHEDULED time-stamp without one is removed, as they are no
10750 ;; longer relevant.
10751 (save-excursion
10752 (let ((scheduled (org-entry-get (point) "SCHEDULED")))
10753 (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
10754 (org-remove-timestamp-with-keyword org-scheduled-string))))
10755 ;; Update every time-stamp with a repeater in the entry.
10756 (let ((planning-re (regexp-opt
10757 (list org-scheduled-string org-deadline-string))))
10758 (while (re-search-forward org-repeat-re end t)
10759 (let* ((ts (match-string 0))
10760 (type (if (not (org-at-planning-p)) "Plain:"
10761 (save-excursion
10762 (re-search-backward
10763 planning-re (line-beginning-position) t)
10764 (match-string 0)))))
10765 (when (and (org-at-timestamp-p 'agenda)
10766 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
10767 (let ((n (string-to-number (match-string 2 ts)))
10768 (what (match-string 3 ts)))
10769 (when (equal what "w") (setq n (* n 7) what "d"))
10770 (when (and (equal what "h")
10771 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
10772 ts)))
10773 (user-error
10774 "Cannot repeat in %d hour(s) because no hour has been set"
10776 ;; Preparation, see if we need to modify the start
10777 ;; date for the change.
10778 (when (match-end 1)
10779 (let ((time (save-match-data (org-time-string-to-time ts)))
10780 (repeater-type (match-string 1 ts)))
10781 (cond
10782 ((equal "." repeater-type)
10783 ;; Shift starting date to today.
10784 (org-timestamp-change (- (org-today) (time-to-days time))
10785 'day))
10786 ((equal "+" repeater-type)
10787 (let ((nshiftmax 10)
10788 (nshift 0))
10789 (while (or (= nshift 0)
10790 (not (time-less-p (current-time) time)))
10791 (when (= nshiftmax (cl-incf nshift))
10792 (or (y-or-n-p
10793 (format "%d repeater intervals were not \
10794 enough to shift date past today. Continue? "
10795 nshift))
10796 (user-error "Abort")))
10797 (org-timestamp-change n (cdr (assoc what whata)))
10798 (org-in-regexp org-ts-regexp3)
10799 (setq ts (match-string 1))
10800 (setq time
10801 (save-match-data
10802 (org-time-string-to-time ts)))))
10803 (org-timestamp-change (- n) (cdr (assoc what whata)))
10804 ;; Rematch, so that we have everything in place
10805 ;; for the real shift.
10806 (org-in-regexp org-ts-regexp3)
10807 (setq ts (match-string 1))
10808 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
10809 ts)))))
10810 (save-excursion
10811 (org-timestamp-change n (cdr (assoc what whata)) nil t))
10812 (setq msg
10813 (concat msg type " " org-last-changed-timestamp " ")))))))
10814 (run-hooks 'org-todo-repeat-hook)
10815 (setq org-log-post-message msg)
10816 (message msg))))
10818 (defun org-show-todo-tree (arg)
10819 "Make a compact tree which shows all headlines marked with TODO.
10820 The tree will show the lines where the regexp matches, and all higher
10821 headlines above the match.
10822 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
10823 With a numeric prefix N, construct a sparse tree for the Nth element
10824 of `org-todo-keywords-1'."
10825 (interactive "P")
10826 (let ((case-fold-search nil)
10827 (kwd-re
10828 (cond ((null arg) (concat org-not-done-regexp "\\s-"))
10829 ((equal arg '(4))
10830 (let ((kwd
10831 (completing-read "Keyword (or KWD1|KWD2|...): "
10832 (mapcar #'list org-todo-keywords-1))))
10833 (concat "\\("
10834 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10835 "\\)\\>")))
10836 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10837 (regexp-quote (nth (1- (prefix-numeric-value arg))
10838 org-todo-keywords-1)))
10839 (t (user-error "Invalid prefix argument: %s" arg)))))
10840 (message "%d TODO entries found"
10841 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
10843 (defun org--deadline-or-schedule (arg type time)
10844 "Insert DEADLINE or SCHEDULE information in current entry.
10845 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
10846 `org-schedule' for information about ARG and TIME arguments."
10847 (let* ((deadline? (eq type 'deadline))
10848 (keyword (if deadline? org-deadline-string org-scheduled-string))
10849 (log (if deadline? org-log-redeadline org-log-reschedule))
10850 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
10851 (old-date-time (and old-date (org-time-string-to-time old-date)))
10852 ;; Save repeater cookie from either TIME or current scheduled
10853 ;; time stamp. We are going to insert it back at the end of
10854 ;; the process.
10855 (repeater (or (and (org-string-nw-p time)
10856 ;; We use `org-repeat-re' because we need
10857 ;; to tell the difference between a real
10858 ;; repeater and a time delta, e.g. "+2d".
10859 (string-match org-repeat-re time)
10860 (match-string 1 time))
10861 (and (org-string-nw-p old-date)
10862 (string-match "\\([.+-]+[0-9]+[hdwmy]\
10863 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
10864 old-date)
10865 (match-string 1 old-date)))))
10866 (pcase arg
10867 (`(4)
10868 (if (not old-date)
10869 (message (if deadline? "Entry had no deadline to remove"
10870 "Entry was not scheduled"))
10871 (when (and old-date log)
10872 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
10873 nil old-date log))
10874 (org-remove-timestamp-with-keyword keyword)
10875 (message (if deadline? "Entry no longer has a deadline."
10876 "Entry is no longer scheduled."))))
10877 (`(16)
10878 (save-excursion
10879 (org-back-to-heading t)
10880 (let ((regexp (if deadline? org-deadline-time-regexp
10881 org-scheduled-time-regexp)))
10882 (if (not (re-search-forward regexp (line-end-position 2) t))
10883 (user-error (if deadline? "No deadline information to update"
10884 "No scheduled information to update"))
10885 (let* ((rpl0 (match-string 1))
10886 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
10887 (msg (if deadline? "Warn starting from" "Delay until")))
10888 (replace-match
10889 (concat keyword
10890 " <" rpl
10891 (format " -%dd"
10892 (abs (- (time-to-days
10893 (save-match-data
10894 (org-read-date
10895 nil t nil msg old-date-time)))
10896 (time-to-days old-date-time))))
10897 ">") t t))))))
10899 (org-add-planning-info type time 'closed)
10900 (when (and old-date
10902 (not (equal old-date org-last-inserted-timestamp)))
10903 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
10904 org-last-inserted-timestamp
10905 old-date
10906 log))
10907 (when repeater
10908 (save-excursion
10909 (org-back-to-heading t)
10910 (when (re-search-forward
10911 (concat keyword " " org-last-inserted-timestamp)
10912 (line-end-position 2)
10914 (goto-char (1- (match-end 0)))
10915 (insert " " repeater)
10916 (setq org-last-inserted-timestamp
10917 (concat (substring org-last-inserted-timestamp 0 -1)
10918 " " repeater
10919 (substring org-last-inserted-timestamp -1))))))
10920 (message (if deadline? "Deadline on %s" "Scheduled to %s")
10921 org-last-inserted-timestamp)))))
10923 (defun org-deadline (arg &optional time)
10924 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10925 With one universal prefix argument, remove any deadline from the item.
10926 With two universal prefix arguments, prompt for a warning delay.
10927 With argument TIME, set the deadline at the corresponding date. TIME
10928 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
10929 (interactive "P")
10930 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
10931 (org-map-entries
10932 (lambda () (org--deadline-or-schedule arg 'deadline time))
10934 (if (eq org-loop-over-headlines-in-active-region 'start-level)
10935 'region-start-level
10936 'region)
10937 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
10938 (org--deadline-or-schedule arg 'deadline time)))
10940 (defun org-schedule (arg &optional time)
10941 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10942 With one universal prefix argument, remove any scheduling date from the item.
10943 With two universal prefix arguments, prompt for a delay cookie.
10944 With argument TIME, scheduled at the corresponding date. TIME can
10945 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
10946 (interactive "P")
10947 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
10948 (org-map-entries
10949 (lambda () (org--deadline-or-schedule arg 'scheduled time))
10951 (if (eq org-loop-over-headlines-in-active-region 'start-level)
10952 'region-start-level
10953 'region)
10954 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
10955 (org--deadline-or-schedule arg 'scheduled time)))
10957 (defun org-get-scheduled-time (pom &optional inherit)
10958 "Get the scheduled time as a time tuple, of a format suitable
10959 for calling org-schedule with, or if there is no scheduling,
10960 returns nil."
10961 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10962 (when time
10963 (apply 'encode-time (org-parse-time-string time)))))
10965 (defun org-get-deadline-time (pom &optional inherit)
10966 "Get the deadline as a time tuple, of a format suitable for
10967 calling org-deadline with, or if there is no scheduling, returns
10968 nil."
10969 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10970 (when time
10971 (apply 'encode-time (org-parse-time-string time)))))
10973 (defun org-remove-timestamp-with-keyword (keyword)
10974 "Remove all time stamps with KEYWORD in the current entry."
10975 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10976 beg)
10977 (save-excursion
10978 (org-back-to-heading t)
10979 (setq beg (point))
10980 (outline-next-heading)
10981 (while (re-search-backward re beg t)
10982 (replace-match "")
10983 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10984 (equal (char-before) ?\ ))
10985 (backward-delete-char 1)
10986 (when (string-match "^[ \t]*$" (buffer-substring
10987 (point-at-bol) (point-at-eol)))
10988 (delete-region (point-at-bol)
10989 (min (point-max) (1+ (point-at-eol))))))))))
10991 (defvar org-time-was-given) ; dynamically scoped parameter
10992 (defvar org-end-time-was-given) ; dynamically scoped parameter
10994 (defun org-at-planning-p ()
10995 "Non-nil when point is on a planning info line."
10996 ;; This is as accurate and faster than `org-element-at-point' since
10997 ;; planning info location is fixed in the section.
10998 (org-with-wide-buffer
10999 (beginning-of-line)
11000 (and (looking-at-p org-planning-line-re)
11001 (eq (point)
11002 (ignore-errors
11003 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
11004 (org-back-to-heading t)
11005 (org-with-limited-levels (org-back-to-heading t)))
11006 (line-beginning-position 2))))))
11008 (defun org-add-planning-info (what &optional time &rest remove)
11009 "Insert new timestamp with keyword in the planning line.
11010 WHAT indicates what kind of time stamp to add. It is a symbol
11011 among `closed', `deadline', `scheduled' and nil. TIME indicates
11012 the time to use. If none is given, the user is prompted for
11013 a date. REMOVE indicates what kind of entries to remove. An old
11014 WHAT entry will also be removed."
11015 (let (org-time-was-given org-end-time-was-given default-time default-input)
11016 (catch 'exit
11017 (when (and (memq what '(scheduled deadline))
11018 (or (not time)
11019 (and (stringp time)
11020 (string-match "^[-+]+[0-9]" time))))
11021 ;; Try to get a default date/time from existing timestamp
11022 (save-excursion
11023 (org-back-to-heading t)
11024 (let ((end (save-excursion (outline-next-heading) (point))) ts)
11025 (when (re-search-forward (if (eq what 'scheduled)
11026 org-scheduled-time-regexp
11027 org-deadline-time-regexp)
11028 end t)
11029 (setq ts (match-string 1)
11030 default-time (apply 'encode-time (org-parse-time-string ts))
11031 default-input (and ts (org-get-compact-tod ts)))))))
11032 (when what
11033 (setq time
11034 (if (stringp time)
11035 ;; This is a string (relative or absolute), set
11036 ;; proper date.
11037 (apply #'encode-time
11038 (org-read-date-analyze
11039 time default-time (decode-time default-time)))
11040 ;; If necessary, get the time from the user
11041 (or time (org-read-date nil 'to-time nil
11042 (cl-case what
11043 (deadline "DEADLINE")
11044 (scheduled "SCHEDULED")
11045 (otherwise nil))
11046 default-time default-input)))))
11047 (org-with-wide-buffer
11048 (org-back-to-heading t)
11049 (forward-line)
11050 (unless (bolp) (insert "\n"))
11051 (cond ((looking-at-p org-planning-line-re)
11052 ;; Move to current indentation.
11053 (skip-chars-forward " \t")
11054 ;; Check if we have to remove something.
11055 (dolist (type (if what (cons what remove) remove))
11056 (save-excursion
11057 (when (re-search-forward
11058 (cl-case type
11059 (closed org-closed-time-regexp)
11060 (deadline org-deadline-time-regexp)
11061 (scheduled org-scheduled-time-regexp)
11062 (otherwise
11063 (error "Invalid planning type: %s" type)))
11064 (line-end-position) t)
11065 ;; Delete until next keyword or end of line.
11066 (delete-region
11067 (match-beginning 0)
11068 (if (re-search-forward org-keyword-time-not-clock-regexp
11069 (line-end-position)
11071 (match-beginning 0)
11072 (line-end-position))))))
11073 ;; If there is nothing more to add and no more keyword
11074 ;; is left, remove the line completely.
11075 (if (and (looking-at-p "[ \t]*$") (not what))
11076 (delete-region (line-beginning-position)
11077 (line-beginning-position 2))
11078 ;; If we removed last keyword, do not leave trailing
11079 ;; white space at the end of line.
11080 (let ((p (point)))
11081 (save-excursion
11082 (end-of-line)
11083 (unless (= (skip-chars-backward " \t" p) 0)
11084 (delete-region (point) (line-end-position)))))))
11085 ((not what) (throw 'exit nil)) ; Nothing to do.
11086 (t (insert-before-markers "\n")
11087 (backward-char 1)
11088 (when org-adapt-indentation
11089 (indent-to-column (1+ (org-outline-level))))))
11090 (when what
11091 ;; Insert planning keyword.
11092 (insert (cl-case what
11093 (closed org-closed-string)
11094 (deadline org-deadline-string)
11095 (scheduled org-scheduled-string)
11096 (otherwise (error "Invalid planning type: %s" what)))
11097 " ")
11098 ;; Insert associated timestamp.
11099 (let ((ts (org-insert-time-stamp
11100 time
11101 (or org-time-was-given
11102 (and (eq what 'closed) org-log-done-with-time))
11103 (eq what 'closed)
11104 nil nil (list org-end-time-was-given))))
11105 (unless (eolp) (insert " "))
11106 ts))))))
11108 (defvar org-log-note-marker (make-marker)
11109 "Marker pointing at the entry where the note is to be inserted.")
11110 (defvar org-log-note-purpose nil)
11111 (defvar org-log-note-state nil)
11112 (defvar org-log-note-previous-state nil)
11113 (defvar org-log-note-extra nil)
11114 (defvar org-log-note-window-configuration nil)
11115 (defvar org-log-note-return-to (make-marker))
11116 (defvar org-log-note-effective-time nil
11117 "Remembered current time so that dynamically scoped
11118 `org-extend-today-until' affects timestamps in state change log")
11120 (defvar org-log-post-message nil
11121 "Message to be displayed after a log note has been stored.
11122 The auto-repeater uses this.")
11124 (defun org-add-note ()
11125 "Add a note to the current entry.
11126 This is done in the same way as adding a state change note."
11127 (interactive)
11128 (org-add-log-setup 'note))
11130 (defun org-log-beginning (&optional create)
11131 "Return expected start of log notes in current entry.
11132 When optional argument CREATE is non-nil, the function creates
11133 a drawer to store notes, if necessary. Returned position ignores
11134 narrowing."
11135 (org-with-wide-buffer
11136 (let ((drawer (org-log-into-drawer)))
11137 (cond
11138 (drawer
11139 (org-end-of-meta-data)
11140 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
11141 (end (if (org-at-heading-p) (point)
11142 (save-excursion (outline-next-heading) (point))))
11143 (case-fold-search t))
11144 (catch 'exit
11145 ;; Try to find existing drawer.
11146 (while (re-search-forward regexp end t)
11147 (let ((element (org-element-at-point)))
11148 (when (eq (org-element-type element) 'drawer)
11149 (let ((cend (org-element-property :contents-end element)))
11150 (when (and (not org-log-states-order-reversed) cend)
11151 (goto-char cend)))
11152 (throw 'exit nil))))
11153 ;; No drawer found. Create one, if permitted.
11154 (when create
11155 (unless (bolp) (insert "\n"))
11156 (let ((beg (point)))
11157 (insert ":" drawer ":\n:END:\n")
11158 (org-indent-region beg (point))
11159 (org-flag-region
11160 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
11161 (end-of-line -1)))))
11163 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
11164 (skip-chars-forward " \t\n")
11165 (beginning-of-line)
11166 (unless org-log-states-order-reversed
11167 (org-skip-over-state-notes)
11168 (skip-chars-backward " \t\n")
11169 (forward-line)))))
11170 (if (bolp) (point) (line-beginning-position 2))))
11172 (defun org-add-log-setup (&optional purpose state prev-state how extra)
11173 "Set up the post command hook to take a note.
11174 If this is about to TODO state change, the new state is expected in STATE.
11175 HOW is an indicator what kind of note should be created.
11176 EXTRA is additional text that will be inserted into the notes buffer."
11177 (move-marker org-log-note-marker (point))
11178 (setq org-log-note-purpose purpose
11179 org-log-note-state state
11180 org-log-note-previous-state prev-state
11181 org-log-note-how how
11182 org-log-note-extra extra
11183 org-log-note-effective-time (org-current-effective-time))
11184 (add-hook 'post-command-hook 'org-add-log-note 'append))
11186 (defun org-skip-over-state-notes ()
11187 "Skip past the list of State notes in an entry."
11188 (when (ignore-errors (goto-char (org-in-item-p)))
11189 (let* ((struct (org-list-struct))
11190 (prevs (org-list-prevs-alist struct))
11191 (regexp
11192 (concat "[ \t]*- +"
11193 (replace-regexp-in-string
11194 " +" " +"
11195 (org-replace-escapes
11196 (regexp-quote (cdr (assq 'state org-log-note-headings)))
11197 `(("%d" . ,org-ts-regexp-inactive)
11198 ("%D" . ,org-ts-regexp)
11199 ("%s" . "\\(?:\"\\S-+\"\\)?")
11200 ("%S" . "\\(?:\"\\S-+\"\\)?")
11201 ("%t" . ,org-ts-regexp-inactive)
11202 ("%T" . ,org-ts-regexp)
11203 ("%u" . ".*?")
11204 ("%U" . ".*?")))))))
11205 (while (looking-at-p regexp)
11206 (goto-char (or (org-list-get-next-item (point) struct prevs)
11207 (org-list-get-item-end (point) struct)))))))
11209 (defun org-add-log-note (&optional _purpose)
11210 "Pop up a window for taking a note, and add this note later."
11211 (remove-hook 'post-command-hook 'org-add-log-note)
11212 (setq org-log-note-window-configuration (current-window-configuration))
11213 (delete-other-windows)
11214 (move-marker org-log-note-return-to (point))
11215 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
11216 (goto-char org-log-note-marker)
11217 (org-switch-to-buffer-other-window "*Org Note*")
11218 (erase-buffer)
11219 (if (memq org-log-note-how '(time state))
11220 (org-store-log-note)
11221 (let ((org-inhibit-startup t)) (org-mode))
11222 (insert (format "# Insert note for %s.
11223 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11224 (cl-case org-log-note-purpose
11225 (clock-out "stopped clock")
11226 (done "closed todo item")
11227 (reschedule "rescheduling")
11228 (delschedule "no longer scheduled")
11229 (redeadline "changing deadline")
11230 (deldeadline "removing deadline")
11231 (refile "refiling")
11232 (note "this entry")
11233 (state
11234 (format "state change from \"%s\" to \"%s\""
11235 (or org-log-note-previous-state "")
11236 (or org-log-note-state "")))
11237 (t (error "This should not happen")))))
11238 (when org-log-note-extra (insert org-log-note-extra))
11239 (setq-local org-finish-function 'org-store-log-note)
11240 (run-hooks 'org-log-buffer-setup-hook)))
11242 (defvar org-note-abort nil) ; dynamically scoped
11243 (defun org-store-log-note ()
11244 "Finish taking a log note, and insert it to where it belongs."
11245 (let ((txt (prog1 (buffer-string)
11246 (kill-buffer)))
11247 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11248 lines)
11249 (while (string-match "\\`# .*\n[ \t\n]*" txt)
11250 (setq txt (replace-match "" t t txt)))
11251 (when (string-match "\\s-+\\'" txt)
11252 (setq txt (replace-match "" t t txt)))
11253 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
11254 (when (org-string-nw-p note)
11255 (setq note
11256 (org-replace-escapes
11257 note
11258 (list (cons "%u" (user-login-name))
11259 (cons "%U" user-full-name)
11260 (cons "%t" (format-time-string
11261 (org-time-stamp-format 'long 'inactive)
11262 org-log-note-effective-time))
11263 (cons "%T" (format-time-string
11264 (org-time-stamp-format 'long nil)
11265 org-log-note-effective-time))
11266 (cons "%d" (format-time-string
11267 (org-time-stamp-format nil 'inactive)
11268 org-log-note-effective-time))
11269 (cons "%D" (format-time-string
11270 (org-time-stamp-format nil nil)
11271 org-log-note-effective-time))
11272 (cons "%s" (cond
11273 ((not org-log-note-state) "")
11274 ((string-match-p org-ts-regexp
11275 org-log-note-state)
11276 (format "\"[%s]\""
11277 (substring org-log-note-state 1 -1)))
11278 (t (format "\"%s\"" org-log-note-state))))
11279 (cons "%S"
11280 (cond
11281 ((not org-log-note-previous-state) "")
11282 ((string-match-p org-ts-regexp
11283 org-log-note-previous-state)
11284 (format "\"[%s]\""
11285 (substring
11286 org-log-note-previous-state 1 -1)))
11287 (t (format "\"%s\""
11288 org-log-note-previous-state)))))))
11289 (when lines (setq note (concat note " \\\\")))
11290 (push note lines))
11291 (when (and lines (not org-note-abort))
11292 (with-current-buffer (marker-buffer org-log-note-marker)
11293 (org-with-wide-buffer
11294 ;; Find location for the new note.
11295 (goto-char org-log-note-marker)
11296 (set-marker org-log-note-marker nil)
11297 ;; Note associated to a clock is to be located right after
11298 ;; the clock. Do not move point.
11299 (unless (eq org-log-note-purpose 'clock-out)
11300 (goto-char (org-log-beginning t)))
11301 ;; Make sure point is at the beginning of an empty line.
11302 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11303 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
11304 ;; In an existing list, add a new item at the top level.
11305 ;; Otherwise, indent line like a regular one.
11306 (let ((itemp (org-in-item-p)))
11307 (if itemp
11308 (indent-line-to
11309 (let ((struct (save-excursion
11310 (goto-char itemp) (org-list-struct))))
11311 (org-list-get-ind (org-list-get-top-point struct) struct)))
11312 (org-indent-line)))
11313 (insert (org-list-bullet-string "-") (pop lines))
11314 (let ((ind (org-list-item-body-column (line-beginning-position))))
11315 (dolist (line lines)
11316 (insert "\n")
11317 (indent-line-to ind)
11318 (insert line)))
11319 (message "Note stored")
11320 (org-back-to-heading t))
11321 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
11322 ;; from within `org-add-log-note' because `buffer-undo-list'
11323 ;; is then modified outside of `org-with-remote-undo'.
11324 (when (eq this-command 'org-agenda-todo)
11325 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
11326 ;; Don't add undo information when called from `org-agenda-todo'.
11327 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
11328 (set-window-configuration org-log-note-window-configuration)
11329 (with-current-buffer (marker-buffer org-log-note-return-to)
11330 (goto-char org-log-note-return-to))
11331 (move-marker org-log-note-return-to nil)
11332 (when org-log-post-message (message "%s" org-log-post-message))))
11334 (defun org-remove-empty-drawer-at (pos)
11335 "Remove an empty drawer at position POS.
11336 POS may also be a marker."
11337 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11338 (org-with-wide-buffer
11339 (goto-char pos)
11340 (let ((drawer (org-element-at-point)))
11341 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
11342 (not (org-element-property :contents-begin drawer)))
11343 (delete-region (org-element-property :begin drawer)
11344 (progn (goto-char (org-element-property :end drawer))
11345 (skip-chars-backward " \r\t\n")
11346 (forward-line)
11347 (point))))))))
11349 (defvar org-ts-type nil)
11350 (defun org-sparse-tree (&optional arg type)
11351 "Create a sparse tree, prompt for the details.
11352 This command can create sparse trees. You first need to select the type
11353 of match used to create the tree:
11355 t Show all TODO entries.
11356 T Show entries with a specific TODO keyword.
11357 m Show entries selected by a tags/property match.
11358 p Enter a property name and its value (both with completion on existing
11359 names/values) and show entries with that property.
11360 r Show entries matching a regular expression (`/' can be used as well).
11361 b Show deadlines and scheduled items before a date.
11362 a Show deadlines and scheduled items after a date.
11363 d Show deadlines due within `org-deadline-warning-days'.
11364 D Show deadlines and scheduled items between a date range."
11365 (interactive "P")
11366 (setq type (or type org-sparse-tree-default-date-type))
11367 (setq org-ts-type type)
11368 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
11369 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
11370 \[c]ycle through date types: %s"
11371 (cl-case type
11372 (all "all timestamps")
11373 (scheduled "only scheduled")
11374 (deadline "only deadline")
11375 (active "only active timestamps")
11376 (inactive "only inactive timestamps")
11377 (closed "with a closed time-stamp")
11378 (otherwise "scheduled/deadline")))
11379 (let ((answer (read-char-exclusive)))
11380 (cl-case answer
11382 (org-sparse-tree
11384 (cadr
11385 (memq type '(nil all scheduled deadline active inactive closed)))))
11386 (?d (call-interactively 'org-check-deadlines))
11387 (?b (call-interactively 'org-check-before-date))
11388 (?a (call-interactively 'org-check-after-date))
11389 (?D (call-interactively 'org-check-dates-range))
11390 (?t (call-interactively 'org-show-todo-tree))
11391 (?T (org-show-todo-tree '(4)))
11392 (?m (call-interactively 'org-match-sparse-tree))
11393 ((?p ?P)
11394 (let* ((kwd (completing-read
11395 "Property: " (mapcar #'list (org-buffer-property-keys))))
11396 (value (completing-read
11397 "Value: " (mapcar #'list (org-property-values kwd)))))
11398 (unless (string-match "\\`{.*}\\'" value)
11399 (setq value (concat "\"" value "\"")))
11400 (org-match-sparse-tree arg (concat kwd "=" value))))
11401 ((?r ?R ?/) (call-interactively 'org-occur))
11402 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
11404 (defvar-local org-occur-highlights nil
11405 "List of overlays used for occur matches.")
11406 (defvar-local org-occur-parameters nil
11407 "Parameters of the active org-occur calls.
11408 This is a list, each call to org-occur pushes as cons cell,
11409 containing the regular expression and the callback, onto the list.
11410 The list can contain several entries if `org-occur' has been called
11411 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11412 will only contain one set of parameters. When the highlights are
11413 removed (for example with `C-c C-c', or with the next edit (depending
11414 on `org-remove-highlights-with-change'), this variable is emptied
11415 as well.")
11417 (defun org-occur (regexp &optional keep-previous callback)
11418 "Make a compact tree which shows all matches of REGEXP.
11420 The tree will show the lines where the regexp matches, and any other context
11421 defined in `org-show-context-detail', which see.
11423 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
11424 done by a previous call to `org-occur' will be kept, to allow stacking of
11425 calls to this command.
11427 Optional argument CALLBACK can be a function of no argument. In this case,
11428 it is called with point at the end of the match, match data being set
11429 accordingly. Current match is shown only if the return value is non-nil.
11430 The function must neither move point nor alter narrowing."
11431 (interactive "sRegexp: \nP")
11432 (when (equal regexp "")
11433 (user-error "Regexp cannot be empty"))
11434 (unless keep-previous
11435 (org-remove-occur-highlights nil nil t))
11436 (push (cons regexp callback) org-occur-parameters)
11437 (let ((cnt 0))
11438 (save-excursion
11439 (goto-char (point-min))
11440 (when (or (not keep-previous) ; do not want to keep
11441 (not org-occur-highlights)) ; no previous matches
11442 ;; hide everything
11443 (org-overview))
11444 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
11445 (isearch-no-upper-case-p regexp t)
11446 org-occur-case-fold-search)))
11447 (while (re-search-forward regexp nil t)
11448 (when (or (not callback)
11449 (save-match-data (funcall callback)))
11450 (setq cnt (1+ cnt))
11451 (when org-highlight-sparse-tree-matches
11452 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11453 (org-show-context 'occur-tree)))))
11454 (when org-remove-highlights-with-change
11455 (add-hook 'before-change-functions 'org-remove-occur-highlights
11456 nil 'local))
11457 (unless org-sparse-tree-open-archived-trees
11458 (org-hide-archived-subtrees (point-min) (point-max)))
11459 (run-hooks 'org-occur-hook)
11460 (when (called-interactively-p 'interactive)
11461 (message "%d match(es) for regexp %s" cnt regexp))
11462 cnt))
11464 (defun org-occur-next-match (&optional n _reset)
11465 "Function for `next-error-function' to find sparse tree matches.
11466 N is the number of matches to move, when negative move backwards.
11467 This function always goes back to the starting point when no
11468 match is found."
11469 (let* ((limit (if (< n 0) (point-min) (point-max)))
11470 (search-func (if (< n 0)
11471 'previous-single-char-property-change
11472 'next-single-char-property-change))
11473 (n (abs n))
11474 (pos (point))
11476 (catch 'exit
11477 (while (setq p1 (funcall search-func (point) 'org-type))
11478 (when (equal p1 limit)
11479 (goto-char pos)
11480 (user-error "No more matches"))
11481 (when (equal (get-char-property p1 'org-type) 'org-occur)
11482 (setq n (1- n))
11483 (when (= n 0)
11484 (goto-char p1)
11485 (throw 'exit (point))))
11486 (goto-char p1))
11487 (goto-char p1)
11488 (user-error "No more matches"))))
11490 (defun org-highlight-new-match (beg end)
11491 "Highlight from BEG to END and mark the highlight is an occur headline."
11492 (let ((ov (make-overlay beg end)))
11493 (overlay-put ov 'face 'secondary-selection)
11494 (overlay-put ov 'org-type 'org-occur)
11495 (push ov org-occur-highlights)))
11497 (defun org-remove-occur-highlights (&optional _beg _end noremove)
11498 "Remove the occur highlights from the buffer.
11499 BEG and END are ignored. If NOREMOVE is nil, remove this function
11500 from the `before-change-functions' in the current buffer."
11501 (interactive)
11502 (unless org-inhibit-highlight-removal
11503 (mapc #'delete-overlay org-occur-highlights)
11504 (setq org-occur-highlights nil)
11505 (setq org-occur-parameters nil)
11506 (unless noremove
11507 (remove-hook 'before-change-functions
11508 'org-remove-occur-highlights 'local))))
11510 ;;;; Priorities
11512 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11513 "Regular expression matching the priority indicator.")
11515 (defvar org-remove-priority-next-time nil)
11517 (defun org-priority-up ()
11518 "Increase the priority of the current item."
11519 (interactive)
11520 (org-priority 'up))
11522 (defun org-priority-down ()
11523 "Decrease the priority of the current item."
11524 (interactive)
11525 (org-priority 'down))
11527 (defun org-priority (&optional action show)
11528 "Change the priority of an item.
11530 When called interactively with a `\\[universal-argument]' prefix,
11531 show the priority in the minibuffer instead of changing it.
11533 When called programatically, ACTION can be `set', `up', `down',
11534 or a character."
11535 (interactive "P")
11536 (when show
11537 ;; Deprecation warning inserted for Org 9.2; once enough time has
11538 ;; passed the SHOW argument should be removed.
11539 (warn "`org-priority' called with deprecated SHOW argument"))
11540 (if (equal action '(4))
11541 (org-show-priority)
11542 (unless org-enable-priority-commands
11543 (user-error "Priority commands are disabled"))
11544 (setq action (or action 'set))
11545 (let (current new news have remove)
11546 (save-excursion
11547 (org-back-to-heading t)
11548 (when (looking-at org-priority-regexp)
11549 (setq current (string-to-char (match-string 2))
11550 have t))
11551 (cond
11552 ((eq action 'remove)
11553 (setq remove t new ?\ ))
11554 ((or (eq action 'set)
11555 (integerp action))
11556 (if (not (eq action 'set))
11557 (setq new action)
11558 (message "Priority %c-%c, SPC to remove: "
11559 org-highest-priority org-lowest-priority)
11560 (save-match-data
11561 (setq new (read-char-exclusive))))
11562 (when (and (= (upcase org-highest-priority) org-highest-priority)
11563 (= (upcase org-lowest-priority) org-lowest-priority))
11564 (setq new (upcase new)))
11565 (cond ((equal new ?\s) (setq remove t))
11566 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11567 (user-error "Priority must be between `%c' and `%c'"
11568 org-highest-priority org-lowest-priority))))
11569 ((eq action 'up)
11570 (setq new (if have
11571 (1- current) ; normal cycling
11572 ;; last priority was empty
11573 (if (eq last-command this-command)
11574 org-lowest-priority ; wrap around empty to lowest
11575 ;; default
11576 (if org-priority-start-cycle-with-default
11577 org-default-priority
11578 (1- org-default-priority))))))
11579 ((eq action 'down)
11580 (setq new (if have
11581 (1+ current) ; normal cycling
11582 ;; last priority was empty
11583 (if (eq last-command this-command)
11584 org-highest-priority ; wrap around empty to highest
11585 ;; default
11586 (if org-priority-start-cycle-with-default
11587 org-default-priority
11588 (1+ org-default-priority))))))
11589 (t (user-error "Invalid action")))
11590 (when (or (< (upcase new) org-highest-priority)
11591 (> (upcase new) org-lowest-priority))
11592 (if (and (memq action '(up down))
11593 (not have) (not (eq last-command this-command)))
11594 ;; `new' is from default priority
11595 (error
11596 "The default can not be set, see `org-default-priority' why")
11597 ;; normal cycling: `new' is beyond highest/lowest priority
11598 ;; and is wrapped around to the empty priority
11599 (setq remove t)))
11600 (setq news (format "%c" new))
11601 (if have
11602 (if remove
11603 (replace-match "" t t nil 1)
11604 (replace-match news t t nil 2))
11605 (if remove
11606 (user-error "No priority cookie found in line")
11607 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
11608 (if (match-end 2)
11609 (progn
11610 (goto-char (match-end 2))
11611 (insert " [#" news "]"))
11612 (goto-char (match-beginning 3))
11613 (insert "[#" news "] "))))
11614 (org-align-tags))
11615 (if remove
11616 (message "Priority removed")
11617 (message "Priority of current item set to %s" news)))))
11619 (defun org-show-priority ()
11620 "Show the priority of the current item.
11621 This priority is composed of the main priority given with the [#A] cookies,
11622 and by additional input from the age of a schedules or deadline entry."
11623 (interactive)
11624 (let ((pri (if (eq major-mode 'org-agenda-mode)
11625 (org-get-at-bol 'priority)
11626 (save-excursion
11627 (save-match-data
11628 (beginning-of-line)
11629 (and (looking-at org-heading-regexp)
11630 (org-get-priority (match-string 0))))))))
11631 (message "Priority is %d" (if pri pri -1000))))
11633 (defun org-get-priority (s)
11634 "Find priority cookie and return priority."
11635 (save-match-data
11636 (if (functionp org-get-priority-function)
11637 (funcall org-get-priority-function)
11638 (if (not (string-match org-priority-regexp s))
11639 (* 1000 (- org-lowest-priority org-default-priority))
11640 (* 1000 (- org-lowest-priority
11641 (string-to-char (match-string 2 s))))))))
11643 ;;;; Tags
11645 (defvar org-agenda-archives-mode)
11646 (defvar org-map-continue-from nil
11647 "Position from where mapping should continue.
11648 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
11650 (defvar org-scanner-tags nil
11651 "The current tag list while the tags scanner is running.")
11653 (defvar org-trust-scanner-tags nil
11654 "Should `org-get-tags' use the tags for the scanner.
11655 This is for internal dynamical scoping only.
11656 When this is non-nil, the function `org-get-tags' will return the value
11657 of `org-scanner-tags' instead of building the list by itself. This
11658 can lead to large speed-ups when the tags scanner is used in a file with
11659 many entries, and when the list of tags is retrieved, for example to
11660 obtain a list of properties. Building the tags list for each entry in such
11661 a file becomes an N^2 operation - but with this variable set, it scales
11662 as N.")
11664 (defvar org--matcher-tags-todo-only nil)
11666 (defun org-scan-tags (action matcher todo-only &optional start-level)
11667 "Scan headline tags with inheritance and produce output ACTION.
11669 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11670 or `agenda' to produce an entry list for an agenda view. It can also be
11671 a Lisp form or a function that should be called at each matched headline, in
11672 this case the return value is a list of all return values from these calls.
11674 MATCHER is a function accepting three arguments, returning
11675 a non-nil value whenever a given set of tags qualifies a headline
11676 for inclusion. See `org-make-tags-matcher' for more information.
11677 As a special case, it can also be set to t (respectively nil) in
11678 order to match all (respectively none) headline.
11680 When TODO-ONLY is non-nil, only lines with a TODO keyword are
11681 included in the output.
11683 START-LEVEL can be a string with asterisks, reducing the scope to
11684 headlines matching this string."
11685 (require 'org-agenda)
11686 (let* ((re (concat "^"
11687 (if start-level
11688 ;; Get the correct level to match
11689 (concat "\\*\\{" (number-to-string start-level) "\\} ")
11690 org-outline-regexp)
11691 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
11692 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
11693 (props (list 'face 'default
11694 'done-face 'org-agenda-done
11695 'undone-face 'default
11696 'mouse-face 'highlight
11697 'org-not-done-regexp org-not-done-regexp
11698 'org-todo-regexp org-todo-regexp
11699 'org-complex-heading-regexp org-complex-heading-regexp
11700 'help-echo
11701 (format "mouse-2 or RET jump to Org file %S"
11702 (abbreviate-file-name
11703 (or (buffer-file-name (buffer-base-buffer))
11704 (buffer-name (buffer-base-buffer)))))))
11705 (org-map-continue-from nil)
11706 lspos tags tags-list
11707 (tags-alist (list (cons 0 org-file-tags)))
11708 (llast 0) rtn rtn1 level category i txt
11709 todo marker entry priority
11710 ts-date ts-date-type ts-date-pair)
11711 (unless (or (member action '(agenda sparse-tree)) (functionp action))
11712 (setq action (list 'lambda nil action)))
11713 (save-excursion
11714 (goto-char (point-min))
11715 (when (eq action 'sparse-tree)
11716 (org-overview)
11717 (org-remove-occur-highlights))
11718 (while (let (case-fold-search)
11719 (re-search-forward re nil t))
11720 (setq org-map-continue-from nil)
11721 (catch :skip
11722 ;; Ignore closing parts of inline tasks.
11723 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
11724 (throw :skip t))
11725 (setq todo (and (match-end 1) (match-string-no-properties 1)))
11726 (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
11727 (goto-char (setq lspos (match-beginning 0)))
11728 (setq level (org-reduced-level (org-outline-level))
11729 category (org-get-category))
11730 (when (eq action 'agenda)
11731 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
11732 ts-date (car ts-date-pair)
11733 ts-date-type (cdr ts-date-pair)))
11734 (setq i llast llast level)
11735 ;; remove tag lists from same and sublevels
11736 (while (>= i level)
11737 (when (setq entry (assoc i tags-alist))
11738 (setq tags-alist (delete entry tags-alist)))
11739 (setq i (1- i)))
11740 ;; add the next tags
11741 (when tags
11742 (setq tags (org-split-string tags ":")
11743 tags-alist
11744 (cons (cons level tags) tags-alist)))
11745 ;; compile tags for current headline
11746 (setq tags-list
11747 (if org-use-tag-inheritance
11748 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11749 tags)
11750 org-scanner-tags tags-list)
11751 (when org-use-tag-inheritance
11752 (setcdr (car tags-alist)
11753 (mapcar (lambda (x)
11754 (setq x (copy-sequence x))
11755 (org-add-prop-inherited x))
11756 (cdar tags-alist))))
11757 (when (and tags org-use-tag-inheritance
11758 (or (not (eq t org-use-tag-inheritance))
11759 org-tags-exclude-from-inheritance))
11760 ;; Selective inheritance, remove uninherited ones.
11761 (setcdr (car tags-alist)
11762 (org-remove-uninherited-tags (cdar tags-alist))))
11763 (when (and
11765 ;; eval matcher only when the todo condition is OK
11766 (and (or (not todo-only) (member todo org-todo-keywords-1))
11767 (if (functionp matcher)
11768 (let ((case-fold-search t) (org-trust-scanner-tags t))
11769 (funcall matcher todo tags-list level))
11770 matcher))
11772 ;; Call the skipper, but return t if it does not
11773 ;; skip, so that the `and' form continues evaluating.
11774 (progn
11775 (unless (eq action 'sparse-tree) (org-agenda-skip))
11778 ;; Check if timestamps are deselecting this entry
11779 (or (not todo-only)
11780 (and (member todo org-todo-keywords-1)
11781 (or (not org-agenda-tags-todo-honor-ignore-options)
11782 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
11784 ;; select this headline
11785 (cond
11786 ((eq action 'sparse-tree)
11787 (and org-highlight-sparse-tree-matches
11788 (org-get-heading) (match-end 0)
11789 (org-highlight-new-match
11790 (match-beginning 1) (match-end 1)))
11791 (org-show-context 'tags-tree))
11792 ((eq action 'agenda)
11793 (setq txt (org-agenda-format-item
11795 (concat
11796 (if (eq org-tags-match-list-sublevels 'indented)
11797 (make-string (1- level) ?.) "")
11798 (org-get-heading))
11799 (make-string level ?\s)
11800 category
11801 tags-list)
11802 priority (org-get-priority txt))
11803 (goto-char lspos)
11804 (setq marker (org-agenda-new-marker))
11805 (org-add-props txt props
11806 'org-marker marker 'org-hd-marker marker 'org-category category
11807 'todo-state todo
11808 'ts-date ts-date
11809 'priority priority
11810 'type (concat "tagsmatch" ts-date-type))
11811 (push txt rtn))
11812 ((functionp action)
11813 (setq org-map-continue-from nil)
11814 (save-excursion
11815 (setq rtn1 (funcall action))
11816 (push rtn1 rtn)))
11817 (t (user-error "Invalid action")))
11819 ;; if we are to skip sublevels, jump to end of subtree
11820 (unless org-tags-match-list-sublevels
11821 (org-end-of-subtree t)
11822 (backward-char 1))))
11823 ;; Get the correct position from where to continue
11824 (if org-map-continue-from
11825 (goto-char org-map-continue-from)
11826 (and (= (point) lspos) (end-of-line 1)))))
11827 (when (and (eq action 'sparse-tree)
11828 (not org-sparse-tree-open-archived-trees))
11829 (org-hide-archived-subtrees (point-min) (point-max)))
11830 (nreverse rtn)))
11832 (defun org-remove-uninherited-tags (tags)
11833 "Remove all tags that are not inherited from the list TAGS."
11834 (cond
11835 ((eq org-use-tag-inheritance t)
11836 (if org-tags-exclude-from-inheritance
11837 (org-delete-all org-tags-exclude-from-inheritance tags)
11838 tags))
11839 ((not org-use-tag-inheritance) nil)
11840 ((stringp org-use-tag-inheritance)
11841 (delq nil (mapcar
11842 (lambda (x)
11843 (if (and (string-match org-use-tag-inheritance x)
11844 (not (member x org-tags-exclude-from-inheritance)))
11845 x nil))
11846 tags)))
11847 ((listp org-use-tag-inheritance)
11848 (delq nil (mapcar
11849 (lambda (x)
11850 (if (member x org-use-tag-inheritance) x nil))
11851 tags)))))
11853 (defun org-match-sparse-tree (&optional todo-only match)
11854 "Create a sparse tree according to tags string MATCH.
11856 MATCH is a string with match syntax. It can contain a selection
11857 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
11858 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
11859 those. See the manual for details.
11861 If optional argument TODO-ONLY is non-nil, only select lines that
11862 are also TODO tasks."
11863 (interactive "P")
11864 (org-agenda-prepare-buffers (list (current-buffer)))
11865 (let ((org--matcher-tags-todo-only todo-only))
11866 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
11867 org--matcher-tags-todo-only)))
11869 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11871 (defvar org-cached-props nil)
11872 (defun org-cached-entry-get (pom property)
11873 (if (or (eq t org-use-property-inheritance)
11874 (and (stringp org-use-property-inheritance)
11875 (let ((case-fold-search t))
11876 (string-match-p org-use-property-inheritance property)))
11877 (and (listp org-use-property-inheritance)
11878 (member-ignore-case property org-use-property-inheritance)))
11879 ;; Caching is not possible, check it directly.
11880 (org-entry-get pom property 'inherit)
11881 ;; Get all properties, so we can do complicated checks easily.
11882 (cdr (assoc-string property
11883 (or org-cached-props
11884 (setq org-cached-props (org-entry-properties pom)))
11885 t))))
11887 (defun org-global-tags-completion-table (&optional files)
11888 "Return the list of all tags in all agenda buffer/files.
11889 Optional FILES argument is a list of files which can be used
11890 instead of the agenda files."
11891 (save-excursion
11892 (org-uniquify
11893 (delq nil
11894 (apply #'append
11895 (mapcar
11896 (lambda (file)
11897 (set-buffer (find-file-noselect file))
11898 (org--tag-add-to-alist
11899 (org-get-buffer-tags)
11900 (mapcar (lambda (x)
11901 (and (stringp (car-safe x))
11902 (list (car-safe x))))
11903 org-current-tag-alist)))
11904 (if (car-safe files) files
11905 (org-agenda-files))))))))
11907 (defun org-make-tags-matcher (match)
11908 "Create the TAGS/TODO matcher form for the selection string MATCH.
11910 Returns a cons of the selection string MATCH and a function
11911 implementing the matcher.
11913 The matcher is to be called at an Org entry, with point on the
11914 headline, and returns non-nil if the entry matches the selection
11915 string MATCH. It must be called with three arguments: the TODO
11916 keyword at the entry (or nil if none), the list of all tags at
11917 the entry including inherited ones and the reduced level of the
11918 headline. Additionally, the category of the entry, if any, must
11919 be specified as the text property `org-category' on the headline.
11921 This function sets the variable `org--matcher-tags-todo-only' to
11922 a non-nil value if the matcher restricts matching to TODO
11923 entries, otherwise it is not touched.
11925 See also `org-scan-tags'."
11926 (unless match
11927 ;; Get a new match request, with completion against the global
11928 ;; tags table and the local tags in current buffer.
11929 (let ((org-last-tags-completion-table
11930 (org--tag-add-to-alist
11931 (org-get-buffer-tags)
11932 (org-global-tags-completion-table))))
11933 (setq match
11934 (completing-read
11935 "Match: "
11936 'org-tags-completion-function nil nil nil 'org-tags-history))))
11938 (let ((match0 match)
11939 (re (concat
11940 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
11941 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
11942 "\\([<>=]\\{1,2\\}\\)"
11943 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
11944 "\\|" org-tag-re "\\)"))
11945 (start 0)
11946 tagsmatch todomatch tagsmatcher todomatcher)
11948 ;; Expand group tags.
11949 (setq match (org-tags-expand match))
11951 ;; Check if there is a TODO part of this match, which would be the
11952 ;; part after a "/". To make sure that this slash is not part of
11953 ;; a property value to be matched against, we also check that
11954 ;; there is no / after that slash. First, find the last slash.
11955 (let ((s 0))
11956 (while (string-match "/+" match s)
11957 (setq start (match-beginning 0))
11958 (setq s (match-end 0))))
11959 (if (and (string-match "/+" match start)
11960 (not (string-match-p "\"" match start)))
11961 ;; Match contains also a TODO-matching request.
11962 (progn
11963 (setq tagsmatch (substring match 0 (match-beginning 0)))
11964 (setq todomatch (substring match (match-end 0)))
11965 (when (string-prefix-p "!" todomatch)
11966 (setq org--matcher-tags-todo-only t)
11967 (setq todomatch (substring todomatch 1)))
11968 (when (string-match "\\`\\s-*\\'" todomatch)
11969 (setq todomatch nil)))
11970 ;; Only matching tags.
11971 (setq tagsmatch match)
11972 (setq todomatch nil))
11974 ;; Make the tags matcher.
11975 (when (org-string-nw-p tagsmatch)
11976 (let ((orlist nil)
11977 (orterms (org-split-string tagsmatch "|"))
11978 term)
11979 (while (setq term (pop orterms))
11980 (while (and (equal (substring term -1) "\\") orterms)
11981 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
11982 (while (string-match re term)
11983 (let* ((rest (substring term (match-end 0)))
11984 (minus (and (match-end 1)
11985 (equal (match-string 1 term) "-")))
11986 (tag (save-match-data
11987 (replace-regexp-in-string
11988 "\\\\-" "-" (match-string 2 term))))
11989 (regexp (eq (string-to-char tag) ?{))
11990 (levelp (match-end 4))
11991 (propp (match-end 5))
11993 (cond
11994 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
11995 (levelp
11996 `(,(org-op-to-function (match-string 3 term))
11997 level
11998 ,(string-to-number (match-string 4 term))))
11999 (propp
12000 (let* ((gv (pcase (upcase (match-string 5 term))
12001 ("CATEGORY"
12002 '(get-text-property (point) 'org-category))
12003 ("TODO" 'todo)
12004 (p `(org-cached-entry-get nil ,p))))
12005 (pv (match-string 7 term))
12006 (regexp (eq (string-to-char pv) ?{))
12007 (strp (eq (string-to-char pv) ?\"))
12008 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
12009 (po (org-op-to-function (match-string 6 term)
12010 (if timep 'time strp))))
12011 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
12012 (when timep (setq pv (org-matcher-time pv)))
12013 (cond ((and regexp (eq po '/=))
12014 `(not (string-match ,pv (or ,gv ""))))
12015 (regexp `(string-match ,pv (or ,gv "")))
12016 (strp `(,po (or ,gv "") ,pv))
12018 `(,po
12019 (string-to-number (or ,gv ""))
12020 ,(string-to-number pv))))))
12021 (t `(member ,tag tags-list)))))
12022 (push (if minus `(not ,mm) mm) tagsmatcher)
12023 (setq term rest)))
12024 (push `(and ,@tagsmatcher) orlist)
12025 (setq tagsmatcher nil))
12026 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
12028 ;; Make the TODO matcher.
12029 (when (org-string-nw-p todomatch)
12030 (let ((orlist nil))
12031 (dolist (term (org-split-string todomatch "|"))
12032 (while (string-match re term)
12033 (let* ((minus (and (match-end 1)
12034 (equal (match-string 1 term) "-")))
12035 (kwd (match-string 2 term))
12036 (regexp (eq (string-to-char kwd) ?{))
12037 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
12038 `(equal todo ,kwd))))
12039 (push (if minus `(not ,mm) mm) todomatcher))
12040 (setq term (substring term (match-end 0))))
12041 (push (if (> (length todomatcher) 1)
12042 (cons 'and todomatcher)
12043 (car todomatcher))
12044 orlist)
12045 (setq todomatcher nil))
12046 (setq todomatcher (cons 'or orlist))))
12048 ;; Return the string and function of the matcher. If no
12049 ;; tags-specific or todo-specific matcher exists, match
12050 ;; everything.
12051 (let ((matcher (if (and tagsmatcher todomatcher)
12052 `(and ,tagsmatcher ,todomatcher)
12053 (or tagsmatcher todomatcher t))))
12054 (when org--matcher-tags-todo-only
12055 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
12056 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
12058 (defun org--tags-expand-group (group tag-groups expanded)
12059 "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
12060 TAG-GROUPS is the list of groups used for expansion. EXPANDED is
12061 an accumulator used in recursive calls."
12062 (dolist (tag group)
12063 (unless (member tag expanded)
12064 (let ((group (assoc tag tag-groups)))
12065 (push tag expanded)
12066 (when group
12067 (setq expanded
12068 (org--tags-expand-group (cdr group) tag-groups expanded))))))
12069 expanded)
12071 (defun org-tags-expand (match &optional single-as-list downcased)
12072 "Expand group tags in MATCH.
12074 This replaces every group tag in MATCH with a regexp tag search.
12075 For example, a group tag \"Work\" defined as { Work : Lab Conf }
12076 will be replaced like this:
12078 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
12079 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
12080 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
12082 Replacing by a regexp preserves the structure of the match.
12083 E.g., this expansion
12085 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
12087 will match anything tagged with \"Lab\" and \"Home\", or tagged
12088 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
12090 A group tag in MATCH can contain regular expressions of its own.
12091 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
12092 will be replaced like this:
12094 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
12096 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
12097 assumed to be a single group tag, and the function will return
12098 the list of tags in this group.
12100 When DOWNCASED is non-nil, expand downcased TAGS."
12101 (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
12102 (let ((tag-groups
12103 (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
12104 (if (not downcased) g
12105 (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
12106 (cond
12107 (single-as-list (org--tags-expand-group (list match) tag-groups nil))
12108 (org-group-tags
12109 (let* ((case-fold-search t)
12110 (tag-syntax org-mode-syntax-table)
12111 (group-keys (mapcar #'car tag-groups))
12112 (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
12113 (return-match (if downcased (downcase match) match)))
12114 ;; Mark regexp-expressions in the match-expression so that we
12115 ;; do not replace them later on.
12116 (let ((s 0))
12117 (while (string-match "{.+?}" return-match s)
12118 (setq s (match-end 0))
12119 (add-text-properties
12120 (match-beginning 0) (match-end 0) '(regexp t) return-match)))
12121 ;; @ and _ are allowed as word-components in tags.
12122 (modify-syntax-entry ?@ "w" tag-syntax)
12123 (modify-syntax-entry ?_ "w" tag-syntax)
12124 ;; For each tag token found in MATCH, compute a regexp and it
12125 (with-syntax-table tag-syntax
12126 (replace-regexp-in-string
12127 key-regexp
12128 (lambda (m)
12129 (if (get-text-property (match-beginning 2) 'regexp m)
12130 m ;regexp tag: ignore
12131 (let* ((operator (match-string 1 m))
12132 (tag-token (let ((tag (match-string 2 m)))
12133 (list (if downcased (downcase tag) tag))))
12134 regexp-tags regular-tags)
12135 ;; Partition tags between regexp and regular tags.
12136 ;; Remove curly bracket syntax from regexp tags.
12137 (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
12138 (save-match-data
12139 (if (string-match "{\\(.+?\\)}" tag)
12140 (push (match-string 1 tag) regexp-tags)
12141 (push tag regular-tags))))
12142 ;; Replace tag token by the appropriate regexp.
12143 ;; Regular tags need to be regexp-quoted, whereas
12144 ;; regexp-tags are inserted as-is.
12145 (let ((regular (regexp-opt regular-tags))
12146 (regexp (mapconcat #'identity regexp-tags "\\|")))
12147 (concat operator
12148 (cond
12149 ((null regular-tags) (format "{%s}" regexp))
12150 ((null regexp-tags) (format "{\\<%s\\>}" regular))
12151 (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
12152 return-match
12153 t t))))
12154 (t match))))
12156 (defun org-op-to-function (op &optional stringp)
12157 "Turn an operator into the appropriate function."
12158 (setq op
12159 (cond
12160 ((equal op "<" ) '(< org-string< org-time<))
12161 ((equal op ">" ) '(> org-string> org-time>))
12162 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12163 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12164 ((member op '("=" "==")) '(= string= org-time=))
12165 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
12166 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12168 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12169 (defvar org-tags-overlay (make-overlay 1 1))
12170 (delete-overlay org-tags-overlay)
12172 (defun org-add-prop-inherited (s)
12173 (add-text-properties 0 (length s) '(inherited t) s)
12176 (defun org-toggle-tag (tag &optional onoff)
12177 "Toggle the tag TAG for the current line.
12178 If ONOFF is `on' or `off', don't toggle but set to this state."
12179 (save-excursion
12180 (org-back-to-heading t)
12181 (let ((current
12182 ;; Reverse the tags list so any new tag is appended to the
12183 ;; current list of tags.
12184 (nreverse (org-get-tags nil t)))
12185 res)
12186 (pcase onoff
12187 (`off (setq current (delete tag current)))
12188 ((or `on (guard (not (member tag current))))
12189 (setq res t)
12190 (cl-pushnew tag current :test #'equal))
12191 (_ (setq current (delete tag current))))
12192 (org-set-tags (nreverse current))
12193 res)))
12195 (defun org--align-tags-here (to-col)
12196 "Align tags on the current headline to TO-COL.
12197 Assume point is on a headline. Preserve point when aligning
12198 tags."
12199 (when (org-match-line org-tag-line-re)
12200 (let* ((tags-start (match-beginning 1))
12201 (blank-start (save-excursion
12202 (goto-char tags-start)
12203 (skip-chars-backward " \t")
12204 (point)))
12205 (new (max (if (>= to-col 0) to-col
12206 (- (abs to-col) (string-width (match-string 1))))
12207 ;; Introduce at least one space after the heading
12208 ;; or the stars.
12209 (save-excursion
12210 (goto-char blank-start)
12211 (1+ (current-column)))))
12212 (current
12213 (save-excursion (goto-char tags-start) (current-column)))
12214 (origin (point-marker))
12215 (column (current-column))
12216 (in-blank? (and (> origin blank-start) (<= origin tags-start))))
12217 (when (/= new current)
12218 (delete-region blank-start tags-start)
12219 (goto-char blank-start)
12220 (let ((indent-tabs-mode nil)) (indent-to new))
12221 ;; Try to move back to original position. If point was in the
12222 ;; blanks before the tags, ORIGIN marker is of no use because
12223 ;; it now points to BLANK-START. Use COLUMN instead.
12224 (if in-blank? (org-move-to-column column) (goto-char origin))))))
12226 (defun org-set-tags-command (&optional arg)
12227 "Set the tags for the current visible entry.
12229 When called with `\\[universal-argument]' prefix argument ARG, \
12230 realign all tags
12231 in the current buffer.
12233 When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
12234 unconditionally do not
12235 offer the fast tag selection interface.
12237 If a region is active, set tags in the region according to the
12238 setting of `org-loop-over-headlines-in-active-region'.
12240 This function is for interactive use only;
12241 in Lisp code use `org-set-tags' instead."
12242 (interactive "P")
12243 (let ((org-use-fast-tag-selection
12244 (unless (equal '(16) arg) org-use-fast-tag-selection)))
12245 (cond
12246 ((equal '(4) arg) (org-align-tags t))
12247 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
12248 (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
12249 (org-map-entries
12250 #'org-set-tags-command
12252 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12253 'region-start-level
12254 'region)
12255 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
12257 (save-excursion
12258 (org-back-to-heading)
12259 (let* ((all-tags (org-get-tags))
12260 (table (setq org-last-tags-completion-table
12261 (org--tag-add-to-alist
12262 (and org-complete-tags-always-offer-all-agenda-tags
12263 (org-global-tags-completion-table
12264 (org-agenda-files)))
12265 (or org-current-tag-alist (org-get-buffer-tags)))))
12266 (current-tags
12267 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
12268 all-tags))
12269 (inherited-tags
12270 (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
12271 all-tags))
12272 (tags
12273 (replace-regexp-in-string
12274 ;; Ignore all forbidden characters in tags.
12275 "[^[:alnum:]_@#%]+" ":"
12276 (if (or (eq t org-use-fast-tag-selection)
12277 (and org-use-fast-tag-selection
12278 (delq nil (mapcar #'cdr table))))
12279 (org-fast-tag-selection
12280 current-tags
12281 inherited-tags
12282 table
12283 (and org-fast-tag-selection-include-todo org-todo-key-alist))
12284 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
12285 (org-trim (completing-read
12286 "Tags: "
12287 #'org-tags-completion-function
12288 nil nil (org-make-tag-string current-tags)
12289 'org-tags-history)))))))
12290 (org-set-tags tags)))))))
12292 (defun org-align-tags (&optional all)
12293 "Align tags in current entry.
12294 When optional argument ALL is non-nil, align all tags in the
12295 visible part of the buffer."
12296 (let ((get-indent-column
12297 (lambda ()
12298 (let ((offset (if (bound-and-true-p org-indent-mode)
12299 (* (1- org-indent-indentation-per-level)
12300 (1- (org-current-level)))
12301 0)))
12302 (+ org-tags-column
12303 (if (> org-tags-column 0) (- offset) offset))))))
12304 (if (and (not all) (org-at-heading-p))
12305 (org--align-tags-here (funcall get-indent-column))
12306 (save-excursion
12307 (if all
12308 (progn
12309 (goto-char (point-min))
12310 (while (re-search-forward org-tag-line-re nil t)
12311 (org--align-tags-here (funcall get-indent-column))))
12312 (org-back-to-heading t)
12313 (org--align-tags-here (funcall get-indent-column)))))))
12315 (defun org-set-tags (tags)
12316 "Set the tags of the current entry to TAGS, replacing current tags.
12318 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
12319 If TAGS is nil or the empty string, all tags are removed.
12321 This function assumes point is on a headline."
12322 (org-with-wide-buffer
12323 (let ((tags (pcase tags
12324 ((pred listp) tags)
12325 ((pred stringp) (split-string (org-trim tags) ":" t))
12326 (_ (error "Invalid tag specification: %S" tags))))
12327 (old-tags (org-get-tags nil t))
12328 (tags-change? nil))
12329 (when (functionp org-tags-sort-function)
12330 (setq tags (sort tags org-tags-sort-function)))
12331 (setq tags-change? (not (equal tags old-tags)))
12332 (when tags-change?
12333 ;; Delete previous tags and any trailing white space.
12334 (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
12335 (line-end-position)))
12336 (skip-chars-backward " \t")
12337 (delete-region (point) (line-end-position))
12338 ;; Deleting white spaces may break an otherwise empty headline.
12339 ;; Re-introduce one space in this case.
12340 (unless (org-at-heading-p) (insert " "))
12341 (when tags
12342 (save-excursion (insert " " (org-make-tag-string tags)))
12343 ;; When text is being inserted on an invisible region
12344 ;; boundary, it can be inadvertently sucked into
12345 ;; invisibility.
12346 (unless (org-invisible-p (line-beginning-position))
12347 (org-flag-region (point) (line-end-position) nil 'outline))))
12348 ;; Align tags, if any.
12349 (when tags (org-align-tags))
12350 (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
12352 (defun org-change-tag-in-region (beg end tag off)
12353 "Add or remove TAG for each entry in the region.
12354 This works in the agenda, and also in an Org buffer."
12355 (interactive
12356 (list (region-beginning) (region-end)
12357 (let ((org-last-tags-completion-table
12358 (if (derived-mode-p 'org-mode)
12359 (org--tag-add-to-alist
12360 (org-get-buffer-tags)
12361 (org-global-tags-completion-table))
12362 (org-global-tags-completion-table))))
12363 (completing-read
12364 "Tag: " 'org-tags-completion-function nil nil nil
12365 'org-tags-history))
12366 (progn
12367 (message "[s]et or [r]emove? ")
12368 (equal (read-char-exclusive) ?r))))
12369 (when (fboundp 'deactivate-mark) (deactivate-mark))
12370 (let ((agendap (equal major-mode 'org-agenda-mode))
12371 l1 l2 m buf pos newhead (cnt 0))
12372 (goto-char end)
12373 (setq l2 (1- (org-current-line)))
12374 (goto-char beg)
12375 (setq l1 (org-current-line))
12376 (cl-loop for l from l1 to l2 do
12377 (org-goto-line l)
12378 (setq m (get-text-property (point) 'org-hd-marker))
12379 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
12380 (and agendap m))
12381 (setq buf (if agendap (marker-buffer m) (current-buffer))
12382 pos (if agendap m (point)))
12383 (with-current-buffer buf
12384 (save-excursion
12385 (save-restriction
12386 (goto-char pos)
12387 (setq cnt (1+ cnt))
12388 (org-toggle-tag tag (if off 'off 'on))
12389 (setq newhead (org-get-heading)))))
12390 (and agendap (org-agenda-change-all-lines newhead m))))
12391 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12393 (defun org-tags-completion-function (string _predicate &optional flag)
12394 "Complete tag STRING.
12395 FLAG specifies the type of completion operation to perform. This
12396 function is passed as a collection function to `completing-read',
12397 which see."
12398 (let ((completion-ignore-case nil) ;tags are case-sensitive
12399 (confirm (lambda (x) (stringp (car x))))
12400 (prefix ""))
12401 (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
12402 (setq prefix (match-string 1 string))
12403 (setq string (match-string 2 string)))
12404 (pcase flag
12405 (`t (all-completions string org-last-tags-completion-table confirm))
12406 (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
12407 (`nil
12408 (pcase (try-completion string org-last-tags-completion-table confirm)
12409 ((and completion (pred stringp))
12410 (concat prefix
12411 completion
12412 (if (and org-add-colon-after-tag-completion
12413 (assoc completion org-last-tags-completion-table))
12415 "")))
12416 (completion completion)))
12417 (_ nil))))
12419 (defun org-fast-tag-insert (kwd tags face &optional end)
12420 "Insert KWD, and the TAGS, the latter with face FACE.
12421 Also insert END."
12422 (insert (format "%-12s" (concat kwd ":"))
12423 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12424 (or end "")))
12426 (defun org-fast-tag-show-exit (flag)
12427 (save-excursion
12428 (org-goto-line 3)
12429 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12430 (replace-match ""))
12431 (when flag
12432 (end-of-line 1)
12433 (org-move-to-column (- (window-width) 19) t)
12434 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12436 (defun org-set-current-tags-overlay (current prefix)
12437 "Add an overlay to CURRENT tag with PREFIX."
12438 (let ((s (org-make-tag-string current)))
12439 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12440 (org-overlay-display org-tags-overlay (concat prefix s))))
12442 (defvar org-last-tag-selection-key nil)
12443 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12444 "Fast tag selection with single keys.
12445 CURRENT is the current list of tags in the headline, INHERITED is the
12446 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12447 possibly with grouping information. TODO-TABLE is a similar table with
12448 TODO keywords, should these have keys assigned to them.
12449 If the keys are nil, a-z are automatically assigned.
12450 Returns the new tags string, or nil to not change the current settings."
12451 (let* ((fulltable (append table todo-table))
12452 (maxlen (if (null fulltable) 0
12453 (apply #'max
12454 (mapcar (lambda (x)
12455 (if (stringp (car x)) (string-width (car x))
12457 fulltable))))
12458 (buf (current-buffer))
12459 (expert (eq org-fast-tag-selection-single-key 'expert))
12460 (buffer-tags nil)
12461 (fwidth (+ maxlen 3 1 3))
12462 (ncol (/ (- (window-width) 4) fwidth))
12463 (i-face 'org-done)
12464 (c-face 'org-todo)
12465 tg cnt e c char c1 c2 ntable tbl rtn
12466 ov-start ov-end ov-prefix
12467 (exit-after-next org-fast-tag-selection-single-key)
12468 (done-keywords org-done-keywords)
12469 groups ingroup intaggroup)
12470 (save-excursion
12471 (beginning-of-line)
12472 (if (looking-at org-tag-line-re)
12473 (setq ov-start (match-beginning 1)
12474 ov-end (match-end 1)
12475 ov-prefix "")
12476 (setq ov-start (1- (point-at-eol))
12477 ov-end (1+ ov-start))
12478 (skip-chars-forward "^\n\r")
12479 (setq ov-prefix
12480 (concat
12481 (buffer-substring (1- (point)) (point))
12482 (if (> (current-column) org-tags-column)
12484 (make-string (- org-tags-column (current-column)) ?\ ))))))
12485 (move-overlay org-tags-overlay ov-start ov-end)
12486 (save-window-excursion
12487 (if expert
12488 (set-buffer (get-buffer-create " *Org tags*"))
12489 (delete-other-windows)
12490 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
12491 (org-switch-to-buffer-other-window " *Org tags*"))
12492 (erase-buffer)
12493 (setq-local org-done-keywords done-keywords)
12494 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12495 (org-fast-tag-insert "Current" current c-face "\n\n")
12496 (org-fast-tag-show-exit exit-after-next)
12497 (org-set-current-tags-overlay current ov-prefix)
12498 (setq tbl fulltable char ?a cnt 0)
12499 (while (setq e (pop tbl))
12500 (cond
12501 ((eq (car e) :startgroup)
12502 (push '() groups) (setq ingroup t)
12503 (unless (zerop cnt)
12504 (setq cnt 0)
12505 (insert "\n"))
12506 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12507 ((eq (car e) :endgroup)
12508 (setq ingroup nil cnt 0)
12509 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12510 ((eq (car e) :startgrouptag)
12511 (setq intaggroup t)
12512 (unless (zerop cnt)
12513 (setq cnt 0)
12514 (insert "\n"))
12515 (insert "[ "))
12516 ((eq (car e) :endgrouptag)
12517 (setq intaggroup nil cnt 0)
12518 (insert "]\n"))
12519 ((equal e '(:newline))
12520 (unless (zerop cnt)
12521 (setq cnt 0)
12522 (insert "\n")
12523 (setq e (car tbl))
12524 (while (equal (car tbl) '(:newline))
12525 (insert "\n")
12526 (setq tbl (cdr tbl)))))
12527 ((equal e '(:grouptags)) (insert " : "))
12529 (setq tg (copy-sequence (car e)) c2 nil)
12530 (if (cdr e)
12531 (setq c (cdr e))
12532 ;; automatically assign a character.
12533 (setq c1 (string-to-char
12534 (downcase (substring
12535 tg (if (= (string-to-char tg) ?@) 1 0)))))
12536 (if (or (rassoc c1 ntable) (rassoc c1 table))
12537 (while (or (rassoc char ntable) (rassoc char table))
12538 (setq char (1+ char)))
12539 (setq c2 c1))
12540 (setq c (or c2 char)))
12541 (when ingroup (push tg (car groups)))
12542 (setq tg (org-add-props tg nil 'face
12543 (cond
12544 ((not (assoc tg table))
12545 (org-get-todo-face tg))
12546 ((member tg current) c-face)
12547 ((member tg inherited) i-face))))
12548 (when (equal (caar tbl) :grouptags)
12549 (org-add-props tg nil 'face 'org-tag-group))
12550 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
12551 (insert "[" c "] " tg (make-string
12552 (- fwidth 4 (length tg)) ?\ ))
12553 (push (cons tg c) ntable)
12554 (when (= (cl-incf cnt) ncol)
12555 (unless (memq (caar tbl) '(:endgroup :endgrouptag))
12556 (insert "\n")
12557 (when (or ingroup intaggroup) (insert " ")))
12558 (setq cnt 0)))))
12559 (setq ntable (nreverse ntable))
12560 (insert "\n")
12561 (goto-char (point-min))
12562 (unless expert (org-fit-window-to-buffer))
12563 (setq rtn
12564 (catch 'exit
12565 (while t
12566 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
12567 (if (not groups) "no " "")
12568 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12569 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12570 (setq org-last-tag-selection-key c)
12571 (cond
12572 ((= c ?\r) (throw 'exit t))
12573 ((= c ?!)
12574 (setq groups (not groups))
12575 (goto-char (point-min))
12576 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12577 ((= c ?\C-c)
12578 (if (not expert)
12579 (org-fast-tag-show-exit
12580 (setq exit-after-next (not exit-after-next)))
12581 (setq expert nil)
12582 (delete-other-windows)
12583 (set-window-buffer (split-window-vertically) " *Org tags*")
12584 (org-switch-to-buffer-other-window " *Org tags*")
12585 (org-fit-window-to-buffer)))
12586 ((or (= c ?\C-g)
12587 (and (= c ?q) (not (rassoc c ntable))))
12588 (delete-overlay org-tags-overlay)
12589 (setq quit-flag t))
12590 ((= c ?\ )
12591 (setq current nil)
12592 (when exit-after-next (setq exit-after-next 'now)))
12593 ((= c ?\t)
12594 (condition-case nil
12595 (setq tg (completing-read
12596 "Tag: "
12597 (or buffer-tags
12598 (with-current-buffer buf
12599 (setq buffer-tags
12600 (org-get-buffer-tags))))))
12601 (quit (setq tg "")))
12602 (when (string-match "\\S-" tg)
12603 (cl-pushnew (list tg) buffer-tags :test #'equal)
12604 (if (member tg current)
12605 (setq current (delete tg current))
12606 (push tg current)))
12607 (when exit-after-next (setq exit-after-next 'now)))
12608 ((setq e (rassoc c todo-table) tg (car e))
12609 (with-current-buffer buf
12610 (save-excursion (org-todo tg)))
12611 (when exit-after-next (setq exit-after-next 'now)))
12612 ((setq e (rassoc c ntable) tg (car e))
12613 (if (member tg current)
12614 (setq current (delete tg current))
12615 (cl-loop for g in groups do
12616 (when (member tg g)
12617 (dolist (x g) (setq current (delete x current)))))
12618 (push tg current))
12619 (when exit-after-next (setq exit-after-next 'now))))
12621 ;; Create a sorted list
12622 (setq current
12623 (sort current
12624 (lambda (a b)
12625 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12626 (when (eq exit-after-next 'now) (throw 'exit t))
12627 (goto-char (point-min))
12628 (beginning-of-line 2)
12629 (delete-region (point) (point-at-eol))
12630 (org-fast-tag-insert "Current" current c-face)
12631 (org-set-current-tags-overlay current ov-prefix)
12632 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
12633 (while (re-search-forward tag-re nil t)
12634 (let ((tag (match-string 1)))
12635 (add-text-properties
12636 (match-beginning 1) (match-end 1)
12637 (list 'face
12638 (cond
12639 ((member tag current) c-face)
12640 ((member tag inherited) i-face)
12641 (t (get-text-property (match-beginning 1) '
12642 face))))))))
12643 (goto-char (point-min)))))
12644 (delete-overlay org-tags-overlay)
12645 (if rtn
12646 (mapconcat 'identity current ":")
12647 nil))))
12649 (defun org-make-tag-string (tags)
12650 "Return string associated to TAGS.
12651 TAGS is a list of strings."
12652 (if (null tags) ""
12653 (format ":%s:" (mapconcat #'identity tags ":"))))
12655 (defun org--get-local-tags ()
12656 "Return list of tags for the current headline.
12657 Assume point is at the beginning of the headline."
12658 (and (looking-at org-tag-line-re)
12659 (split-string (match-string-no-properties 2) ":" t)))
12661 (defun org-get-tags (&optional pos local)
12662 "Get the list of tags specified in the current headline.
12664 When argument POS is non-nil, retrieve tags for headline at POS.
12666 According to `org-use-tag-inheritance', tags may be inherited
12667 from parent headlines, and from the whole document, through
12668 `org-file-tags'. In this case, the returned list of tags
12669 contains tags in this order: file tags, tags inherited from
12670 parent headlines, local tags.
12672 However, when optional argument LOCAL is non-nil, only return
12673 tags specified at the headline.
12675 Inherited tags have the `inherited' text property."
12676 (if (and org-trust-scanner-tags
12677 (or (not pos) (eq pos (point)))
12678 (not local))
12679 org-scanner-tags
12680 (org-with-point-at (or pos (point))
12681 (unless (org-before-first-heading-p)
12682 (org-back-to-heading t)
12683 (let ((ltags (org--get-local-tags)) itags)
12684 (if (or local (not org-use-tag-inheritance)) ltags
12685 (while (org-up-heading-safe)
12686 (setq itags (append (mapcar #'org-add-prop-inherited
12687 (org--get-local-tags))
12688 itags)))
12689 (setq itags (append org-file-tags itags))
12690 (delete-dups
12691 (append (org-remove-uninherited-tags itags) ltags))))))))
12693 (defun org-get-buffer-tags ()
12694 "Get a table of all tags used in the buffer, for completion."
12695 (org-with-point-at 1
12696 (let (tags)
12697 (while (re-search-forward org-tag-line-re nil t)
12698 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
12699 tags)))
12700 (mapcar #'list (delete-dups (append org-file-tags tags))))))
12702 ;;;; The mapping API
12704 (defvar org-agenda-skip-comment-trees)
12705 (defvar org-agenda-skip-function)
12706 (defun org-map-entries (func &optional match scope &rest skip)
12707 "Call FUNC at each headline selected by MATCH in SCOPE.
12709 FUNC is a function or a lisp form. The function will be called without
12710 arguments, with the cursor positioned at the beginning of the headline.
12711 The return values of all calls to the function will be collected and
12712 returned as a list.
12714 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12715 does not need to preserve point. After evaluation, the cursor will be
12716 moved to the end of the line (presumably of the headline of the
12717 processed entry) and search continues from there. Under some
12718 circumstances, this may not produce the wanted results. For example,
12719 if you have removed (e.g. archived) the current (sub)tree it could
12720 mean that the next entry will be skipped entirely. In such cases, you
12721 can specify the position from where search should continue by making
12722 FUNC set the variable `org-map-continue-from' to the desired buffer
12723 position.
12725 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12726 Only headlines that are matched by this query will be considered during
12727 the iteration. When MATCH is nil or t, all headlines will be
12728 visited by the iteration.
12730 SCOPE determines the scope of this command. It can be any of:
12732 nil The current buffer, respecting the restriction if any
12733 tree The subtree started with the entry at point
12734 region The entries within the active region, if any
12735 region-start-level
12736 The entries within the active region, but only those at
12737 the same level than the first one.
12738 file The current buffer, without restriction
12739 file-with-archives
12740 The current buffer, and any archives associated with it
12741 agenda All agenda files
12742 agenda-with-archives
12743 All agenda files with any archive files associated with them
12744 \(file1 file2 ...)
12745 If this is a list, all files in the list will be scanned
12747 The remaining args are treated as settings for the skipping facilities of
12748 the scanner. The following items can be given here:
12750 archive skip trees with the archive tag
12751 comment skip trees with the COMMENT keyword
12752 function or Emacs Lisp form:
12753 will be used as value for `org-agenda-skip-function', so
12754 whenever the function returns a position, FUNC will not be
12755 called for that entry and search will continue from the
12756 position returned
12758 If your function needs to retrieve the tags including inherited tags
12759 at the *current* entry, you can use the value of the variable
12760 `org-scanner-tags' which will be much faster than getting the value
12761 with `org-get-tags'. If your function gets properties with
12762 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12763 to t around the call to `org-entry-properties' to get the same speedup.
12764 Note that if your function moves around to retrieve tags and properties at
12765 a *different* entry, you cannot use these techniques."
12766 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
12767 (not (org-region-active-p)))
12768 (let* ((org-agenda-archives-mode nil) ; just to make sure
12769 (org-agenda-skip-archived-trees (memq 'archive skip))
12770 (org-agenda-skip-comment-trees (memq 'comment skip))
12771 (org-agenda-skip-function
12772 (car (org-delete-all '(comment archive) skip)))
12773 (org-tags-match-list-sublevels t)
12774 (start-level (eq scope 'region-start-level))
12775 matcher res
12776 org-todo-keywords-for-agenda
12777 org-done-keywords-for-agenda
12778 org-todo-keyword-alist-for-agenda
12779 org-tag-alist-for-agenda
12780 org--matcher-tags-todo-only)
12782 (cond
12783 ((eq match t) (setq matcher t))
12784 ((eq match nil) (setq matcher t))
12785 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12787 (save-excursion
12788 (save-restriction
12789 (cond ((eq scope 'tree)
12790 (org-back-to-heading t)
12791 (org-narrow-to-subtree)
12792 (setq scope nil))
12793 ((and (or (eq scope 'region) (eq scope 'region-start-level))
12794 (org-region-active-p))
12795 ;; If needed, set start-level to a string like "2"
12796 (when start-level
12797 (save-excursion
12798 (goto-char (region-beginning))
12799 (unless (org-at-heading-p) (outline-next-heading))
12800 (setq start-level (org-current-level))))
12801 (narrow-to-region (region-beginning)
12802 (save-excursion
12803 (goto-char (region-end))
12804 (unless (and (bolp) (org-at-heading-p))
12805 (outline-next-heading))
12806 (point)))
12807 (setq scope nil)))
12809 (if (not scope)
12810 (progn
12811 (org-agenda-prepare-buffers
12812 (and buffer-file-name (list buffer-file-name)))
12813 (setq res
12814 (org-scan-tags
12815 func matcher org--matcher-tags-todo-only start-level)))
12816 ;; Get the right scope
12817 (cond
12818 ((and scope (listp scope) (symbolp (car scope)))
12819 (setq scope (eval scope)))
12820 ((eq scope 'agenda)
12821 (setq scope (org-agenda-files t)))
12822 ((eq scope 'agenda-with-archives)
12823 (setq scope (org-agenda-files t))
12824 (setq scope (org-add-archive-files scope)))
12825 ((eq scope 'file)
12826 (setq scope (and buffer-file-name (list buffer-file-name))))
12827 ((eq scope 'file-with-archives)
12828 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12829 (org-agenda-prepare-buffers scope)
12830 (dolist (file scope)
12831 (with-current-buffer (org-find-base-buffer-visiting file)
12832 (org-with-wide-buffer
12833 (goto-char (point-min))
12834 (setq res
12835 (append
12837 (org-scan-tags
12838 func matcher org--matcher-tags-todo-only)))))))))
12839 res)))
12841 ;;; Properties API
12843 (defconst org-special-properties
12844 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
12845 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
12846 "The special properties valid in Org mode.
12847 These are properties that are not defined in the property drawer,
12848 but in some other way.")
12850 (defconst org-default-properties
12851 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12852 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12853 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12854 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
12855 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
12856 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
12857 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12858 "Some properties that are used by Org mode for various purposes.
12859 Being in this list makes sure that they are offered for completion.")
12861 (defun org--valid-property-p (property)
12862 "Non nil when string PROPERTY is a valid property name."
12863 (not
12864 (or (equal property "")
12865 (string-match-p "\\s-" property))))
12867 (defun org--update-property-plist (key val props)
12868 "Associate KEY to VAL in alist PROPS.
12869 Modifications are made by side-effect. Return new alist."
12870 (let* ((appending (string= (substring key -1) "+"))
12871 (key (if appending (substring key 0 -1) key))
12872 (old (assoc-string key props t)))
12873 (if (not old) (cons (cons key val) props)
12874 (setcdr old (if appending (concat (cdr old) " " val) val))
12875 props)))
12877 (defun org-get-property-block (&optional beg force)
12878 "Return the (beg . end) range of the body of the property drawer.
12879 BEG is the beginning of the current subtree, or of the part
12880 before the first headline. If it is not given, it will be found.
12881 If the drawer does not exist, create it if FORCE is non-nil, or
12882 return nil."
12883 (org-with-wide-buffer
12884 (when beg (goto-char beg))
12885 (unless (org-before-first-heading-p)
12886 (let ((beg (cond (beg)
12887 ((or (not (featurep 'org-inlinetask))
12888 (org-inlinetask-in-task-p))
12889 (org-back-to-heading t))
12890 (t (org-with-limited-levels (org-back-to-heading t))))))
12891 (forward-line)
12892 (when (looking-at-p org-planning-line-re) (forward-line))
12893 (cond ((looking-at org-property-drawer-re)
12894 (forward-line)
12895 (cons (point) (progn (goto-char (match-end 0))
12896 (line-beginning-position))))
12897 (force
12898 (goto-char beg)
12899 (org-insert-property-drawer)
12900 (let ((pos (save-excursion (search-forward ":END:")
12901 (line-beginning-position))))
12902 (cons pos pos))))))))
12904 (defun org-at-property-p ()
12905 "Non-nil when point is inside a property drawer.
12906 See `org-property-re' for match data, if applicable."
12907 (save-excursion
12908 (beginning-of-line)
12909 (and (looking-at org-property-re)
12910 (let ((property-drawer (save-match-data (org-get-property-block))))
12911 (and property-drawer
12912 (>= (point) (car property-drawer))
12913 (< (point) (cdr property-drawer)))))))
12915 (defun org-property-action ()
12916 "Do an action on properties."
12917 (interactive)
12918 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12919 (let ((c (read-char-exclusive)))
12920 (cl-case c
12921 (?s (call-interactively #'org-set-property))
12922 (?d (call-interactively #'org-delete-property))
12923 (?D (call-interactively #'org-delete-property-globally))
12924 (?c (call-interactively #'org-compute-property-at-point))
12925 (otherwise (user-error "No such property action %c" c)))))
12927 (defun org-inc-effort ()
12928 "Increment the value of the effort property in the current entry."
12929 (interactive)
12930 (org-set-effort t))
12932 (defvar org-clock-effort) ; Defined in org-clock.el.
12933 (defvar org-clock-current-task) ; Defined in org-clock.el.
12934 (defun org-set-effort (&optional increment value)
12935 "Set the effort property of the current entry.
12936 If INCREMENT is non-nil, set the property to the next allowed
12937 value. Otherwise, if optional argument VALUE is provided, use
12938 it. Eventually, prompt for the new value if none of the previous
12939 variables is set."
12940 (interactive "P")
12941 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
12942 (current (org-entry-get nil org-effort-property))
12943 (value
12944 (cond
12945 (increment
12946 (unless allowed (user-error "Allowed effort values are not set"))
12947 (or (cl-caadr (member (list current) allowed))
12948 (user-error "Unknown value %S among allowed values" current)))
12949 (value
12950 (if (stringp value) value
12951 (error "Invalid effort value: %S" value)))
12953 (let ((must-match
12954 (and allowed
12955 (not (get-text-property 0 'org-unrestricted
12956 (caar allowed))))))
12957 (completing-read "Effort: " allowed nil must-match))))))
12958 (unless (equal current value)
12959 (org-entry-put nil org-effort-property value))
12960 (org-refresh-property '((effort . identity)
12961 (effort-minutes . org-duration-to-minutes))
12962 value)
12963 (when (equal (org-get-heading t t t t)
12964 (bound-and-true-p org-clock-current-task))
12965 (setq org-clock-effort value)
12966 (org-clock-update-mode-line))
12967 (message "%s is now %s" org-effort-property value)))
12969 (defun org-entry-properties (&optional pom which)
12970 "Get all properties of the current entry.
12972 When POM is a buffer position, get all properties from the entry
12973 there instead.
12975 This includes the TODO keyword, the tags, time strings for
12976 deadline, scheduled, and clocking, and any additional properties
12977 defined in the entry.
12979 If WHICH is nil or `all', get all properties. If WHICH is
12980 `special' or `standard', only get that subclass. If WHICH is
12981 a string, only get that property.
12983 Return value is an alist. Keys are properties, as upcased
12984 strings."
12985 (org-with-point-at pom
12986 (when (and (derived-mode-p 'org-mode)
12987 (ignore-errors (org-back-to-heading t)))
12988 (catch 'exit
12989 (let* ((beg (point))
12990 (specific (and (stringp which) (upcase which)))
12991 (which (cond ((not specific) which)
12992 ((member specific org-special-properties) 'special)
12993 (t 'standard)))
12994 props)
12995 ;; Get the special properties, like TODO and TAGS.
12996 (when (memq which '(nil all special))
12997 (when (or (not specific) (string= specific "CLOCKSUM"))
12998 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
12999 (when clocksum
13000 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
13001 props)))
13002 (when specific (throw 'exit props)))
13003 (when (or (not specific) (string= specific "CLOCKSUM_T"))
13004 (let ((clocksumt (get-text-property (point)
13005 :org-clock-minutes-today)))
13006 (when clocksumt
13007 (push (cons "CLOCKSUM_T"
13008 (org-duration-from-minutes clocksumt))
13009 props)))
13010 (when specific (throw 'exit props)))
13011 (when (or (not specific) (string= specific "ITEM"))
13012 (let ((case-fold-search nil))
13013 (when (looking-at org-complex-heading-regexp)
13014 (push (cons "ITEM"
13015 (let ((title (match-string-no-properties 4)))
13016 (if (org-string-nw-p title)
13017 (org-remove-tabs title)
13018 "")))
13019 props)))
13020 (when specific (throw 'exit props)))
13021 (when (or (not specific) (string= specific "TODO"))
13022 (let ((case-fold-search nil))
13023 (when (and (looking-at org-todo-line-regexp) (match-end 2))
13024 (push (cons "TODO" (match-string-no-properties 2)) props)))
13025 (when specific (throw 'exit props)))
13026 (when (or (not specific) (string= specific "PRIORITY"))
13027 (push (cons "PRIORITY"
13028 (if (looking-at org-priority-regexp)
13029 (match-string-no-properties 2)
13030 (char-to-string org-default-priority)))
13031 props)
13032 (when specific (throw 'exit props)))
13033 (when (or (not specific) (string= specific "FILE"))
13034 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
13035 props)
13036 (when specific (throw 'exit props)))
13037 (when (or (not specific) (string= specific "TAGS"))
13038 (let ((tags (org-get-tags nil t)))
13039 (when tags
13040 (push (cons "TAGS" (org-make-tag-string tags))
13041 props)))
13042 (when specific (throw 'exit props)))
13043 (when (or (not specific) (string= specific "ALLTAGS"))
13044 (let ((tags (org-get-tags)))
13045 (when tags
13046 (push (cons "ALLTAGS" (org-make-tag-string tags))
13047 props)))
13048 (when specific (throw 'exit props)))
13049 (when (or (not specific) (string= specific "BLOCKED"))
13050 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
13051 (when specific (throw 'exit props)))
13052 (when (or (not specific)
13053 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
13054 (forward-line)
13055 (when (looking-at-p org-planning-line-re)
13056 (end-of-line)
13057 (let ((bol (line-beginning-position))
13058 ;; Backward compatibility: time keywords used to
13059 ;; be configurable (before 8.3). Make sure we
13060 ;; get the correct keyword.
13061 (key-assoc `(("CLOSED" . ,org-closed-string)
13062 ("DEADLINE" . ,org-deadline-string)
13063 ("SCHEDULED" . ,org-scheduled-string))))
13064 (dolist (pair (if specific (list (assoc specific key-assoc))
13065 key-assoc))
13066 (save-excursion
13067 (when (search-backward (cdr pair) bol t)
13068 (goto-char (match-end 0))
13069 (skip-chars-forward " \t")
13070 (and (looking-at org-ts-regexp-both)
13071 (push (cons (car pair)
13072 (match-string-no-properties 0))
13073 props)))))))
13074 (when specific (throw 'exit props)))
13075 (when (or (not specific)
13076 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
13077 (let ((find-ts
13078 (lambda (end ts)
13079 ;; Fix next time-stamp before END. TS is the
13080 ;; list of time-stamps found so far.
13081 (let ((ts ts)
13082 (regexp (cond
13083 ((string= specific "TIMESTAMP")
13084 org-ts-regexp)
13085 ((string= specific "TIMESTAMP_IA")
13086 org-ts-regexp-inactive)
13087 ((assoc "TIMESTAMP_IA" ts)
13088 org-ts-regexp)
13089 ((assoc "TIMESTAMP" ts)
13090 org-ts-regexp-inactive)
13091 (t org-ts-regexp-both))))
13092 (catch 'next
13093 (while (re-search-forward regexp end t)
13094 (backward-char)
13095 (let ((object (org-element-context)))
13096 ;; Accept to match timestamps in node
13097 ;; properties, too.
13098 (when (memq (org-element-type object)
13099 '(node-property timestamp))
13100 (let ((type
13101 (org-element-property :type object)))
13102 (cond
13103 ((and (memq type '(active active-range))
13104 (not (equal specific "TIMESTAMP_IA")))
13105 (unless (assoc "TIMESTAMP" ts)
13106 (push (cons "TIMESTAMP"
13107 (org-element-property
13108 :raw-value object))
13110 (when specific (throw 'exit ts))))
13111 ((and (memq type '(inactive inactive-range))
13112 (not (string= specific "TIMESTAMP")))
13113 (unless (assoc "TIMESTAMP_IA" ts)
13114 (push (cons "TIMESTAMP_IA"
13115 (org-element-property
13116 :raw-value object))
13118 (when specific (throw 'exit ts))))))
13119 ;; Both timestamp types are found,
13120 ;; move to next part.
13121 (when (= (length ts) 2) (throw 'next ts)))))
13122 ts)))))
13123 (goto-char beg)
13124 ;; First look for timestamps within headline.
13125 (let ((ts (funcall find-ts (line-end-position) nil)))
13126 (if (= (length ts) 2) (setq props (nconc ts props))
13127 ;; Then find timestamps in the section, skipping
13128 ;; planning line.
13129 (let ((end (save-excursion (outline-next-heading))))
13130 (forward-line)
13131 (when (looking-at-p org-planning-line-re) (forward-line))
13132 (setq props (nconc (funcall find-ts end ts) props))))))))
13133 ;; Get the standard properties, like :PROP:.
13134 (when (memq which '(nil all standard))
13135 ;; If we are looking after a specific property, delegate
13136 ;; to `org-entry-get', which is faster. However, make an
13137 ;; exception for "CATEGORY", since it can be also set
13138 ;; through keywords (i.e. #+CATEGORY).
13139 (if (and specific (not (equal specific "CATEGORY")))
13140 (let ((value (org-entry-get beg specific nil t)))
13141 (throw 'exit (and value (list (cons specific value)))))
13142 (let ((range (org-get-property-block beg)))
13143 (when range
13144 (let ((end (cdr range)) seen-base)
13145 (goto-char (car range))
13146 ;; Unlike to `org--update-property-plist', we
13147 ;; handle the case where base values is found
13148 ;; after its extension. We also forbid standard
13149 ;; properties to be named as special properties.
13150 (while (re-search-forward org-property-re end t)
13151 (let* ((key (upcase (match-string-no-properties 2)))
13152 (extendp (string-match-p "\\+\\'" key))
13153 (key-base (if extendp (substring key 0 -1) key))
13154 (value (match-string-no-properties 3)))
13155 (cond
13156 ((member-ignore-case key-base org-special-properties))
13157 (extendp
13158 (setq props
13159 (org--update-property-plist key value props)))
13160 ((member key seen-base))
13161 (t (push key seen-base)
13162 (let ((p (assoc-string key props t)))
13163 (if p (setcdr p (concat value " " (cdr p)))
13164 (push (cons key value) props))))))))))))
13165 (unless (assoc "CATEGORY" props)
13166 (push (cons "CATEGORY" (org-get-category beg)) props)
13167 (when (string= specific "CATEGORY") (throw 'exit props)))
13168 ;; Return value.
13169 props)))))
13171 (defun org--property-local-values (property literal-nil)
13172 "Return value for PROPERTY in current entry.
13173 Value is a list whose car is the base value for PROPERTY and cdr
13174 a list of accumulated values. Return nil if neither is found in
13175 the entry. Also return nil when PROPERTY is set to \"nil\",
13176 unless LITERAL-NIL is non-nil."
13177 (let ((range (org-get-property-block)))
13178 (when range
13179 (goto-char (car range))
13180 (let* ((case-fold-search t)
13181 (end (cdr range))
13182 (value
13183 ;; Base value.
13184 (save-excursion
13185 (let ((v (and (re-search-forward
13186 (org-re-property property nil t) end t)
13187 (match-string-no-properties 3))))
13188 (list (if literal-nil v (org-not-nil v)))))))
13189 ;; Find additional values.
13190 (let* ((property+ (org-re-property (concat property "+") nil t)))
13191 (while (re-search-forward property+ end t)
13192 (push (match-string-no-properties 3) value)))
13193 ;; Return final values.
13194 (and (not (equal value '(nil))) (nreverse value))))))
13196 (defun org--property-global-value (property literal-nil)
13197 "Return value for PROPERTY in current buffer.
13198 Return value is a string. Return nil if property is not set
13199 globally. Also return nil when PROPERTY is set to \"nil\",
13200 unless LITERAL-NIL is non-nil."
13201 (let ((global
13202 (cdr (or (assoc-string property org-file-properties t)
13203 (assoc-string property org-global-properties t)
13204 (assoc-string property org-global-properties-fixed t)))))
13205 (if literal-nil global (org-not-nil global))))
13207 (defun org-entry-get (pom property &optional inherit literal-nil)
13208 "Get value of PROPERTY for entry or content at point-or-marker POM.
13210 If INHERIT is non-nil and the entry does not have the property,
13211 then also check higher levels of the hierarchy. If INHERIT is
13212 the symbol `selective', use inheritance only if the setting in
13213 `org-use-property-inheritance' selects PROPERTY for inheritance.
13215 If the property is present but empty, the return value is the
13216 empty string. If the property is not present at all, nil is
13217 returned. In any other case, return the value as a string.
13218 Search is case-insensitive.
13220 If LITERAL-NIL is set, return the string value \"nil\" as
13221 a string, do not interpret it as the list atom nil. This is used
13222 for inheritance when a \"nil\" value can supersede a non-nil
13223 value higher up the hierarchy."
13224 (org-with-point-at pom
13225 (cond
13226 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
13227 ;; We need a special property. Use `org-entry-properties' to
13228 ;; retrieve it, but specify the wanted property.
13229 (cdr (assoc-string property (org-entry-properties nil property))))
13230 ((and inherit
13231 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
13232 (org-entry-get-with-inheritance property literal-nil))
13234 (let* ((local (org--property-local-values property literal-nil))
13235 (value (and local (mapconcat #'identity (delq nil local) " "))))
13236 (if literal-nil value (org-not-nil value)))))))
13238 (defun org-property-or-variable-value (var &optional inherit)
13239 "Check if there is a property fixing the value of VAR.
13240 If yes, return this value. If not, return the current value of the variable."
13241 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13242 (if (and prop (stringp prop) (string-match "\\S-" prop))
13243 (read prop)
13244 (symbol-value var))))
13246 (defun org-entry-delete (pom property)
13247 "Delete PROPERTY from entry at point-or-marker POM.
13248 Accumulated properties, i.e. PROPERTY+, are also removed. Return
13249 non-nil when a property was removed."
13250 (org-with-point-at pom
13251 (pcase (org-get-property-block)
13252 (`(,begin . ,origin)
13253 (let* ((end (copy-marker origin))
13254 (re (org-re-property
13255 (concat (regexp-quote property) "\\+?") t t)))
13256 (goto-char begin)
13257 (while (re-search-forward re end t)
13258 (delete-region (match-beginning 0) (line-beginning-position 2)))
13259 ;; If drawer is empty, remove it altogether.
13260 (when (= begin end)
13261 (delete-region (line-beginning-position 0)
13262 (line-beginning-position 2)))
13263 ;; Return non-nil if some property was removed.
13264 (prog1 (/= end origin) (set-marker end nil))))
13265 (_ nil))))
13267 ;; Multi-values properties are properties that contain multiple values
13268 ;; These values are assumed to be single words, separated by whitespace.
13269 (defun org-entry-add-to-multivalued-property (pom property value)
13270 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13271 (let* ((old (org-entry-get pom property))
13272 (values (and old (split-string old))))
13273 (setq value (org-entry-protect-space value))
13274 (unless (member value values)
13275 (setq values (append values (list value)))
13276 (org-entry-put pom property (mapconcat #'identity values " ")))))
13278 (defun org-entry-remove-from-multivalued-property (pom property value)
13279 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13280 (let* ((old (org-entry-get pom property))
13281 (values (and old (split-string old))))
13282 (setq value (org-entry-protect-space value))
13283 (when (member value values)
13284 (setq values (delete value values))
13285 (org-entry-put pom property (mapconcat #'identity values " ")))))
13287 (defun org-entry-member-in-multivalued-property (pom property value)
13288 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13289 (let* ((old (org-entry-get pom property))
13290 (values (and old (split-string old))))
13291 (setq value (org-entry-protect-space value))
13292 (member value values)))
13294 (defun org-entry-get-multivalued-property (pom property)
13295 "Return a list of values in a multivalued property."
13296 (let* ((value (org-entry-get pom property))
13297 (values (and value (split-string value))))
13298 (mapcar #'org-entry-restore-space values)))
13300 (defun org-entry-put-multivalued-property (pom property &rest values)
13301 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13302 VALUES should be a list of strings. Spaces will be protected."
13303 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
13304 (let* ((value (org-entry-get pom property))
13305 (values (and value (split-string value))))
13306 (mapcar #'org-entry-restore-space values)))
13308 (defun org-entry-protect-space (s)
13309 "Protect spaces and newline in string S."
13310 (while (string-match " " s)
13311 (setq s (replace-match "%20" t t s)))
13312 (while (string-match "\n" s)
13313 (setq s (replace-match "%0A" t t s)))
13316 (defun org-entry-restore-space (s)
13317 "Restore spaces and newline in string S."
13318 (while (string-match "%20" s)
13319 (setq s (replace-match " " t t s)))
13320 (while (string-match "%0A" s)
13321 (setq s (replace-match "\n" t t s)))
13324 (defvar org-entry-property-inherited-from (make-marker)
13325 "Marker pointing to the entry from where a property was inherited.
13326 Each call to `org-entry-get-with-inheritance' will set this marker to the
13327 location of the entry where the inheritance search matched. If there was
13328 no match, the marker will point nowhere.
13329 Note that also `org-entry-get' calls this function, if the INHERIT flag
13330 is set.")
13332 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13333 "Get PROPERTY of entry or content at point, search higher levels if needed.
13334 The search will stop at the first ancestor which has the property defined.
13335 If the value found is \"nil\", return nil to show that the property
13336 should be considered as undefined (this is the meaning of nil here).
13337 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13338 (move-marker org-entry-property-inherited-from nil)
13339 (org-with-wide-buffer
13340 (let (value)
13341 (catch 'exit
13342 (while t
13343 (let ((v (org--property-local-values property literal-nil)))
13344 (when v
13345 (setq value
13346 (concat (mapconcat #'identity (delq nil v) " ")
13347 (and value " ")
13348 value)))
13349 (cond
13350 ((car v)
13351 (org-back-to-heading t)
13352 (move-marker org-entry-property-inherited-from (point))
13353 (throw 'exit nil))
13354 ((org-up-heading-safe))
13356 (let ((global (org--property-global-value property literal-nil)))
13357 (cond ((not global))
13358 (value (setq value (concat global " " value)))
13359 (t (setq value global))))
13360 (throw 'exit nil))))))
13361 (if literal-nil value (org-not-nil value)))))
13363 (defvar org-property-changed-functions nil
13364 "Hook called when the value of a property has changed.
13365 Each hook function should accept two arguments, the name of the property
13366 and the new value.")
13368 (defun org-entry-put (pom property value)
13369 "Set PROPERTY to VALUE for entry at point-or-marker POM.
13371 If the value is nil, it is converted to the empty string. If it
13372 is not a string, an error is raised. Also raise an error on
13373 invalid property names.
13375 PROPERTY can be any regular property (see
13376 `org-special-properties'). It can also be \"TODO\",
13377 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
13379 For the last two properties, VALUE may have any of the special
13380 values \"earlier\" and \"later\". The function then increases or
13381 decreases scheduled or deadline date by one day."
13382 (cond ((null value) (setq value ""))
13383 ((not (stringp value)) (error "Properties values should be strings"))
13384 ((not (org--valid-property-p property))
13385 (user-error "Invalid property name: \"%s\"" property)))
13386 (org-with-point-at pom
13387 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
13388 (org-back-to-heading t)
13389 (org-with-limited-levels (org-back-to-heading t)))
13390 (let ((beg (point)))
13391 (cond
13392 ((equal property "TODO")
13393 (cond ((not (org-string-nw-p value)) (setq value 'none))
13394 ((not (member value org-todo-keywords-1))
13395 (user-error "\"%s\" is not a valid TODO state" value)))
13396 (org-todo value)
13397 (org-align-tags))
13398 ((equal property "PRIORITY")
13399 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
13400 (org-align-tags))
13401 ((equal property "SCHEDULED")
13402 (forward-line)
13403 (if (and (looking-at-p org-planning-line-re)
13404 (re-search-forward
13405 org-scheduled-time-regexp (line-end-position) t))
13406 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
13407 ((string= value "later") (org-timestamp-change 1 'day))
13408 ((string= value "") (org-schedule '(4)))
13409 (t (org-schedule nil value)))
13410 (if (member value '("earlier" "later" ""))
13411 (call-interactively #'org-schedule)
13412 (org-schedule nil value))))
13413 ((equal property "DEADLINE")
13414 (forward-line)
13415 (if (and (looking-at-p org-planning-line-re)
13416 (re-search-forward
13417 org-deadline-time-regexp (line-end-position) t))
13418 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
13419 ((string= value "later") (org-timestamp-change 1 'day))
13420 ((string= value "") (org-deadline '(4)))
13421 (t (org-deadline nil value)))
13422 (if (member value '("earlier" "later" ""))
13423 (call-interactively #'org-deadline)
13424 (org-deadline nil value))))
13425 ((member property org-special-properties)
13426 (error "The %s property cannot be set with `org-entry-put'" property))
13428 (let* ((range (org-get-property-block beg 'force))
13429 (end (cdr range))
13430 (case-fold-search t))
13431 (goto-char (car range))
13432 (if (re-search-forward (org-re-property property nil t) end t)
13433 (progn (delete-region (match-beginning 0) (match-end 0))
13434 (goto-char (match-beginning 0)))
13435 (goto-char end)
13436 (insert "\n")
13437 (backward-char))
13438 (insert ":" property ":")
13439 (when value (insert " " value))
13440 (org-indent-line)))))
13441 (run-hook-with-args 'org-property-changed-functions property value)))
13443 (defun org-buffer-property-keys (&optional specials defaults columns)
13444 "Get all property keys in the current buffer.
13446 When SPECIALS is non-nil, also list the special properties that
13447 reflect things like tags and TODO state.
13449 When DEFAULTS is non-nil, also include properties that has
13450 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
13451 DESCRIPTION, LOCATION, and LOGGING and others.
13453 When COLUMNS in non-nil, also include property names given in
13454 COLUMN formats in the current buffer."
13455 (let ((case-fold-search t)
13456 (props (append
13457 (and specials org-special-properties)
13458 (and defaults (cons org-effort-property org-default-properties))
13459 nil)))
13460 (org-with-wide-buffer
13461 (goto-char (point-min))
13462 (while (re-search-forward org-property-start-re nil t)
13463 (catch :skip
13464 (let ((range (org-get-property-block)))
13465 (unless range (throw :skip nil))
13466 (goto-char (car range))
13467 (let ((begin (car range))
13468 (end (cdr range)))
13469 ;; Make sure that found property block is not located
13470 ;; before current point, as it would generate an infloop.
13471 ;; It can happen, for example, in the following
13472 ;; situation:
13474 ;; * Headline
13475 ;; :PROPERTIES:
13476 ;; ...
13477 ;; :END:
13478 ;; *************** Inlinetask
13479 ;; #+BEGIN_EXAMPLE
13480 ;; :PROPERTIES:
13481 ;; #+END_EXAMPLE
13483 (if (< begin (point)) (throw :skip nil) (goto-char begin))
13484 (while (< (point) end)
13485 (let ((p (progn (looking-at org-property-re)
13486 (match-string-no-properties 2))))
13487 ;; Only add true property name, not extension symbol.
13488 (push (if (not (string-match-p "\\+\\'" p)) p
13489 (substring p 0 -1))
13490 props))
13491 (forward-line))))
13492 (outline-next-heading)))
13493 (when columns
13494 (goto-char (point-min))
13495 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
13496 (let ((element (org-element-at-point)))
13497 (when (memq (org-element-type element) '(keyword node-property))
13498 (let ((value (org-element-property :value element))
13499 (start 0))
13500 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
13501 \\(?:{[^}]+}\\)?"
13502 value start)
13503 (setq start (match-end 0))
13504 (let ((p (match-string-no-properties 1 value)))
13505 (unless (member-ignore-case p org-special-properties)
13506 (push p props))))))))))
13507 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
13509 (defun org-property-values (key)
13510 "List all non-nil values of property KEY in current buffer."
13511 (org-with-wide-buffer
13512 (goto-char (point-min))
13513 (let ((case-fold-search t)
13514 (re (org-re-property key))
13515 values)
13516 (while (re-search-forward re nil t)
13517 (push (org-entry-get (point) key) values))
13518 (delete-dups values))))
13520 (defun org-insert-property-drawer ()
13521 "Insert a property drawer into the current entry."
13522 (org-with-wide-buffer
13523 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
13524 (org-back-to-heading t)
13525 (org-with-limited-levels (org-back-to-heading t)))
13526 (forward-line)
13527 (when (looking-at-p org-planning-line-re) (forward-line))
13528 (unless (looking-at-p org-property-drawer-re)
13529 ;; Make sure we start editing a line from current entry, not from
13530 ;; next one. It prevents extending text properties or overlays
13531 ;; belonging to the latter.
13532 (when (bolp) (backward-char))
13533 (let ((begin (1+ (point)))
13534 (inhibit-read-only t))
13535 (insert "\n:PROPERTIES:\n:END:")
13536 (when (eobp) (insert "\n"))
13537 (org-indent-region begin (point))))))
13539 (defun org-insert-drawer (&optional arg drawer)
13540 "Insert a drawer at point.
13542 When optional argument ARG is non-nil, insert a property drawer.
13544 Optional argument DRAWER, when non-nil, is a string representing
13545 drawer's name. Otherwise, the user is prompted for a name.
13547 If a region is active, insert the drawer around that region
13548 instead.
13550 Point is left between drawer's boundaries."
13551 (interactive "P")
13552 (let* ((drawer (if arg "PROPERTIES"
13553 (or drawer (read-from-minibuffer "Drawer: ")))))
13554 (cond
13555 ;; With C-u, fall back on `org-insert-property-drawer'
13556 (arg (org-insert-property-drawer))
13557 ;; Check validity of suggested drawer's name.
13558 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
13559 (user-error "Invalid drawer name"))
13560 ;; With an active region, insert a drawer at point.
13561 ((not (org-region-active-p))
13562 (progn
13563 (unless (bolp) (insert "\n"))
13564 (insert (format ":%s:\n\n:END:\n" drawer))
13565 (forward-line -2)))
13566 ;; Otherwise, insert the drawer at point
13568 (let ((rbeg (region-beginning))
13569 (rend (copy-marker (region-end))))
13570 (unwind-protect
13571 (progn
13572 (goto-char rbeg)
13573 (beginning-of-line)
13574 (when (save-excursion
13575 (re-search-forward org-outline-regexp-bol rend t))
13576 (user-error "Drawers cannot contain headlines"))
13577 ;; Position point at the beginning of the first
13578 ;; non-blank line in region. Insert drawer's opening
13579 ;; there, then indent it.
13580 (org-skip-whitespace)
13581 (beginning-of-line)
13582 (insert ":" drawer ":\n")
13583 (forward-line -1)
13584 (indent-for-tab-command)
13585 ;; Move point to the beginning of the first blank line
13586 ;; after the last non-blank line in region. Insert
13587 ;; drawer's closing, then indent it.
13588 (goto-char rend)
13589 (skip-chars-backward " \r\t\n")
13590 (insert "\n:END:")
13591 (deactivate-mark t)
13592 (indent-for-tab-command)
13593 (unless (eolp) (insert "\n")))
13594 ;; Clear marker, whatever the outcome of insertion is.
13595 (set-marker rend nil)))))))
13597 (defvar org-property-set-functions-alist nil
13598 "Property set function alist.
13599 Each entry should have the following format:
13601 (PROPERTY . READ-FUNCTION)
13603 The read function will be called with the same argument as
13604 `org-completing-read'.")
13606 (defun org-set-property-function (property)
13607 "Get the function that should be used to set PROPERTY.
13608 This is computed according to `org-property-set-functions-alist'."
13609 (or (cdr (assoc property org-property-set-functions-alist))
13610 'org-completing-read))
13612 (defun org-read-property-value (property &optional pom)
13613 "Read value for PROPERTY, as a string.
13614 When optional argument POM is non-nil, completion uses additional
13615 information, i.e., allowed or existing values at point or marker
13616 POM."
13617 (let* ((completion-ignore-case t)
13618 (allowed
13619 (or (org-property-get-allowed-values nil property 'table)
13620 (and pom (org-property-get-allowed-values pom property 'table))))
13621 (current (org-entry-get nil property))
13622 (prompt (format "%s value%s: "
13623 property
13624 (if (org-string-nw-p current)
13625 (format " [%s]" current)
13626 "")))
13627 (set-function (org-set-property-function property)))
13628 (org-trim
13629 (if allowed
13630 (funcall set-function
13631 prompt allowed nil
13632 (not (get-text-property 0 'org-unrestricted (caar allowed))))
13633 (let ((all (mapcar #'list
13634 (append (org-property-values property)
13635 (and pom
13636 (org-with-point-at pom
13637 (org-property-values property)))))))
13638 (funcall set-function prompt all nil nil "" nil current))))))
13640 (defvar org-last-set-property nil)
13641 (defvar org-last-set-property-value nil)
13642 (defun org-read-property-name ()
13643 "Read a property name."
13644 (let ((completion-ignore-case t)
13645 (default-prop (or (and (org-at-property-p)
13646 (match-string-no-properties 2))
13647 org-last-set-property)))
13648 (org-completing-read
13649 (concat "Property"
13650 (if default-prop (concat " [" default-prop "]") "")
13651 ": ")
13652 (mapcar #'list (org-buffer-property-keys nil t t))
13653 nil nil nil nil default-prop)))
13655 (defun org-set-property-and-value (use-last)
13656 "Allow to set [PROPERTY]: [value] direction from prompt.
13657 When use-default, don't even ask, just use the last
13658 \"[PROPERTY]: [value]\" string from the history."
13659 (interactive "P")
13660 (let* ((completion-ignore-case t)
13661 (pv (or (and use-last org-last-set-property-value)
13662 (org-completing-read
13663 "Enter a \"[Property]: [value]\" pair: "
13664 nil nil nil nil nil
13665 org-last-set-property-value)))
13666 prop val)
13667 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
13668 (setq prop (match-string 1 pv)
13669 val (match-string 2 pv))
13670 (org-set-property prop val))))
13672 (defun org-set-property (property value)
13673 "In the current entry, set PROPERTY to VALUE.
13675 When called interactively, this will prompt for a property name, offering
13676 completion on existing and default properties. And then it will prompt
13677 for a value, offering completion either on allowed values (via an inherited
13678 xxx_ALL property) or on existing values in other instances of this property
13679 in the current file.
13681 Throw an error when trying to set a property with an invalid name."
13682 (interactive (list nil nil))
13683 (let ((property (or property (org-read-property-name))))
13684 ;; `org-entry-put' also makes the following check, but this one
13685 ;; avoids polluting `org-last-set-property' and
13686 ;; `org-last-set-property-value' needlessly.
13687 (unless (org--valid-property-p property)
13688 (user-error "Invalid property name: \"%s\"" property))
13689 (let ((value (or value (org-read-property-value property)))
13690 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
13691 (setq org-last-set-property property)
13692 (setq org-last-set-property-value (concat property ": " value))
13693 ;; Possibly postprocess the inserted value:
13694 (when fn (setq value (funcall fn value)))
13695 (unless (equal (org-entry-get nil property) value)
13696 (org-entry-put nil property value)))))
13698 (defun org-find-property (property &optional value)
13699 "Find first entry in buffer that sets PROPERTY.
13701 When optional argument VALUE is non-nil, only consider an entry
13702 if it contains PROPERTY set to this value. If PROPERTY should be
13703 explicitly set to nil, use string \"nil\" for VALUE.
13705 Return position where the entry begins, or nil if there is no
13706 such entry. If narrowing is in effect, only search the visible
13707 part of the buffer."
13708 (save-excursion
13709 (goto-char (point-min))
13710 (let ((case-fold-search t)
13711 (re (org-re-property property nil (not value) value)))
13712 (catch 'exit
13713 (while (re-search-forward re nil t)
13714 (when (if value (org-at-property-p)
13715 (org-entry-get (point) property nil t))
13716 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
13718 (defun org-delete-property (property)
13719 "In the current entry, delete PROPERTY."
13720 (interactive
13721 (let* ((completion-ignore-case t)
13722 (cat (org-entry-get (point) "CATEGORY"))
13723 (props0 (org-entry-properties nil 'standard))
13724 (props (if cat props0
13725 (delete `("CATEGORY" . ,(org-get-category)) props0)))
13726 (prop (if (< 1 (length props))
13727 (completing-read "Property: " props nil t)
13728 (caar props))))
13729 (list prop)))
13730 (if (not property)
13731 (message "No property to delete in this entry")
13732 (org-entry-delete nil property)
13733 (message "Property \"%s\" deleted" property)))
13735 (defun org-delete-property-globally (property)
13736 "Remove PROPERTY globally, from all entries.
13737 This function ignores narrowing, if any."
13738 (interactive
13739 (let* ((completion-ignore-case t)
13740 (prop (completing-read
13741 "Globally remove property: "
13742 (mapcar #'list (org-buffer-property-keys)))))
13743 (list prop)))
13744 (org-with-wide-buffer
13745 (goto-char (point-min))
13746 (let ((count 0)
13747 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
13748 (while (re-search-forward re nil t)
13749 (when (org-entry-delete (point) property) (cl-incf count)))
13750 (message "Property \"%s\" removed from %d entries" property count))))
13752 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13754 (defun org-compute-property-at-point ()
13755 "Compute the property at point.
13756 This looks for an enclosing column format, extracts the operator and
13757 then applies it to the property in the column format's scope."
13758 (interactive)
13759 (unless (org-at-property-p)
13760 (user-error "Not at a property"))
13761 (let ((prop (match-string-no-properties 2)))
13762 (org-columns-get-format-and-top-level)
13763 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
13764 (user-error "No operator defined for property %s" prop))
13765 (org-columns-compute prop)))
13767 (defvar org-property-allowed-value-functions nil
13768 "Hook for functions supplying allowed values for a specific property.
13769 The functions must take a single argument, the name of the property, and
13770 return a flat list of allowed values. If \":ETC\" is one of
13771 the values, this means that these values are intended as defaults for
13772 completion, but that other values should be allowed too.
13773 The functions must return nil if they are not responsible for this
13774 property.")
13776 (defun org-property-get-allowed-values (pom property &optional table)
13777 "Get allowed values for the property PROPERTY.
13778 When TABLE is non-nil, return an alist that can directly be used for
13779 completion."
13780 (let (vals)
13781 (cond
13782 ((equal property "TODO")
13783 (setq vals (org-with-point-at pom
13784 (append org-todo-keywords-1 '("")))))
13785 ((equal property "PRIORITY")
13786 (let ((n org-lowest-priority))
13787 (while (>= n org-highest-priority)
13788 (push (char-to-string n) vals)
13789 (setq n (1- n)))))
13790 ((equal property "CATEGORY"))
13791 ((member property org-special-properties))
13792 ((setq vals (run-hook-with-args-until-success
13793 'org-property-allowed-value-functions property)))
13795 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13796 (when (and vals (string-match "\\S-" vals))
13797 (setq vals (car (read-from-string (concat "(" vals ")"))))
13798 (setq vals (mapcar (lambda (x)
13799 (cond ((stringp x) x)
13800 ((numberp x) (number-to-string x))
13801 ((symbolp x) (symbol-name x))
13802 (t "???")))
13803 vals)))))
13804 (when (member ":ETC" vals)
13805 (setq vals (remove ":ETC" vals))
13806 (org-add-props (car vals) '(org-unrestricted t)))
13807 (if table (mapcar 'list vals) vals)))
13809 (defun org-property-previous-allowed-value (&optional _previous)
13810 "Switch to the next allowed value for this property."
13811 (interactive)
13812 (org-property-next-allowed-value t))
13814 (defun org-property-next-allowed-value (&optional previous)
13815 "Switch to the next allowed value for this property."
13816 (interactive)
13817 (unless (org-at-property-p)
13818 (user-error "Not at a property"))
13819 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
13820 (key (match-string 2))
13821 (value (match-string 3))
13822 (allowed (or (org-property-get-allowed-values (point) key)
13823 (and (member value '("[ ]" "[-]" "[X]"))
13824 '("[ ]" "[X]"))))
13825 (heading (save-match-data (nth 4 (org-heading-components))))
13826 nval)
13827 (unless allowed
13828 (user-error "Allowed values for this property have not been defined"))
13829 (when previous (setq allowed (reverse allowed)))
13830 (when (member value allowed)
13831 (setq nval (car (cdr (member value allowed)))))
13832 (setq nval (or nval (car allowed)))
13833 (when (equal nval value)
13834 (user-error "Only one allowed value for this property"))
13835 (org-at-property-p)
13836 (replace-match (concat " :" key ": " nval) t t)
13837 (org-indent-line)
13838 (beginning-of-line 1)
13839 (skip-chars-forward " \t")
13840 (when (equal prop org-effort-property)
13841 (org-refresh-property
13842 '((effort . identity)
13843 (effort-minutes . org-duration-to-minutes))
13844 nval)
13845 (when (string= org-clock-current-task heading)
13846 (setq org-clock-effort nval)
13847 (org-clock-update-mode-line)))
13848 (run-hook-with-args 'org-property-changed-functions key nval)))
13850 (defun org-find-olp (path &optional this-buffer)
13851 "Return a marker pointing to the entry at outline path OLP.
13852 If anything goes wrong, throw an error.
13853 You can wrap this call to catch the error like this:
13855 (condition-case msg
13856 (org-mobile-locate-entry (match-string 4))
13857 (error (nth 1 msg)))
13859 The return value will then be either a string with the error message,
13860 or a marker if everything is OK.
13862 If THIS-BUFFER is set, the outline path does not contain a file,
13863 only headings."
13864 (let* ((file (if this-buffer buffer-file-name (pop path)))
13865 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
13866 (level 1)
13867 (lmin 1)
13868 (lmax 1)
13869 end found flevel)
13870 (unless buffer (error "File not found :%s" file))
13871 (with-current-buffer buffer
13872 (unless (derived-mode-p 'org-mode)
13873 (error "Buffer %s needs to be in Org mode" buffer))
13874 (org-with-wide-buffer
13875 (goto-char (point-min))
13876 (dolist (heading path)
13877 (let ((re (format org-complex-heading-regexp-format
13878 (regexp-quote heading)))
13879 (cnt 0))
13880 (while (re-search-forward re end t)
13881 (setq level (- (match-end 1) (match-beginning 1)))
13882 (when (and (>= level lmin) (<= level lmax))
13883 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
13884 (when (= cnt 0)
13885 (error "Heading not found on level %d: %s" lmax heading))
13886 (when (> cnt 1)
13887 (error "Heading not unique on level %d: %s" lmax heading))
13888 (goto-char found)
13889 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
13890 (setq end (save-excursion (org-end-of-subtree t t)))))
13891 (when (org-at-heading-p)
13892 (point-marker))))))
13894 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
13895 "Find node HEADING in BUFFER.
13896 Return a marker to the heading if it was found, or nil if not.
13897 If POS-ONLY is set, return just the position instead of a marker.
13899 The heading text must match exact, but it may have a TODO keyword,
13900 a priority cookie and tags in the standard locations."
13901 (with-current-buffer (or buffer (current-buffer))
13902 (org-with-wide-buffer
13903 (goto-char (point-min))
13904 (let (case-fold-search)
13905 (when (re-search-forward
13906 (format org-complex-heading-regexp-format
13907 (regexp-quote heading)) nil t)
13908 (if pos-only
13909 (match-beginning 0)
13910 (move-marker (make-marker) (match-beginning 0))))))))
13912 (defun org-find-exact-heading-in-directory (heading &optional dir)
13913 "Find Org node headline HEADING in all \".org\" files in directory DIR.
13914 When the target headline is found, return a marker to this location."
13915 (let ((files (directory-files (or dir default-directory)
13916 t "\\`[^.#].*\\.org\\'"))
13917 visiting m buffer)
13918 (catch 'found
13919 (dolist (file files)
13920 (message "trying %s" file)
13921 (setq visiting (org-find-base-buffer-visiting file))
13922 (setq buffer (or visiting (find-file-noselect file)))
13923 (setq m (org-find-exact-headline-in-buffer
13924 heading buffer))
13925 (when (and (not m) (not visiting)) (kill-buffer buffer))
13926 (and m (throw 'found m))))))
13928 (defun org-find-entry-with-id (ident)
13929 "Locate the entry that contains the ID property with exact value IDENT.
13930 IDENT can be a string, a symbol or a number, this function will search for
13931 the string representation of it.
13932 Return the position where this entry starts, or nil if there is no such entry."
13933 (interactive "sID: ")
13934 (let ((id (cond
13935 ((stringp ident) ident)
13936 ((symbolp ident) (symbol-name ident))
13937 ((numberp ident) (number-to-string ident))
13938 (t (error "IDENT %s must be a string, symbol or number" ident)))))
13939 (org-with-wide-buffer (org-find-property "ID" id))))
13941 ;;;; Timestamps
13943 (defvar org-last-changed-timestamp nil)
13944 (defvar org-last-inserted-timestamp nil
13945 "The last time stamp inserted with `org-insert-time-stamp'.")
13947 (defun org-time-stamp (arg &optional inactive)
13948 "Prompt for a date/time and insert a time stamp.
13950 If the user specifies a time like HH:MM or if this command is
13951 called with at least one prefix argument, the time stamp contains
13952 the date and the time. Otherwise, only the date is included.
13954 All parts of a date not specified by the user are filled in from
13955 the timestamp at point, if any, or the current date/time
13956 otherwise.
13958 If there is already a timestamp at the cursor, it is replaced.
13960 With two universal prefix arguments, insert an active timestamp
13961 with the current time without prompting the user.
13963 When called from lisp, the timestamp is inactive if INACTIVE is
13964 non-nil."
13965 (interactive "P")
13966 (let* ((ts (cond
13967 ((org-at-date-range-p t)
13968 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
13969 ((org-at-timestamp-p 'lax) (match-string 0))))
13970 ;; Default time is either the timestamp at point or today.
13971 ;; When entering a range, only the range start is considered.
13972 (default-time (and ts
13973 (apply #'encode-time (org-parse-time-string ts))))
13974 (default-input (and ts (org-get-compact-tod ts)))
13975 (repeater (and ts
13976 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
13977 (match-string 0 ts)))
13978 org-time-was-given
13979 org-end-time-was-given
13980 (time
13981 (if (equal arg '(16)) (current-time)
13982 ;; Preserve `this-command' and `last-command'.
13983 (let ((this-command this-command)
13984 (last-command last-command))
13985 (org-read-date
13986 arg 'totime nil nil default-time default-input
13987 inactive)))))
13988 (cond
13989 ((and ts
13990 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13991 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13992 (insert "--")
13993 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13995 ;; Make sure we're on a timestamp. When in the middle of a date
13996 ;; range, move arbitrarily to range end.
13997 (unless (org-at-timestamp-p 'lax)
13998 (skip-chars-forward "-")
13999 (org-at-timestamp-p 'lax))
14000 (replace-match "")
14001 (setq org-last-changed-timestamp
14002 (org-insert-time-stamp
14003 time (or org-time-was-given arg)
14004 inactive nil nil (list org-end-time-was-given)))
14005 (when repeater
14006 (backward-char)
14007 (insert " " repeater)
14008 (setq org-last-changed-timestamp
14009 (concat (substring org-last-inserted-timestamp 0 -1)
14010 " " repeater ">")))
14011 (message "Timestamp updated"))
14012 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
14013 (t (org-insert-time-stamp
14014 time (or org-time-was-given arg) inactive nil nil
14015 (list org-end-time-was-given))))))
14017 ;; FIXME: can we use this for something else, like computing time differences?
14018 (defun org-get-compact-tod (s)
14019 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14020 (let* ((t1 (match-string 1 s))
14021 (h1 (string-to-number (match-string 2 s)))
14022 (m1 (string-to-number (match-string 3 s)))
14023 (t2 (and (match-end 4) (match-string 5 s)))
14024 (h2 (and t2 (string-to-number (match-string 6 s))))
14025 (m2 (and t2 (string-to-number (match-string 7 s))))
14026 dh dm)
14027 (if (not t2)
14029 (setq dh (- h2 h1) dm (- m2 m1))
14030 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14031 (concat t1 "+" (number-to-string dh)
14032 (and (/= 0 dm) (format ":%02d" dm)))))))
14034 (defun org-time-stamp-inactive (&optional arg)
14035 "Insert an inactive time stamp.
14037 An inactive time stamp is enclosed in square brackets instead of angle
14038 brackets. It is inactive in the sense that it does not trigger agenda entries,
14039 does not link to the calendar and cannot be changed with the S-cursor keys.
14040 So these are more for recording a certain time/date.
14042 If the user specifies a time like HH:MM or if this command is called with
14043 at least one prefix argument, the time stamp contains the date and the time.
14044 Otherwise, only the date is included.
14046 When called with two universal prefix arguments, insert an active time stamp
14047 with the current time without prompting the user."
14048 (interactive "P")
14049 (org-time-stamp arg 'inactive))
14051 (defvar org-date-ovl (make-overlay 1 1))
14052 (overlay-put org-date-ovl 'face 'org-date-selected)
14053 (delete-overlay org-date-ovl)
14055 (defvar org-ans1) ; dynamically scoped parameter
14056 (defvar org-ans2) ; dynamically scoped parameter
14058 (defvar org-plain-time-of-day-regexp) ; defined below
14060 (defvar org-overriding-default-time nil) ; dynamically scoped
14061 (defvar org-read-date-overlay nil)
14062 (defvar org-dcst nil) ; dynamically scoped
14063 (defvar org-read-date-history nil)
14064 (defvar org-read-date-final-answer nil)
14065 (defvar org-read-date-analyze-futurep nil)
14066 (defvar org-read-date-analyze-forced-year nil)
14067 (defvar org-read-date-inactive)
14068 (defvar org-def)
14069 (defvar org-defdecode)
14070 (defvar org-with-time)
14072 (defvar calendar-setup) ; Dynamically scoped.
14073 (defun org-read-date (&optional with-time to-time from-string prompt
14074 default-time default-input inactive)
14075 "Read a date, possibly a time, and make things smooth for the user.
14076 The prompt will suggest to enter an ISO date, but you can also enter anything
14077 which will at least partially be understood by `parse-time-string'.
14078 Unrecognized parts of the date will default to the current day, month, year,
14079 hour and minute. If this command is called to replace a timestamp at point,
14080 or to enter the second timestamp of a range, the default time is taken
14081 from the existing stamp. Furthermore, the command prefers the future,
14082 so if you are giving a date where the year is not given, and the day-month
14083 combination is already past in the current year, it will assume you
14084 mean next year. For details, see the manual. A few examples:
14086 3-2-5 --> 2003-02-05
14087 feb 15 --> currentyear-02-15
14088 2/15 --> currentyear-02-15
14089 sep 12 9 --> 2009-09-12
14090 12:45 --> today 12:45
14091 22 sept 0:34 --> currentyear-09-22 0:34
14092 12 --> currentyear-currentmonth-12
14093 Fri --> nearest Friday after today
14094 -Tue --> last Tuesday
14095 etc.
14097 Furthermore you can specify a relative date by giving, as the *first* thing
14098 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
14099 change in days weeks, months, years.
14100 With a single plus or minus, the date is relative to today. With a double
14101 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14102 +4d --> four days from today
14103 +4 --> same as above
14104 +2w --> two weeks from today
14105 ++5 --> five days from default date
14107 The function understands only English month and weekday abbreviations.
14109 While prompting, a calendar is popped up - you can also select the
14110 date with the mouse (button 1). The calendar shows a period of three
14111 months. To scroll it to other months, use the keys `>' and `<'.
14112 If you don't like the calendar, turn it off with
14113 (setq org-read-date-popup-calendar nil)
14115 With optional argument TO-TIME, the date will immediately be converted
14116 to an internal time.
14117 With an optional argument WITH-TIME, the prompt will suggest to
14118 also insert a time. Note that when WITH-TIME is not set, you can
14119 still enter a time, and this function will inform the calling routine
14120 about this change. The calling routine may then choose to change the
14121 format used to insert the time stamp into the buffer to include the time.
14122 With optional argument FROM-STRING, read from this string instead from
14123 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14124 the time/date that is used for everything that is not specified by the
14125 user."
14126 (require 'parse-time)
14127 (let* ((org-with-time with-time)
14128 (org-time-stamp-rounding-minutes
14129 (if (equal org-with-time '(16))
14130 '(0 0)
14131 org-time-stamp-rounding-minutes))
14132 (org-dcst org-display-custom-times)
14133 (ct (org-current-time))
14134 (org-def (or org-overriding-default-time default-time ct))
14135 (org-defdecode (decode-time org-def))
14136 (cur-frame (selected-frame))
14137 (mouse-autoselect-window nil) ; Don't let the mouse jump
14138 (calendar-setup
14139 (and (eq calendar-setup 'calendar-only) 'calendar-only))
14140 (calendar-move-hook nil)
14141 (calendar-view-diary-initially-flag nil)
14142 (calendar-view-holidays-initially-flag nil)
14143 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
14144 ;; Rationalize `org-def' and `org-defdecode', if required.
14145 (when (< (nth 2 org-defdecode) org-extend-today-until)
14146 (setf (nth 2 org-defdecode) -1)
14147 (setf (nth 1 org-defdecode) 59)
14148 (setq org-def (apply #'encode-time org-defdecode))
14149 (setq org-defdecode (decode-time org-def)))
14150 (let* ((timestr (format-time-string
14151 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
14152 org-def))
14153 (prompt (concat (if prompt (concat prompt " ") "")
14154 (format "Date+time [%s]: " timestr))))
14155 (cond
14156 (from-string (setq ans from-string))
14157 (org-read-date-popup-calendar
14158 (save-excursion
14159 (save-window-excursion
14160 (calendar)
14161 (when (eq calendar-setup 'calendar-only)
14162 (setq cal-frame
14163 (window-frame (get-buffer-window "*Calendar*" 'visible)))
14164 (select-frame cal-frame))
14165 (org-eval-in-calendar '(setq cursor-type nil) t)
14166 (unwind-protect
14167 (progn
14168 (calendar-forward-day (- (time-to-days org-def)
14169 (calendar-absolute-from-gregorian
14170 (calendar-current-date))))
14171 (org-eval-in-calendar nil t)
14172 (let* ((old-map (current-local-map))
14173 (map (copy-keymap calendar-mode-map))
14174 (minibuffer-local-map
14175 (copy-keymap org-read-date-minibuffer-local-map)))
14176 (org-defkey map (kbd "RET") 'org-calendar-select)
14177 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14178 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14179 (unwind-protect
14180 (progn
14181 (use-local-map map)
14182 (setq org-read-date-inactive inactive)
14183 (add-hook 'post-command-hook 'org-read-date-display)
14184 (setq org-ans0
14185 (read-string prompt
14186 default-input
14187 'org-read-date-history
14188 nil))
14189 ;; org-ans0: from prompt
14190 ;; org-ans1: from mouse click
14191 ;; org-ans2: from calendar motion
14192 (setq ans
14193 (concat org-ans0 " " (or org-ans1 org-ans2))))
14194 (remove-hook 'post-command-hook 'org-read-date-display)
14195 (use-local-map old-map)
14196 (when org-read-date-overlay
14197 (delete-overlay org-read-date-overlay)
14198 (setq org-read-date-overlay nil)))))
14199 (bury-buffer "*Calendar*")
14200 (when cal-frame
14201 (delete-frame cal-frame)
14202 (select-frame-set-input-focus cur-frame))))))
14204 (t ; Naked prompt only
14205 (unwind-protect
14206 (setq ans (read-string prompt default-input
14207 'org-read-date-history timestr))
14208 (when org-read-date-overlay
14209 (delete-overlay org-read-date-overlay)
14210 (setq org-read-date-overlay nil))))))
14212 (setq final (org-read-date-analyze ans org-def org-defdecode))
14214 (when org-read-date-analyze-forced-year
14215 (message "Year was forced into %s"
14216 (if org-read-date-force-compatible-dates
14217 "compatible range (1970-2037)"
14218 "range representable on this machine"))
14219 (ding))
14221 ;; One round trip to get rid of 34th of August and stuff like that....
14222 (setq final (decode-time (apply 'encode-time final)))
14224 (setq org-read-date-final-answer ans)
14226 (if to-time
14227 (apply 'encode-time final)
14228 (if (and (boundp 'org-time-was-given) org-time-was-given)
14229 (format "%04d-%02d-%02d %02d:%02d"
14230 (nth 5 final) (nth 4 final) (nth 3 final)
14231 (nth 2 final) (nth 1 final))
14232 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14234 (defun org-read-date-display ()
14235 "Display the current date prompt interpretation in the minibuffer."
14236 (when org-read-date-display-live
14237 (when org-read-date-overlay
14238 (delete-overlay org-read-date-overlay))
14239 (when (minibufferp (current-buffer))
14240 (save-excursion
14241 (end-of-line 1)
14242 (while (not (equal (buffer-substring
14243 (max (point-min) (- (point) 4)) (point))
14244 " "))
14245 (insert " ")))
14246 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14247 " " (or org-ans1 org-ans2)))
14248 (org-end-time-was-given nil)
14249 (f (org-read-date-analyze ans org-def org-defdecode))
14250 (fmts (if org-dcst
14251 org-time-stamp-custom-formats
14252 org-time-stamp-formats))
14253 (fmt (if (or org-with-time
14254 (and (boundp 'org-time-was-given) org-time-was-given))
14255 (cdr fmts)
14256 (car fmts)))
14257 (txt (format-time-string fmt (apply 'encode-time f)))
14258 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
14259 (txt (concat "=> " txt)))
14260 (when (and org-end-time-was-given
14261 (string-match org-plain-time-of-day-regexp txt))
14262 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14263 org-end-time-was-given
14264 (substring txt (match-end 0)))))
14265 (when org-read-date-analyze-futurep
14266 (setq txt (concat txt " (=>F)")))
14267 (setq org-read-date-overlay
14268 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14269 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
14271 (defun org-read-date-analyze (ans def defdecode)
14272 "Analyze the combined answer of the date prompt."
14273 ;; FIXME: cleanup and comment
14274 (let ((org-def def)
14275 (org-defdecode defdecode)
14276 (nowdecode (decode-time))
14277 delta deltan deltaw deltadef year month day
14278 hour minute second wday pm h2 m2 tl wday1
14279 iso-year iso-weekday iso-week iso-date futurep kill-year)
14280 (setq org-read-date-analyze-futurep nil
14281 org-read-date-analyze-forced-year nil)
14282 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14283 (setq ans "+0"))
14285 (when (setq delta (org-read-date-get-relative ans nil org-def))
14286 (setq ans (replace-match "" t t ans)
14287 deltan (car delta)
14288 deltaw (nth 1 delta)
14289 deltadef (nth 2 delta)))
14291 ;; Check if there is an iso week date in there. If yes, store the
14292 ;; info and postpone interpreting it until the rest of the parsing
14293 ;; is done.
14294 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14295 (setq iso-year (when (match-end 1)
14296 (org-small-year-to-year
14297 (string-to-number (match-string 1 ans))))
14298 iso-weekday (when (match-end 3)
14299 (string-to-number (match-string 3 ans)))
14300 iso-week (string-to-number (match-string 2 ans)))
14301 (setq ans (replace-match "" t t ans)))
14303 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14304 (when (string-match
14305 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14306 (setq year (if (match-end 2)
14307 (string-to-number (match-string 2 ans))
14308 (progn (setq kill-year t)
14309 (string-to-number (format-time-string "%Y"))))
14310 month (string-to-number (match-string 3 ans))
14311 day (string-to-number (match-string 4 ans)))
14312 (setq year (org-small-year-to-year year))
14313 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14314 t nil ans)))
14316 ;; Help matching dotted european dates
14317 (when (string-match
14318 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
14319 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
14320 (setq kill-year t)
14321 (string-to-number (format-time-string "%Y")))
14322 day (string-to-number (match-string 1 ans))
14323 month (string-to-number (match-string 2 ans))
14324 ans (replace-match (format "%04d-%02d-%02d" year month day)
14325 t nil ans)))
14327 ;; Help matching american dates, like 5/30 or 5/30/7
14328 (when (string-match
14329 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14330 (setq year (if (match-end 4)
14331 (string-to-number (match-string 4 ans))
14332 (progn (setq kill-year t)
14333 (string-to-number (format-time-string "%Y"))))
14334 month (string-to-number (match-string 1 ans))
14335 day (string-to-number (match-string 2 ans)))
14336 (setq year (org-small-year-to-year year))
14337 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14338 t nil ans)))
14339 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14340 ;; If there is a time with am/pm, and *no* time without it, we convert
14341 ;; so that matching will be successful.
14342 (cl-loop for i from 1 to 2 do ; twice, for end time as well
14343 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14344 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14345 (setq hour (string-to-number (match-string 1 ans))
14346 minute (if (match-end 3)
14347 (string-to-number (match-string 3 ans))
14349 pm (equal ?p
14350 (string-to-char (downcase (match-string 4 ans)))))
14351 (if (and (= hour 12) (not pm))
14352 (setq hour 0)
14353 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
14354 (setq ans (replace-match (format "%02d:%02d" hour minute)
14355 t t ans))))
14357 ;; Check if a time range is given as a duration
14358 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14359 (setq hour (string-to-number (match-string 1 ans))
14360 h2 (+ hour (string-to-number (match-string 3 ans)))
14361 minute (string-to-number (match-string 2 ans))
14362 m2 (+ minute (if (match-end 5) (string-to-number
14363 (match-string 5 ans))0)))
14364 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14365 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14366 t t ans)))
14368 ;; Check if there is a time range
14369 (when (boundp 'org-end-time-was-given)
14370 (setq org-time-was-given nil)
14371 (when (and (string-match org-plain-time-of-day-regexp ans)
14372 (match-end 8))
14373 (setq org-end-time-was-given (match-string 8 ans))
14374 (setq ans (concat (substring ans 0 (match-beginning 7))
14375 (substring ans (match-end 7))))))
14377 (setq tl (parse-time-string ans)
14378 day (or (nth 3 tl) (nth 3 org-defdecode))
14379 month
14380 (cond ((nth 4 tl))
14381 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
14382 ;; Day was specified. Make sure DAY+MONTH
14383 ;; combination happens in the future.
14384 ((nth 3 tl)
14385 (setq futurep t)
14386 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
14387 (nth 4 nowdecode)))
14388 (t (nth 4 org-defdecode)))
14389 year
14390 (cond ((and (not kill-year) (nth 5 tl)))
14391 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
14392 ;; Month was guessed in the future and is at least
14393 ;; equal to NOWDECODE's. Fix year accordingly.
14394 (futurep
14395 (if (or (> month (nth 4 nowdecode))
14396 (>= day (nth 3 nowdecode)))
14397 (nth 5 nowdecode)
14398 (1+ (nth 5 nowdecode))))
14399 ;; Month was specified. Make sure MONTH+YEAR
14400 ;; combination happens in the future.
14401 ((nth 4 tl)
14402 (setq futurep t)
14403 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
14404 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
14405 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
14406 (t (nth 5 nowdecode))))
14407 (t (nth 5 org-defdecode)))
14408 hour (or (nth 2 tl) (nth 2 org-defdecode))
14409 minute (or (nth 1 tl) (nth 1 org-defdecode))
14410 second (or (nth 0 tl) 0)
14411 wday (nth 6 tl))
14413 (when (and (eq org-read-date-prefer-future 'time)
14414 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14415 (equal day (nth 3 nowdecode))
14416 (equal month (nth 4 nowdecode))
14417 (equal year (nth 5 nowdecode))
14418 (nth 2 tl)
14419 (or (< (nth 2 tl) (nth 2 nowdecode))
14420 (and (= (nth 2 tl) (nth 2 nowdecode))
14421 (nth 1 tl)
14422 (< (nth 1 tl) (nth 1 nowdecode)))))
14423 (setq day (1+ day)
14424 futurep t))
14426 ;; Special date definitions below
14427 (cond
14428 (iso-week
14429 ;; There was an iso week
14430 (require 'cal-iso)
14431 (setq futurep nil)
14432 (setq year (or iso-year year)
14433 day (or iso-weekday wday 1)
14434 wday nil ; to make sure that the trigger below does not match
14435 iso-date (calendar-gregorian-from-absolute
14436 (calendar-iso-to-absolute
14437 (list iso-week day year))))
14438 ; FIXME: Should we also push ISO weeks into the future?
14439 ; (when (and org-read-date-prefer-future
14440 ; (not iso-year)
14441 ; (< (calendar-absolute-from-gregorian iso-date)
14442 ; (time-to-days nil)))
14443 ; (setq year (1+ year)
14444 ; iso-date (calendar-gregorian-from-absolute
14445 ; (calendar-iso-to-absolute
14446 ; (list iso-week day year)))))
14447 (setq month (car iso-date)
14448 year (nth 2 iso-date)
14449 day (nth 1 iso-date)))
14450 (deltan
14451 (setq futurep nil)
14452 (unless deltadef
14453 (let ((now (decode-time)))
14454 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14455 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14456 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14457 ((equal deltaw "m") (setq month (+ month deltan)))
14458 ((equal deltaw "y") (setq year (+ year deltan)))))
14459 ((and wday (not (nth 3 tl)))
14460 ;; Weekday was given, but no day, so pick that day in the week
14461 ;; on or after the derived date.
14462 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14463 (unless (equal wday wday1)
14464 (setq day (+ day (% (- wday wday1 -7) 7))))))
14465 (when (and (boundp 'org-time-was-given)
14466 (nth 2 tl))
14467 (setq org-time-was-given t))
14468 (when (< year 100) (setq year (+ 2000 year)))
14469 ;; Check of the date is representable
14470 (if org-read-date-force-compatible-dates
14471 (progn
14472 (when (< year 1970)
14473 (setq year 1970 org-read-date-analyze-forced-year t))
14474 (when (> year 2037)
14475 (setq year 2037 org-read-date-analyze-forced-year t)))
14476 (condition-case nil
14477 (ignore (encode-time second minute hour day month year))
14478 (error
14479 (setq year (nth 5 org-defdecode))
14480 (setq org-read-date-analyze-forced-year t))))
14481 (setq org-read-date-analyze-futurep futurep)
14482 (list second minute hour day month year)))
14484 (defvar parse-time-weekdays)
14485 (defun org-read-date-get-relative (s today default)
14486 "Check string S for special relative date string.
14487 TODAY and DEFAULT are internal times, for today and for a default.
14488 Return shift list (N what def-flag)
14489 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14490 N is the number of WHATs to shift.
14491 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14492 the DEFAULT date rather than TODAY."
14493 (require 'parse-time)
14494 (when (and
14495 (string-match
14496 (concat
14497 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14498 "\\([0-9]+\\)?"
14499 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14500 "\\([ \t]\\|$\\)") s)
14501 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14502 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14503 (string-to-char (substring (match-string 1 s) -1))
14504 ?+))
14505 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14506 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14507 (what (if (match-end 3) (match-string 3 s) "d"))
14508 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14509 (date (if rel default today))
14510 (wday (nth 6 (decode-time date)))
14511 delta)
14512 (if wday1
14513 (progn
14514 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14515 (when (= delta 0) (setq delta 7))
14516 (when (= dir ?-)
14517 (setq delta (- delta 7))
14518 (when (= delta 0) (setq delta -7)))
14519 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14520 (list delta "d" rel))
14521 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14523 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14524 "Turn a user-specified date into the internal representation.
14525 The internal representation needed by the calendar is (month day year).
14526 This is a wrapper to handle the brain-dead convention in calendar that
14527 user function argument order change dependent on argument order."
14528 (pcase calendar-date-style
14529 (`american (list arg1 arg2 arg3))
14530 (`european (list arg2 arg1 arg3))
14531 (`iso (list arg2 arg3 arg1))))
14533 (defun org-eval-in-calendar (form &optional keepdate)
14534 "Eval FORM in the calendar window and return to current window.
14535 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
14536 (let ((sf (selected-frame))
14537 (sw (selected-window)))
14538 (select-window (get-buffer-window "*Calendar*" t))
14539 (eval form)
14540 (when (and (not keepdate) (calendar-cursor-to-date))
14541 (let* ((date (calendar-cursor-to-date))
14542 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14543 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14544 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14545 (select-window sw)
14546 (select-frame-set-input-focus sf)))
14548 (defun org-calendar-select ()
14549 "Return to `org-read-date' with the date currently selected.
14550 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14551 (interactive)
14552 (when (calendar-cursor-to-date)
14553 (let* ((date (calendar-cursor-to-date))
14554 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14555 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14556 (when (active-minibuffer-window) (exit-minibuffer))))
14558 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14559 "Insert a date stamp for the date given by the internal TIME.
14560 See `format-time-string' for the format of TIME.
14561 WITH-HM means use the stamp format that includes the time of the day.
14562 INACTIVE means use square brackets instead of angular ones, so that the
14563 stamp will not contribute to the agenda.
14564 PRE and POST are optional strings to be inserted before and after the
14565 stamp.
14566 The command returns the inserted time stamp."
14567 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14568 stamp)
14569 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14570 (insert-before-markers (or pre ""))
14571 (when (listp extra)
14572 (setq extra (car extra))
14573 (if (and (stringp extra)
14574 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14575 (setq extra (format "-%02d:%02d"
14576 (string-to-number (match-string 1 extra))
14577 (string-to-number (match-string 2 extra))))
14578 (setq extra nil)))
14579 (when extra
14580 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14581 (insert-before-markers (setq stamp (format-time-string fmt time)))
14582 (insert-before-markers (or post ""))
14583 (setq org-last-inserted-timestamp stamp)))
14585 (defun org-toggle-time-stamp-overlays ()
14586 "Toggle the use of custom time stamp formats."
14587 (interactive)
14588 (setq org-display-custom-times (not org-display-custom-times))
14589 (unless org-display-custom-times
14590 (let ((p (point-min)) (bmp (buffer-modified-p)))
14591 (while (setq p (next-single-property-change p 'display))
14592 (when (and (get-text-property p 'display)
14593 (eq (get-text-property p 'face) 'org-date))
14594 (remove-text-properties
14595 p (setq p (next-single-property-change p 'display))
14596 '(display t))))
14597 (set-buffer-modified-p bmp)))
14598 (org-restart-font-lock)
14599 (setq org-table-may-need-update t)
14600 (if org-display-custom-times
14601 (message "Time stamps are overlaid with custom format")
14602 (message "Time stamp overlays removed")))
14604 (defun org-display-custom-time (beg end)
14605 "Overlay modified time stamp format over timestamp between BEG and END."
14606 (let* ((ts (buffer-substring beg end))
14607 t1 with-hm tf time str (off 0))
14608 (save-match-data
14609 (setq t1 (org-parse-time-string ts t))
14610 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
14611 (setq off (- (match-end 0) (match-beginning 0)))))
14612 (setq end (- end off))
14613 (setq with-hm (and (nth 1 t1) (nth 2 t1))
14614 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14615 time (org-fix-decoded-time t1)
14616 str (org-add-props
14617 (format-time-string
14618 (substring tf 1 -1) (apply 'encode-time time))
14619 nil 'mouse-face 'highlight))
14620 (put-text-property beg end 'display str)))
14622 (defun org-fix-decoded-time (time)
14623 "Set 0 instead of nil for the first 6 elements of time.
14624 Don't touch the rest."
14625 (let ((n 0))
14626 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14628 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
14629 "Difference between TIMESTAMP-STRING and now in days.
14630 If SECONDS is non-nil, return the difference in seconds."
14631 (let ((fdiff (if seconds #'float-time #'time-to-days)))
14632 (- (funcall fdiff (org-time-string-to-time timestamp-string))
14633 (funcall fdiff nil))))
14635 (defun org-deadline-close-p (timestamp-string &optional ndays)
14636 "Is the time in TIMESTAMP-STRING close to the current date?"
14637 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14638 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
14639 (not (org-entry-is-done-p))))
14641 (defun org-get-wdays (ts &optional delay zero-delay)
14642 "Get the deadline lead time appropriate for timestring TS.
14643 When DELAY is non-nil, get the delay time for scheduled items
14644 instead of the deadline lead time. When ZERO-DELAY is non-nil
14645 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
14646 don't try to find the delay cookie in the scheduled timestamp."
14647 (let ((tv (if delay org-scheduled-delay-days
14648 org-deadline-warning-days)))
14649 (cond
14650 ((or (and delay (< tv 0))
14651 (and delay zero-delay (<= tv 0))
14652 (and (not delay) (<= tv 0)))
14653 ;; Enforce this value no matter what
14654 (- tv))
14655 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
14656 ;; lead time is specified.
14657 (floor (* (string-to-number (match-string 1 ts))
14658 (cdr (assoc (match-string 2 ts)
14659 '(("d" . 1) ("w" . 7)
14660 ("m" . 30.4) ("y" . 365.25)
14661 ("h" . 0.041667)))))))
14662 ;; go for the default.
14663 (t tv))))
14665 (defun org-calendar-select-mouse (ev)
14666 "Return to `org-read-date' with the date currently selected.
14667 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14668 (interactive "e")
14669 (mouse-set-point ev)
14670 (when (calendar-cursor-to-date)
14671 (let* ((date (calendar-cursor-to-date))
14672 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14673 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14674 (when (active-minibuffer-window) (exit-minibuffer))))
14676 (defun org-check-deadlines (ndays)
14677 "Check if there are any deadlines due or past due.
14678 A deadline is considered due if it happens within `org-deadline-warning-days'
14679 days from today's date. If the deadline appears in an entry marked DONE,
14680 it is not shown. A numeric prefix argument NDAYS can be used to test that
14681 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
14682 are shown."
14683 (interactive "P")
14684 (let* ((org-warn-days
14685 (cond
14686 ((equal ndays '(4)) 100000)
14687 (ndays (prefix-numeric-value ndays))
14688 (t (abs org-deadline-warning-days))))
14689 (case-fold-search nil)
14690 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14691 (callback
14692 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
14693 (message "%d deadlines past-due or due within %d days"
14694 (org-occur regexp nil callback)
14695 org-warn-days)))
14697 (defsubst org-re-timestamp (type)
14698 "Return a regexp for timestamp TYPE.
14699 Allowed values for TYPE are:
14701 all: all timestamps
14702 active: only active timestamps (<...>)
14703 inactive: only inactive timestamps ([...])
14704 scheduled: only scheduled timestamps
14705 deadline: only deadline timestamps
14706 closed: only closed time-stamps
14708 When TYPE is nil, fall back on returning a regexp that matches
14709 both scheduled and deadline timestamps."
14710 (cl-case type
14711 (all org-ts-regexp-both)
14712 (active org-ts-regexp)
14713 (inactive org-ts-regexp-inactive)
14714 (scheduled org-scheduled-time-regexp)
14715 (deadline org-deadline-time-regexp)
14716 (closed org-closed-time-regexp)
14717 (otherwise
14718 (concat "\\<"
14719 (regexp-opt (list org-deadline-string org-scheduled-string))
14720 " *<\\([^>]+\\)>"))))
14722 (defun org-check-before-date (d)
14723 "Check if there are deadlines or scheduled entries before date D."
14724 (interactive (list (org-read-date)))
14725 (let* ((case-fold-search nil)
14726 (regexp (org-re-timestamp org-ts-type))
14727 (ts-type org-ts-type)
14728 (callback
14729 (lambda ()
14730 (let ((match (match-string 1)))
14731 (and (if (memq ts-type '(active inactive all))
14732 (eq (org-element-type (save-excursion
14733 (backward-char)
14734 (org-element-context)))
14735 'timestamp)
14736 (org-at-planning-p))
14737 (time-less-p
14738 (org-time-string-to-time match)
14739 (org-time-string-to-time d)))))))
14740 (message "%d entries before %s"
14741 (org-occur regexp nil callback)
14742 d)))
14744 (defun org-check-after-date (d)
14745 "Check if there are deadlines or scheduled entries after date D."
14746 (interactive (list (org-read-date)))
14747 (let* ((case-fold-search nil)
14748 (regexp (org-re-timestamp org-ts-type))
14749 (ts-type org-ts-type)
14750 (callback
14751 (lambda ()
14752 (let ((match (match-string 1)))
14753 (and (if (memq ts-type '(active inactive all))
14754 (eq (org-element-type (save-excursion
14755 (backward-char)
14756 (org-element-context)))
14757 'timestamp)
14758 (org-at-planning-p))
14759 (not (time-less-p
14760 (org-time-string-to-time match)
14761 (org-time-string-to-time d))))))))
14762 (message "%d entries after %s"
14763 (org-occur regexp nil callback)
14764 d)))
14766 (defun org-check-dates-range (start-date end-date)
14767 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
14768 (interactive (list (org-read-date nil nil nil "Range starts")
14769 (org-read-date nil nil nil "Range end")))
14770 (let ((case-fold-search nil)
14771 (regexp (org-re-timestamp org-ts-type))
14772 (callback
14773 (let ((type org-ts-type))
14774 (lambda ()
14775 (let ((match (match-string 1)))
14776 (and
14777 (if (memq type '(active inactive all))
14778 (eq (org-element-type (save-excursion
14779 (backward-char)
14780 (org-element-context)))
14781 'timestamp)
14782 (org-at-planning-p))
14783 (not (time-less-p
14784 (org-time-string-to-time match)
14785 (org-time-string-to-time start-date)))
14786 (time-less-p
14787 (org-time-string-to-time match)
14788 (org-time-string-to-time end-date))))))))
14789 (message "%d entries between %s and %s"
14790 (org-occur regexp nil callback) start-date end-date)))
14792 (defun org-evaluate-time-range (&optional to-buffer)
14793 "Evaluate a time range by computing the difference between start and end.
14794 Normally the result is just printed in the echo area, but with prefix arg
14795 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14796 If the time range is actually in a table, the result is inserted into the
14797 next column.
14798 For time difference computation, a year is assumed to be exactly 365
14799 days in order to avoid rounding problems."
14800 (interactive "P")
14802 (org-clock-update-time-maybe)
14803 (save-excursion
14804 (unless (org-at-date-range-p t)
14805 (goto-char (point-at-bol))
14806 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14807 (unless (org-at-date-range-p t)
14808 (user-error "Not at a time-stamp range, and none found in current line")))
14809 (let* ((ts1 (match-string 1))
14810 (ts2 (match-string 2))
14811 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14812 (match-end (match-end 0))
14813 (time1 (org-time-string-to-time ts1))
14814 (time2 (org-time-string-to-time ts2))
14815 (diff (abs (float-time (time-subtract time2 time1))))
14816 (negative (time-less-p time2 time1))
14817 ;; (ys (floor (* 365 24 60 60)))
14818 (ds (* 24 60 60))
14819 (hs (* 60 60))
14820 (fy "%dy %dd %02d:%02d")
14821 (fy1 "%dy %dd")
14822 (fd "%dd %02d:%02d")
14823 (fd1 "%dd")
14824 (fh "%02d:%02d")
14825 y d h m align)
14826 (if havetime
14827 (setq ; y (floor diff ys) diff (mod diff ys)
14829 d (floor diff ds) diff (mod diff ds)
14830 h (floor diff hs) diff (mod diff hs)
14831 m (floor diff 60))
14832 (setq ; y (floor diff ys) diff (mod diff ys)
14834 d (round diff ds)
14835 h 0 m 0))
14836 (if (not to-buffer)
14837 (message "%s" (org-make-tdiff-string y d h m))
14838 (if (org-at-table-p)
14839 (progn
14840 (goto-char match-end)
14841 (setq align t)
14842 (and (looking-at " *|") (goto-char (match-end 0))))
14843 (goto-char match-end))
14844 (when (looking-at
14845 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14846 (replace-match ""))
14847 (when negative (insert " -"))
14848 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14849 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14850 (insert " " (format fh h m))))
14851 (when align (org-table-align))
14852 (message "Time difference inserted")))))
14854 (defun org-make-tdiff-string (y d h m)
14855 (let ((fmt "")
14856 (l nil))
14857 (when (> y 0)
14858 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
14859 (push y l))
14860 (when (> d 0)
14861 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
14862 (push d l))
14863 (when (> h 0)
14864 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
14865 (push h l))
14866 (when (> m 0)
14867 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
14868 (push m l))
14869 (apply 'format fmt (nreverse l))))
14871 (defun org-time-string-to-time (s)
14872 "Convert timestamp string S into internal time."
14873 (apply #'encode-time (org-parse-time-string s)))
14875 (defun org-time-string-to-seconds (s)
14876 "Convert a timestamp string S into a number of seconds."
14877 (float-time (org-time-string-to-time s)))
14879 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
14881 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
14882 "Convert time stamp S to an absolute day number.
14884 If DAYNR in non-nil, and there is a specifier for a cyclic time
14885 stamp, get the closest date to DAYNR. If PREFER is
14886 `past' (respectively `future') return a date past (respectively
14887 after) or equal to DAYNR.
14889 POS is the location of time stamp S, as a buffer position in
14890 BUFFER.
14892 Diary sexp timestamps are matched against DAYNR, when non-nil.
14893 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
14894 signaled."
14895 (cond
14896 ((string-match "\\`%%\\((.*)\\)" s)
14897 ;; Sexp timestamp: try to match DAYNR, if available, since we're
14898 ;; only able to match individual dates. If it fails, raise an
14899 ;; error.
14900 (if (and daynr
14901 (org-diary-sexp-entry
14902 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
14903 daynr
14904 (signal 'org-diary-sexp-no-match (list s))))
14905 (daynr (org-closest-date s daynr prefer))
14906 (t (time-to-days
14907 (condition-case errdata
14908 (apply #'encode-time (org-parse-time-string s))
14909 (error (error "Bad timestamp `%s'%s\nError was: %s"
14911 (if (not (and buffer pos)) ""
14912 (format-message " at %d in buffer `%s'" pos buffer))
14913 (cdr errdata))))))))
14915 (defun org-days-to-iso-week (days)
14916 "Return the iso week number."
14917 (require 'cal-iso)
14918 (car (calendar-iso-from-absolute days)))
14920 (defun org-small-year-to-year (year)
14921 "Convert 2-digit years into 4-digit years.
14922 YEAR is expanded into one of the 30 next years, if possible, or
14923 into a past one. Any year larger than 99 is returned unchanged."
14924 (if (>= year 100) year
14925 (let* ((current (string-to-number (format-time-string "%Y")))
14926 (century (/ current 100))
14927 (offset (- year (% current 100))))
14928 (cond ((> offset 30) (+ (* (1- century) 100) year))
14929 ((> offset -70) (+ (* century 100) year))
14930 (t (+ (* (1+ century) 100) year))))))
14932 (defun org-time-from-absolute (d)
14933 "Return the time corresponding to date D.
14934 D may be an absolute day number, or a calendar-type list (month day year)."
14935 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14936 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14938 (defvar org-agenda-current-date)
14939 (defun org-calendar-holiday ()
14940 "List of holidays, for Diary display in Org mode."
14941 (require 'holidays)
14942 (let ((hl (calendar-check-holidays org-agenda-current-date)))
14943 (and hl (mapconcat #'identity hl "; "))))
14945 (defun org-diary-sexp-entry (sexp entry d)
14946 "Process a SEXP diary ENTRY for date D."
14947 (require 'diary-lib)
14948 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
14949 ;; dynamically.
14950 (let* ((sexp `(let ((entry ,entry)
14951 (date ',d))
14952 ,(car (read-from-string sexp))))
14953 (result (if calendar-debug-sexp (eval sexp)
14954 (condition-case nil
14955 (eval sexp)
14956 (error
14957 (beep)
14958 (message "Bad sexp at line %d in %s: %s"
14959 (org-current-line)
14960 (buffer-file-name) sexp)
14961 (sleep-for 2))))))
14962 (cond ((stringp result) (split-string result "; "))
14963 ((and (consp result)
14964 (not (consp (cdr result)))
14965 (stringp (cdr result))) (cdr result))
14966 ((and (consp result)
14967 (stringp (car result))) result)
14968 (result entry))))
14970 (defun org-diary-to-ical-string (frombuf)
14971 "Get iCalendar entries from diary entries in buffer FROMBUF.
14972 This uses the icalendar.el library."
14973 (let* ((tmpdir temporary-file-directory)
14974 (tmpfile (make-temp-name
14975 (expand-file-name "orgics" tmpdir)))
14976 buf rtn b e)
14977 (with-current-buffer frombuf
14978 (icalendar-export-region (point-min) (point-max) tmpfile)
14979 (setq buf (find-buffer-visiting tmpfile))
14980 (set-buffer buf)
14981 (goto-char (point-min))
14982 (when (re-search-forward "^BEGIN:VEVENT" nil t)
14983 (setq b (match-beginning 0)))
14984 (goto-char (point-max))
14985 (when (re-search-backward "^END:VEVENT" nil t)
14986 (setq e (match-end 0)))
14987 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14988 (kill-buffer buf)
14989 (delete-file tmpfile)
14990 rtn))
14992 (defun org-closest-date (start current prefer)
14993 "Return closest date to CURRENT starting from START.
14995 CURRENT and START are both time stamps.
14997 When PREFER is `past', return a date that is either CURRENT or
14998 past. When PREFER is `future', return a date that is either
14999 CURRENT or future.
15001 Only time stamps with a repeater are modified. Any other time
15002 stamp stay unchanged. In any case, return value is an absolute
15003 day number."
15004 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
15005 ;; No repeater. Do not shift time stamp.
15006 (time-to-days (apply #'encode-time (org-parse-time-string start)))
15007 (let ((value (string-to-number (match-string 1 start)))
15008 (type (match-string 2 start)))
15009 (if (= 0 value)
15010 ;; Repeater with a 0-value is considered as void.
15011 (time-to-days (apply #'encode-time (org-parse-time-string start)))
15012 (let* ((base (org-date-to-gregorian start))
15013 (target (org-date-to-gregorian current))
15014 (sday (calendar-absolute-from-gregorian base))
15015 (cday (calendar-absolute-from-gregorian target))
15016 n1 n2)
15017 ;; If START is already past CURRENT, just return START.
15018 (if (<= cday sday) sday
15019 ;; Compute closest date before (N1) and closest date past
15020 ;; (N2) CURRENT.
15021 (pcase type
15022 ("h"
15023 (let ((missing-hours
15024 (mod (+ (- (* 24 (- cday sday))
15025 (nth 2 (org-parse-time-string start)))
15026 org-extend-today-until)
15027 value)))
15028 (setf n1 (if (= missing-hours 0) cday
15029 (- cday (1+ (/ missing-hours 24)))))
15030 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
15031 ((or "d" "w")
15032 (let ((value (if (equal type "w") (* 7 value) value)))
15033 (setf n1 (+ sday (* value (/ (- cday sday) value))))
15034 (setf n2 (+ n1 value))))
15035 ("m"
15036 (let* ((add-months
15037 (lambda (d n)
15038 ;; Add N months to gregorian date D, i.e.,
15039 ;; a list (MONTH DAY YEAR). Return a valid
15040 ;; gregorian date.
15041 (let ((m (+ (nth 0 d) n)))
15042 (list (mod m 12)
15043 (nth 1 d)
15044 (+ (/ m 12) (nth 2 d))))))
15045 (months ; Complete months to TARGET.
15046 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
15047 (- (nth 0 target) (nth 0 base))
15048 ;; If START's day is greater than
15049 ;; TARGET's, remove incomplete month.
15050 (if (> (nth 1 target) (nth 1 base)) 0 -1))
15051 value)
15052 value))
15053 (before (funcall add-months base months)))
15054 (setf n1 (calendar-absolute-from-gregorian before))
15055 (setf n2
15056 (calendar-absolute-from-gregorian
15057 (funcall add-months before value)))))
15059 (let* ((d (nth 1 base))
15060 (m (nth 0 base))
15061 (y (nth 2 base))
15062 (years ; Complete years to TARGET.
15063 (* (/ (- (nth 2 target)
15065 ;; If START's month and day are
15066 ;; greater than TARGET's, remove
15067 ;; incomplete year.
15068 (if (or (> (nth 0 target) m)
15069 (and (= (nth 0 target) m)
15070 (> (nth 1 target) d)))
15073 value)
15074 value))
15075 (before (list m d (+ y years))))
15076 (setf n1 (calendar-absolute-from-gregorian before))
15077 (setf n2 (calendar-absolute-from-gregorian
15078 (list m d (+ (nth 2 before) value)))))))
15079 ;; Handle PREFER parameter, if any.
15080 (cond
15081 ((eq prefer 'past) (if (= cday n2) n2 n1))
15082 ((eq prefer 'future) (if (= cday n1) n1 n2))
15083 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
15085 (defun org-date-to-gregorian (d)
15086 "Turn any specification of date D into a Gregorian date for the calendar."
15087 (cond ((integerp d) (calendar-gregorian-from-absolute d))
15088 ((and (listp d) (= (length d) 3)) d)
15089 ((stringp d)
15090 (let ((d (org-parse-time-string d)))
15091 (list (nth 4 d) (nth 3 d) (nth 5 d))))
15092 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
15094 (defun org-timestamp-up (&optional arg)
15095 "Increase the date item at the cursor by one.
15096 If the cursor is on the year, change the year. If it is on the month,
15097 the day or the time, change that. If the cursor is on the enclosing
15098 bracket, change the timestamp type.
15099 With prefix ARG, change by that many units."
15100 (interactive "p")
15101 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15103 (defun org-timestamp-down (&optional arg)
15104 "Decrease the date item at the cursor by one.
15105 If the cursor is on the year, change the year. If it is on the month,
15106 the day or the time, change that. If the cursor is on the enclosing
15107 bracket, change the timestamp type.
15108 With prefix ARG, change by that many units."
15109 (interactive "p")
15110 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15112 (defun org-timestamp-up-day (&optional arg)
15113 "Increase the date in the time stamp by one day.
15114 With prefix ARG, change that many days."
15115 (interactive "p")
15116 (if (and (not (org-at-timestamp-p 'lax))
15117 (org-at-heading-p))
15118 (org-todo 'up)
15119 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15121 (defun org-timestamp-down-day (&optional arg)
15122 "Decrease the date in the time stamp by one day.
15123 With prefix ARG, change that many days."
15124 (interactive "p")
15125 (if (and (not (org-at-timestamp-p 'lax))
15126 (org-at-heading-p))
15127 (org-todo 'down)
15128 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15130 (defun org-at-timestamp-p (&optional extended)
15131 "Non-nil if point is inside a timestamp.
15133 By default, the function only consider syntactically valid active
15134 timestamps. However, the caller may have a broader definition
15135 for timestamps. As a consequence, optional argument EXTENDED can
15136 be set to the following values
15138 `inactive'
15140 Include also syntactically valid inactive timestamps.
15142 `agenda'
15144 Include timestamps allowed in Agenda, i.e., those in
15145 properties drawers, planning lines and clock lines.
15147 `lax'
15149 Ignore context. The function matches any part of the
15150 document looking like a timestamp. This includes comments,
15151 example blocks...
15153 For backward-compatibility with Org 9.0, every other non-nil
15154 value is equivalent to `inactive'.
15156 When at a timestamp, return the position of the point as a symbol
15157 among `bracket', `after', `year', `month', `hour', `minute',
15158 `day' or a number of character from the last know part of the
15159 time stamp.
15161 When matching, the match groups are the following:
15162 group 1: year
15163 group 2: month
15164 group 3: day number
15165 group 4: day name
15166 group 5: hours, if any
15167 group 6: minutes, if any"
15168 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
15169 (pos (point))
15170 (match?
15171 (let ((boundaries (org-in-regexp regexp)))
15172 (save-match-data
15173 (cond ((null boundaries) nil)
15174 ((eq extended 'lax) t)
15176 (or (and (eq extended 'agenda)
15177 (or (org-at-planning-p)
15178 (org-at-property-p)
15179 (and (bound-and-true-p
15180 org-agenda-include-inactive-timestamps)
15181 (org-at-clock-log-p))))
15182 (eq 'timestamp
15183 (save-excursion
15184 (when (= pos (cdr boundaries)) (forward-char -1))
15185 (org-element-type (org-element-context)))))))))))
15186 (cond
15187 ((not match?) nil)
15188 ((= pos (match-beginning 0)) 'bracket)
15189 ;; Distinguish location right before the closing bracket from
15190 ;; right after it.
15191 ((= pos (1- (match-end 0))) 'bracket)
15192 ((= pos (match-end 0)) 'after)
15193 ((org-pos-in-match-range pos 2) 'year)
15194 ((org-pos-in-match-range pos 3) 'month)
15195 ((org-pos-in-match-range pos 7) 'hour)
15196 ((org-pos-in-match-range pos 8) 'minute)
15197 ((or (org-pos-in-match-range pos 4)
15198 (org-pos-in-match-range pos 5)) 'day)
15199 ((and (> pos (or (match-end 8) (match-end 5)))
15200 (< pos (match-end 0)))
15201 (- pos (or (match-end 8) (match-end 5))))
15202 (t 'day))))
15204 (defun org-toggle-timestamp-type ()
15205 "Toggle the type (<active> or [inactive]) of a time stamp."
15206 (interactive)
15207 (when (org-at-timestamp-p 'lax)
15208 (let ((beg (match-beginning 0)) (end (match-end 0))
15209 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15210 (save-excursion
15211 (goto-char beg)
15212 (while (re-search-forward "[][<>]" end t)
15213 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15214 t t)))
15215 (message "Timestamp is now %sactive"
15216 (if (equal (char-after beg) ?<) "" "in")))))
15218 (defun org-at-clock-log-p ()
15219 "Non-nil if point is on a clock log line."
15220 (and (org-match-line org-clock-line-re)
15221 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
15223 (defvar org-clock-history) ; defined in org-clock.el
15224 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
15225 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
15226 "Change the date in the time stamp at point.
15227 The date will be changed by N times WHAT. WHAT can be `day', `month',
15228 `year', `minute', `second'. If WHAT is not given, the cursor position
15229 in the timestamp determines what will be changed.
15230 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
15231 (let ((origin (point))
15232 (timestamp? (org-at-timestamp-p 'lax))
15233 origin-cat
15234 with-hm inactive
15235 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15236 extra rem
15237 ts time time0 fixnext clrgx)
15238 (unless timestamp? (user-error "Not at a timestamp"))
15239 (if (and (not what) (eq timestamp? 'bracket))
15240 (org-toggle-timestamp-type)
15241 ;; Point isn't on brackets. Remember the part of the time-stamp
15242 ;; the point was in. Indeed, size of time-stamps may change,
15243 ;; but point must be kept in the same category nonetheless.
15244 (setq origin-cat timestamp?)
15245 (when (and (not what) (not (eq timestamp? 'day))
15246 org-display-custom-times
15247 (get-text-property (point) 'display)
15248 (not (get-text-property (1- (point)) 'display)))
15249 (setq timestamp? 'day))
15250 (setq timestamp? (or what timestamp?)
15251 inactive (= (char-after (match-beginning 0)) ?\[)
15252 ts (match-string 0))
15253 (replace-match "")
15254 (when (string-match
15255 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
15257 (setq extra (match-string 1 ts))
15258 (when suppress-tmp-delay
15259 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
15260 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15261 (setq with-hm t))
15262 (setq time0 (org-parse-time-string ts))
15263 (when (and updown
15264 (eq timestamp? 'minute)
15265 (not current-prefix-arg))
15266 ;; This looks like s-up and s-down. Change by one rounding step.
15267 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15268 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
15269 (setcar (cdr time0) (+ (nth 1 time0)
15270 (if (> n 0) (- rem) (- dm rem))))))
15271 (setq time
15272 (apply #'encode-time
15273 (or (car time0) 0)
15274 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
15275 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
15276 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
15277 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
15278 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
15279 (nthcdr 6 time0)))
15280 (when (and (memq timestamp? '(hour minute))
15281 extra
15282 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15283 (setq extra (org-modify-ts-extra
15284 extra
15285 (if (eq timestamp? 'hour) 2 5)
15286 n dm)))
15287 (when (integerp timestamp?)
15288 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
15289 (when (eq what 'calendar)
15290 (let ((cal-date (org-get-date-from-calendar)))
15291 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15292 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15293 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15294 (setcar time0 (or (car time0) 0))
15295 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15296 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15297 (setq time (apply 'encode-time time0))))
15298 ;; Insert the new time-stamp, and ensure point stays in the same
15299 ;; category as before (i.e. not after the last position in that
15300 ;; category).
15301 (let ((pos (point)))
15302 ;; Stay before inserted string. `save-excursion' is of no use.
15303 (setq org-last-changed-timestamp
15304 (org-insert-time-stamp time with-hm inactive nil nil extra))
15305 (goto-char pos))
15306 (save-match-data
15307 (looking-at org-ts-regexp3)
15308 (goto-char
15309 (pcase origin-cat
15310 ;; `day' category ends before `hour' if any, or at the end
15311 ;; of the day name.
15312 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
15313 (`hour (min (match-end 7) origin))
15314 (`minute (min (1- (match-end 8)) origin))
15315 ((pred integerp) (min (1- (match-end 0)) origin))
15316 ;; Point was right after the time-stamp. However, the
15317 ;; time-stamp length might have changed, so refer to
15318 ;; (match-end 0) instead.
15319 (`after (match-end 0))
15320 ;; `year' and `month' have both fixed size: point couldn't
15321 ;; have moved into another part.
15322 (_ origin))))
15323 ;; Update clock if on a CLOCK line.
15324 (org-clock-update-time-maybe)
15325 ;; Maybe adjust the closest clock in `org-clock-history'
15326 (when org-clock-adjust-closest
15327 (if (not (and (org-at-clock-log-p)
15328 (< 1 (length (delq nil (mapcar 'marker-position
15329 org-clock-history))))))
15330 (message "No clock to adjust")
15331 (cond ((save-excursion ; fix previous clock?
15332 (re-search-backward org-ts-regexp0 nil t)
15333 (looking-back (concat org-clock-string " \\[")
15334 (line-beginning-position)))
15335 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
15336 ((save-excursion ; fix next clock?
15337 (re-search-backward org-ts-regexp0 nil t)
15338 (looking-at (concat org-ts-regexp0 "\\] =>")))
15339 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
15340 (save-window-excursion
15341 ;; Find closest clock to point, adjust the previous/next one in history
15342 (let* ((p (save-excursion (org-back-to-heading t)))
15343 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
15344 (clfixnth
15345 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
15346 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
15347 (if (not clfixpos)
15348 (message "No clock to adjust")
15349 (save-excursion
15350 (org-goto-marker-or-bmk clfixpos)
15351 (org-show-subtree)
15352 (when (re-search-forward clrgx nil t)
15353 (goto-char (match-beginning 1))
15354 (let (org-clock-adjust-closest)
15355 (org-timestamp-change n timestamp? updown))
15356 (message "Clock adjusted in %s for heading: %s"
15357 (file-name-nondirectory (buffer-file-name))
15358 (org-get-heading t t)))))))))
15359 ;; Try to recenter the calendar window, if any.
15360 (when (and org-calendar-follow-timestamp-change
15361 (get-buffer-window "*Calendar*" t)
15362 (memq timestamp? '(day month year)))
15363 (org-recenter-calendar (time-to-days time))))))
15365 (defun org-modify-ts-extra (s pos n dm)
15366 "Change the different parts of the lead-time and repeat fields in timestamp."
15367 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15368 ng h m new rem)
15369 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15370 (cond
15371 ((or (org-pos-in-match-range pos 2)
15372 (org-pos-in-match-range pos 3))
15373 (setq m (string-to-number (match-string 3 s))
15374 h (string-to-number (match-string 2 s)))
15375 (if (org-pos-in-match-range pos 2)
15376 (setq h (+ h n))
15377 (setq n (* dm (with-no-warnings (cl-signum n))))
15378 (unless (= 0 (setq rem (% m dm)))
15379 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15380 (setq m (+ m n)))
15381 (when (< m 0) (setq m (+ m 60) h (1- h)))
15382 (when (> m 59) (setq m (- m 60) h (1+ h)))
15383 (setq h (mod h 24))
15384 (setq ng 1 new (format "-%02d:%02d" h m)))
15385 ((org-pos-in-match-range pos 6)
15386 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15387 ((org-pos-in-match-range pos 5)
15388 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15390 ((org-pos-in-match-range pos 9)
15391 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15392 ((org-pos-in-match-range pos 8)
15393 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15395 (when ng
15396 (setq s (concat
15397 (substring s 0 (match-beginning ng))
15399 (substring s (match-end ng))))))
15402 (defun org-recenter-calendar (d)
15403 "If the calendar is visible, recenter it to date D."
15404 (let ((cwin (get-buffer-window "*Calendar*" t)))
15405 (when cwin
15406 (let ((calendar-move-hook nil))
15407 (with-selected-window cwin
15408 (calendar-goto-date
15409 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
15411 (defun org-goto-calendar (&optional arg)
15412 "Go to the Emacs calendar at the current date.
15413 If there is a time stamp in the current line, go to that date.
15414 A prefix ARG can be used to force the current date."
15415 (interactive "P")
15416 (let ((calendar-move-hook nil)
15417 (calendar-view-holidays-initially-flag nil)
15418 (calendar-view-diary-initially-flag nil)
15419 diff)
15420 (when (or (org-at-timestamp-p 'lax)
15421 (org-match-line (concat ".*" org-ts-regexp)))
15422 (let ((d1 (time-to-days nil))
15423 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
15424 (setq diff (- d2 d1))))
15425 (calendar)
15426 (calendar-goto-today)
15427 (when (and diff (not arg)) (calendar-forward-day diff))))
15429 (defun org-get-date-from-calendar ()
15430 "Return a list (month day year) of date at point in calendar."
15431 (with-current-buffer "*Calendar*"
15432 (save-match-data
15433 (calendar-cursor-to-date))))
15435 (defun org-date-from-calendar ()
15436 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15437 If there is already a time stamp at the cursor position, update it."
15438 (interactive)
15439 (if (org-at-timestamp-p 'lax)
15440 (org-timestamp-change 0 'calendar)
15441 (let ((cal-date (org-get-date-from-calendar)))
15442 (org-insert-time-stamp
15443 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15445 (defcustom org-image-actual-width t
15446 "Should we use the actual width of images when inlining them?
15448 When set to t, always use the image width.
15450 When set to a number, use imagemagick (when available) to set
15451 the image's width to this value.
15453 When set to a number in a list, try to get the width from any
15454 #+ATTR.* keyword if it matches a width specification like
15456 #+ATTR_HTML: :width 300px
15458 and fall back on that number if none is found.
15460 When set to nil, try to get the width from an #+ATTR.* keyword
15461 and fall back on the original width if none is found.
15463 This requires Emacs >= 24.1, build with imagemagick support."
15464 :group 'org-appearance
15465 :version "24.4"
15466 :package-version '(Org . "8.0")
15467 :type '(choice
15468 (const :tag "Use the image width" t)
15469 (integer :tag "Use a number of pixels")
15470 (list :tag "Use #+ATTR* or a number of pixels" (integer))
15471 (const :tag "Use #+ATTR* or don't resize" nil)))
15473 (defcustom org-agenda-inhibit-startup nil
15474 "Inhibit startup when preparing agenda buffers.
15475 When this variable is t, the initialization of the Org agenda
15476 buffers is inhibited: e.g. the visibility state is not set, the
15477 tables are not re-aligned, etc."
15478 :type 'boolean
15479 :version "24.3"
15480 :group 'org-agenda)
15482 (defcustom org-agenda-ignore-properties nil
15483 "Avoid updating text properties when building the agenda.
15484 Properties are used to prepare buffers for effort estimates,
15485 appointments, statistics and subtree-local categories.
15486 If you don't use these in the agenda, you can add them to this
15487 list and agenda building will be a bit faster.
15488 The value is a list, with zero or more of the symbols `effort', `appt',
15489 `stats' or `category'."
15490 :type '(set :greedy t
15491 (const effort)
15492 (const appt)
15493 (const stats)
15494 (const category))
15495 :version "26.1"
15496 :package-version '(Org . "8.3")
15497 :group 'org-agenda)
15499 ;;;; Files
15501 (defun org-save-all-org-buffers ()
15502 "Save all Org buffers without user confirmation."
15503 (interactive)
15504 (message "Saving all Org buffers...")
15505 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
15506 (when (featurep 'org-id) (org-id-locations-save))
15507 (message "Saving all Org buffers... done"))
15509 (defun org-revert-all-org-buffers ()
15510 "Revert all Org buffers.
15511 Prompt for confirmation when there are unsaved changes.
15512 Be sure you know what you are doing before letting this function
15513 overwrite your changes.
15515 This function is useful in a setup where one tracks Org files
15516 with a version control system, to revert on one machine after pulling
15517 changes from another. I believe the procedure must be like this:
15519 1. M-x org-save-all-org-buffers
15520 2. Pull changes from the other machine, resolve conflicts
15521 3. M-x org-revert-all-org-buffers"
15522 (interactive)
15523 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15524 (user-error "Abort"))
15525 (save-excursion
15526 (save-window-excursion
15527 (dolist (b (buffer-list))
15528 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
15529 (with-current-buffer b buffer-file-name))
15530 (pop-to-buffer-same-window b)
15531 (revert-buffer t 'no-confirm)))
15532 (when (and (featurep 'org-id) org-id-track-globally)
15533 (org-id-locations-load)))))
15535 ;;;; Agenda files
15537 ;;;###autoload
15538 (defun org-switchb (&optional arg)
15539 "Switch between Org buffers.
15541 With `\\[universal-argument]' prefix, restrict available buffers to files.
15543 With `\\[universal-argument] \\[universal-argument]' \
15544 prefix, restrict available buffers to agenda files."
15545 (interactive "P")
15546 (let ((blist (org-buffer-list
15547 (cond ((equal arg '(4)) 'files)
15548 ((equal arg '(16)) 'agenda)))))
15549 (pop-to-buffer-same-window
15550 (completing-read "Org buffer: "
15551 (mapcar #'list (mapcar #'buffer-name blist))
15552 nil t))))
15554 (defun org-buffer-list (&optional predicate exclude-tmp)
15555 "Return a list of Org buffers.
15556 PREDICATE can be `export', `files' or `agenda'.
15558 export restrict the list to Export buffers.
15559 files restrict the list to buffers visiting Org files.
15560 agenda restrict the list to buffers visiting agenda files.
15562 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15563 (let* ((bfn nil)
15564 (agenda-files (and (eq predicate 'agenda)
15565 (mapcar 'file-truename (org-agenda-files t))))
15566 (filter
15567 (cond
15568 ((eq predicate 'files)
15569 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
15570 ((eq predicate 'export)
15571 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
15572 ((eq predicate 'agenda)
15573 (lambda (b)
15574 (with-current-buffer b
15575 (and (derived-mode-p 'org-mode)
15576 (setq bfn (buffer-file-name b))
15577 (member (file-truename bfn) agenda-files)))))
15578 (t (lambda (b) (with-current-buffer b
15579 (or (derived-mode-p 'org-mode)
15580 (string-match "\\*Org .*Export"
15581 (buffer-name b)))))))))
15582 (delq nil
15583 (mapcar
15584 (lambda(b)
15585 (if (and (funcall filter b)
15586 (or (not exclude-tmp)
15587 (not (string-match "tmp" (buffer-name b)))))
15589 nil))
15590 (buffer-list)))))
15592 (defun org-agenda-files (&optional unrestricted archives)
15593 "Get the list of agenda files.
15594 Optional UNRESTRICTED means return the full list even if a restriction
15595 is currently in place.
15596 When ARCHIVES is t, include all archive files that are really being
15597 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15598 `org-agenda-archives-mode' is t."
15599 (let ((files
15600 (cond
15601 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15602 ((stringp org-agenda-files) (org-read-agenda-file-list))
15603 ((listp org-agenda-files) org-agenda-files)
15604 (t (error "Invalid value of `org-agenda-files'")))))
15605 (setq files (apply 'append
15606 (mapcar (lambda (f)
15607 (if (file-directory-p f)
15608 (directory-files
15609 f t org-agenda-file-regexp)
15610 (list f)))
15611 files)))
15612 (when org-agenda-skip-unavailable-files
15613 (setq files (delq nil
15614 (mapcar (function
15615 (lambda (file)
15616 (and (file-readable-p file) file)))
15617 files))))
15618 (when (or (eq archives t)
15619 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15620 (setq files (org-add-archive-files files)))
15621 files))
15623 (defun org-agenda-file-p (&optional file)
15624 "Return non-nil, if FILE is an agenda file.
15625 If FILE is omitted, use the file associated with the current
15626 buffer."
15627 (let ((fname (or file (buffer-file-name))))
15628 (and fname
15629 (member (file-truename fname)
15630 (mapcar #'file-truename (org-agenda-files t))))))
15632 (defun org-edit-agenda-file-list ()
15633 "Edit the list of agenda files.
15634 Depending on setup, this either uses customize to edit the variable
15635 `org-agenda-files', or it visits the file that is holding the list. In the
15636 latter case, the buffer is set up in a way that saving it automatically kills
15637 the buffer and restores the previous window configuration."
15638 (interactive)
15639 (if (stringp org-agenda-files)
15640 (let ((cw (current-window-configuration)))
15641 (find-file org-agenda-files)
15642 (setq-local org-window-configuration cw)
15643 (add-hook 'after-save-hook
15644 (lambda ()
15645 (set-window-configuration
15646 (prog1 org-window-configuration
15647 (kill-buffer (current-buffer))))
15648 (org-install-agenda-files-menu)
15649 (message "New agenda file list installed"))
15650 nil 'local)
15651 (message "%s" (substitute-command-keys
15652 "Edit list and finish with \\[save-buffer]")))
15653 (customize-variable 'org-agenda-files)))
15655 (defun org-store-new-agenda-file-list (list)
15656 "Set new value for the agenda file list and save it correctly."
15657 (if (stringp org-agenda-files)
15658 (let ((fe (org-read-agenda-file-list t)) b u)
15659 (while (setq b (find-buffer-visiting org-agenda-files))
15660 (kill-buffer b))
15661 (with-temp-file org-agenda-files
15662 (insert
15663 (mapconcat
15664 (lambda (f) ;; Keep un-expanded entries.
15665 (if (setq u (assoc f fe))
15666 (cdr u)
15668 list "\n")
15669 "\n")))
15670 (let ((org-mode-hook nil) (org-inhibit-startup t)
15671 (org-insert-mode-line-in-empty-file nil))
15672 (setq org-agenda-files list)
15673 (customize-save-variable 'org-agenda-files org-agenda-files))))
15675 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15676 "Read the list of agenda files from a file.
15677 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15678 filenames, used by `org-store-new-agenda-file-list' to write back
15679 un-expanded file names."
15680 (when (file-directory-p org-agenda-files)
15681 (error "`org-agenda-files' cannot be a single directory"))
15682 (when (stringp org-agenda-files)
15683 (with-temp-buffer
15684 (insert-file-contents org-agenda-files)
15685 (mapcar
15686 (lambda (f)
15687 (let ((e (expand-file-name (substitute-in-file-name f)
15688 org-directory)))
15689 (if pair-with-expansion
15690 (cons e f)
15691 e)))
15692 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15694 ;;;###autoload
15695 (defun org-cycle-agenda-files ()
15696 "Cycle through the files in `org-agenda-files'.
15697 If the current buffer visits an agenda file, find the next one in the list.
15698 If the current buffer does not, find the first agenda file."
15699 (interactive)
15700 (let* ((fs (or (org-agenda-files t)
15701 (user-error "No agenda files")))
15702 (files (copy-sequence fs))
15703 (tcf (and buffer-file-name (file-truename buffer-file-name)))
15704 file)
15705 (when tcf
15706 (while (and (setq file (pop files))
15707 (not (equal (file-truename file) tcf)))))
15708 (find-file (car (or files fs)))
15709 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
15711 (defun org-agenda-file-to-front (&optional to-end)
15712 "Move/add the current file to the top of the agenda file list.
15713 If the file is not present in the list, it is added to the front. If it is
15714 present, it is moved there. With optional argument TO-END, add/move to the
15715 end of the list."
15716 (interactive "P")
15717 (let ((org-agenda-skip-unavailable-files nil)
15718 (file-alist (mapcar (lambda (x)
15719 (cons (file-truename x) x))
15720 (org-agenda-files t)))
15721 (ctf (file-truename
15722 (or buffer-file-name
15723 (user-error "Please save the current buffer to a file"))))
15724 x had)
15725 (setq x (assoc ctf file-alist) had x)
15727 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15728 (if to-end
15729 (setq file-alist (append (delq x file-alist) (list x)))
15730 (setq file-alist (cons x (delq x file-alist))))
15731 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15732 (org-install-agenda-files-menu)
15733 (message "File %s to %s of agenda file list"
15734 (if had "moved" "added") (if to-end "end" "front"))))
15736 (defun org-remove-file (&optional file)
15737 "Remove current file from the list of files in variable `org-agenda-files'.
15738 These are the files which are being checked for agenda entries.
15739 Optional argument FILE means use this file instead of the current."
15740 (interactive)
15741 (let* ((org-agenda-skip-unavailable-files nil)
15742 (file (or file buffer-file-name
15743 (user-error "Current buffer does not visit a file")))
15744 (true-file (file-truename file))
15745 (afile (abbreviate-file-name file))
15746 (files (delq nil (mapcar
15747 (lambda (x)
15748 (unless (equal true-file
15749 (file-truename x))
15751 (org-agenda-files t)))))
15752 (if (not (= (length files) (length (org-agenda-files t))))
15753 (progn
15754 (org-store-new-agenda-file-list files)
15755 (org-install-agenda-files-menu)
15756 (message "Removed from Org Agenda list: %s" afile))
15757 (message "File was not in list: %s (not removed)" afile))))
15759 (defun org-file-menu-entry (file)
15760 (vector file (list 'find-file file) t))
15762 (defun org-check-agenda-file (file)
15763 "Make sure FILE exists. If not, ask user what to do."
15764 (unless (file-exists-p file)
15765 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
15766 (abbreviate-file-name file))
15767 (let ((r (downcase (read-char-exclusive))))
15768 (cond
15769 ((equal r ?r)
15770 (org-remove-file file)
15771 (throw 'nextfile t))
15772 (t (user-error "Abort"))))))
15774 (defun org-get-agenda-file-buffer (file)
15775 "Get an agenda buffer visiting FILE.
15776 If the buffer needs to be created, add it to the list of buffers
15777 which might be released later."
15778 (let ((buf (org-find-base-buffer-visiting file)))
15779 (if buf
15780 buf ; just return it
15781 ;; Make a new buffer and remember it
15782 (setq buf (find-file-noselect file))
15783 (when buf (push buf org-agenda-new-buffers))
15784 buf)))
15786 (defun org-release-buffers (blist)
15787 "Release all buffers in list, asking the user for confirmation when needed.
15788 When a buffer is unmodified, it is just killed. When modified, it is saved
15789 \(if the user agrees) and then killed."
15790 (let (file)
15791 (dolist (buf blist)
15792 (setq file (buffer-file-name buf))
15793 (when (and (buffer-modified-p buf)
15794 file
15795 (y-or-n-p (format "Save file %s? " file)))
15796 (with-current-buffer buf (save-buffer)))
15797 (kill-buffer buf))))
15799 (defun org-agenda-prepare-buffers (files)
15800 "Create buffers for all agenda files, protect archived trees and comments."
15801 (interactive)
15802 (let ((pa '(:org-archived t))
15803 (pc '(:org-comment t))
15804 (pall '(:org-archived t :org-comment t))
15805 (inhibit-read-only t)
15806 (org-inhibit-startup org-agenda-inhibit-startup)
15807 (rea (org-make-tag-string (list org-archive-tag)))
15808 re pos)
15809 (setq org-tag-alist-for-agenda nil
15810 org-tag-groups-alist-for-agenda nil)
15811 (save-excursion
15812 (save-restriction
15813 (dolist (file files)
15814 (catch 'nextfile
15815 (if (bufferp file)
15816 (set-buffer file)
15817 (org-check-agenda-file file)
15818 (set-buffer (org-get-agenda-file-buffer file)))
15819 (widen)
15820 (org-set-regexps-and-options 'tags-only)
15821 (setq pos (point))
15822 (or (memq 'category org-agenda-ignore-properties)
15823 (org-refresh-category-properties))
15824 (or (memq 'stats org-agenda-ignore-properties)
15825 (org-refresh-stats-properties))
15826 (or (memq 'effort org-agenda-ignore-properties)
15827 (org-refresh-effort-properties))
15828 (or (memq 'appt org-agenda-ignore-properties)
15829 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
15830 (setq org-todo-keywords-for-agenda
15831 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15832 (setq org-done-keywords-for-agenda
15833 (append org-done-keywords-for-agenda org-done-keywords))
15834 (setq org-todo-keyword-alist-for-agenda
15835 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15836 (setq org-tag-alist-for-agenda
15837 (org--tag-add-to-alist
15838 org-tag-alist-for-agenda
15839 org-current-tag-alist))
15840 ;; Merge current file's tag groups into global
15841 ;; `org-tag-groups-alist-for-agenda'.
15842 (when org-group-tags
15843 (dolist (alist org-tag-groups-alist)
15844 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
15845 (if old
15846 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
15847 (push alist org-tag-groups-alist-for-agenda)))))
15848 (with-silent-modifications
15849 (save-excursion
15850 (remove-text-properties (point-min) (point-max) pall)
15851 (when org-agenda-skip-archived-trees
15852 (goto-char (point-min))
15853 (while (re-search-forward rea nil t)
15854 (when (org-at-heading-p t)
15855 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15856 (goto-char (point-min))
15857 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
15858 (while (re-search-forward re nil t)
15859 (when (save-match-data (org-in-commented-heading-p t))
15860 (add-text-properties
15861 (match-beginning 0) (org-end-of-subtree t) pc)))))
15862 (goto-char pos)))))
15863 (setq org-todo-keywords-for-agenda
15864 (org-uniquify org-todo-keywords-for-agenda))
15865 (setq org-todo-keyword-alist-for-agenda
15866 (org-uniquify org-todo-keyword-alist-for-agenda))))
15869 ;;;; CDLaTeX minor mode
15871 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15872 "Keymap for the minor `org-cdlatex-mode'.")
15874 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
15875 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
15876 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
15877 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
15878 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
15880 (defvar org-cdlatex-texmathp-advice-is-done nil
15881 "Flag remembering if we have applied the advice to texmathp already.")
15883 (define-minor-mode org-cdlatex-mode
15884 "Toggle the minor `org-cdlatex-mode'.
15885 This mode supports entering LaTeX environment and math in LaTeX fragments
15886 in Org mode.
15887 \\{org-cdlatex-mode-map}"
15888 nil " OCDL" nil
15889 (when org-cdlatex-mode
15890 (require 'cdlatex)
15891 (run-hooks 'cdlatex-mode-hook)
15892 (cdlatex-compute-tables))
15893 (unless org-cdlatex-texmathp-advice-is-done
15894 (setq org-cdlatex-texmathp-advice-is-done t)
15895 (defadvice texmathp (around org-math-always-on activate)
15896 "Always return t in Org buffers.
15897 This is because we want to insert math symbols without dollars even outside
15898 the LaTeX math segments. If Org mode thinks that point is actually inside
15899 an embedded LaTeX fragment, let `texmathp' do its job.
15900 `\\[org-cdlatex-mode-map]'"
15901 (interactive)
15902 (let (p)
15903 (cond
15904 ((not (derived-mode-p 'org-mode)) ad-do-it)
15905 ((eq this-command 'cdlatex-math-symbol)
15906 (setq ad-return-value t
15907 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15909 (let ((p (org-inside-LaTeX-fragment-p)))
15910 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15911 (setq ad-return-value t
15912 texmathp-why '("Org mode embedded math" . 0))
15913 (when p ad-do-it)))))))))
15915 (defun turn-on-org-cdlatex ()
15916 "Unconditionally turn on `org-cdlatex-mode'."
15917 (org-cdlatex-mode 1))
15919 (defun org-try-cdlatex-tab ()
15920 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15921 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15922 - inside a LaTeX fragment, or
15923 - after the first word in a line, where an abbreviation expansion could
15924 insert a LaTeX environment."
15925 (when org-cdlatex-mode
15926 (cond
15927 ;; Before any word on the line: No expansion possible.
15928 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
15929 ;; Just after first word on the line: Expand it. Make sure it
15930 ;; cannot happen on headlines, though.
15931 ((save-excursion
15932 (skip-chars-backward "a-zA-Z0-9*")
15933 (skip-chars-backward " \t")
15934 (and (bolp) (not (org-at-heading-p))))
15935 (cdlatex-tab) t)
15936 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
15938 (defun org-cdlatex-underscore-caret (&optional _arg)
15939 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15940 Revert to the normal definition outside of these fragments."
15941 (interactive "P")
15942 (if (org-inside-LaTeX-fragment-p)
15943 (call-interactively 'cdlatex-sub-superscript)
15944 (let (org-cdlatex-mode)
15945 (call-interactively (key-binding (vector last-input-event))))))
15947 (defun org-cdlatex-math-modify (&optional _arg)
15948 "Execute `cdlatex-math-modify' in LaTeX fragments.
15949 Revert to the normal definition outside of these fragments."
15950 (interactive "P")
15951 (if (org-inside-LaTeX-fragment-p)
15952 (call-interactively 'cdlatex-math-modify)
15953 (let (org-cdlatex-mode)
15954 (call-interactively (key-binding (vector last-input-event))))))
15956 (defun org-cdlatex-environment-indent (&optional environment item)
15957 "Execute `cdlatex-environment' and indent the inserted environment.
15959 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
15961 The inserted environment is indented to current indentation
15962 unless point is at the beginning of the line, in which the
15963 environment remains unintended."
15964 (interactive)
15965 ;; cdlatex-environment always return nil. Therefore, capture output
15966 ;; first and determine if an environment was selected.
15967 (let* ((beg (point-marker))
15968 (end (copy-marker (point) t))
15969 (inserted (progn
15970 (ignore-errors (cdlatex-environment environment item))
15971 (< beg end)))
15972 ;; Figure out how many lines to move forward after the
15973 ;; environment has been inserted.
15974 (lines (when inserted
15975 (save-excursion
15976 (- (cl-loop while (< beg (point))
15977 with x = 0
15978 do (forward-line -1)
15979 (cl-incf x)
15980 finally return x)
15981 (if (progn (goto-char beg)
15982 (and (progn (skip-chars-forward " \t") (eolp))
15983 (progn (skip-chars-backward " \t") (bolp))))
15984 1 0)))))
15985 (env (org-trim (delete-and-extract-region beg end))))
15986 (when inserted
15987 ;; Get indentation of next line unless at column 0.
15988 (let ((ind (if (bolp) 0
15989 (save-excursion
15990 (org-return-indent)
15991 (prog1 (current-indentation)
15992 (when (progn (skip-chars-forward " \t") (eolp))
15993 (delete-region beg (point)))))))
15994 (bol (progn (skip-chars-backward " \t") (bolp))))
15995 ;; Insert a newline before environment unless at column zero
15996 ;; to "escape" the current line. Insert a newline if
15997 ;; something is one the same line as \end{ENVIRONMENT}.
15998 (insert
15999 (concat (unless bol "\n") env
16000 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
16001 (unless (zerop ind)
16002 (save-excursion
16003 (goto-char beg)
16004 (while (< (point) end)
16005 (unless (eolp) (indent-line-to ind))
16006 (forward-line))))
16007 (goto-char beg)
16008 (forward-line lines)
16009 (indent-line-to ind)))
16010 (set-marker beg nil)
16011 (set-marker end nil)))
16014 ;;;; LaTeX fragments
16016 (defun org-inside-LaTeX-fragment-p ()
16017 "Test if point is inside a LaTeX fragment.
16018 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16019 sequence appearing also before point.
16020 Even though the matchers for math are configurable, this function assumes
16021 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16022 delimiters are skipped when they have been removed by customization.
16023 The return value is nil, or a cons cell with the delimiter and the
16024 position of this delimiter.
16026 This function does a reasonably good job, but can locally be fooled by
16027 for example currency specifications. For example it will assume being in
16028 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16029 fragments that are properly closed, but during editing, we have to live
16030 with the uncertainty caused by missing closing delimiters. This function
16031 looks only before point, not after."
16032 (catch 'exit
16033 (let ((pos (point))
16034 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16035 (lim (save-excursion (org-backward-paragraph) (point)))
16036 dd-on str (start 0) m re)
16037 (goto-char pos)
16038 (when dodollar
16039 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16040 re (nth 1 (assoc "$" org-latex-regexps)))
16041 (while (string-match re str start)
16042 (cond
16043 ((= (match-end 0) (length str))
16044 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16045 ((= (match-end 0) (- (length str) 5))
16046 (throw 'exit nil))
16047 (t (setq start (match-end 0))))))
16048 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16049 (goto-char pos)
16050 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16051 (and (match-beginning 2) (throw 'exit nil))
16052 ;; count $$
16053 (while (re-search-backward "\\$\\$" lim t)
16054 (setq dd-on (not dd-on)))
16055 (goto-char pos)
16056 (when dd-on (cons "$$" m))))))
16058 (defun org-inside-latex-macro-p ()
16059 "Is point inside a LaTeX macro or its arguments?"
16060 (save-match-data
16061 (org-in-regexp
16062 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16064 (defun org--make-preview-overlay (beg end image &optional imagetype)
16065 "Build an overlay between BEG and END using IMAGE file.
16066 Argument IMAGETYPE is the extension of the displayed image,
16067 as a string. It defaults to \"png\"."
16068 (let ((ov (make-overlay beg end))
16069 (imagetype (or (intern imagetype) 'png)))
16070 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16071 (overlay-put ov 'evaporate t)
16072 (overlay-put ov
16073 'modification-hooks
16074 (list (lambda (o _flag _beg _end &optional _l)
16075 (delete-overlay o))))
16076 (overlay-put ov
16077 'display
16078 (list 'image :type imagetype :file image :ascent 'center))))
16080 (defun org-clear-latex-preview (&optional beg end)
16081 "Remove all overlays with LaTeX fragment images in current buffer.
16082 When optional arguments BEG and END are non-nil, remove all
16083 overlays between them instead. Return a non-nil value when some
16084 overlays were removed, nil otherwise."
16085 (let ((overlays
16086 (cl-remove-if-not
16087 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
16088 (overlays-in (or beg (point-min)) (or end (point-max))))))
16089 (mapc #'delete-overlay overlays)
16090 overlays))
16092 (defun org--latex-preview-region (beg end)
16093 "Preview LaTeX fragments between BEG and END.
16094 BEG and END are buffer positions."
16095 (let ((file (buffer-file-name (buffer-base-buffer))))
16096 (save-excursion
16097 (org-format-latex
16098 (concat org-preview-latex-image-directory "org-ltximg")
16099 beg end
16100 ;; Emacs cannot overlay images from remote hosts. Create it in
16101 ;; `temporary-file-directory' instead.
16102 (if (or (not file) (file-remote-p file))
16103 temporary-file-directory
16104 default-directory)
16105 'overlays nil 'forbuffer org-preview-latex-default-process))))
16107 (defun org-latex-preview (&optional arg)
16108 "Toggle preview of the LaTeX fragment at point.
16110 If the cursor is on a LaTeX fragment, create the image and
16111 overlay it over the source code, if there is none. Remove it
16112 otherwise. If there is no fragment at point, display images for
16113 all fragments in the current section.
16115 With a `\\[universal-argument]' prefix argument ARG, clear images \
16116 for all fragments
16117 in the current section.
16119 With a `\\[universal-argument] \\[universal-argument]' prefix \
16120 argument ARG, display image for all
16121 fragments in the buffer.
16123 With a `\\[universal-argument] \\[universal-argument] \
16124 \\[universal-argument]' prefix argument ARG, clear image for all
16125 fragments in the buffer."
16126 (interactive "P")
16127 (cond
16128 ((not (display-graphic-p)) nil)
16129 ;; Clear whole buffer.
16130 ((equal arg '(64))
16131 (org-clear-latex-preview (point-min) (point-max))
16132 (message "LaTeX previews removed from buffer"))
16133 ;; Preview whole buffer.
16134 ((equal arg '(16))
16135 (message "Creating LaTeX previews in buffer...")
16136 (org--latex-preview-region (point-min) (point-max))
16137 (message "Creating LaTeX previews in buffer... done."))
16138 ;; Clear current section.
16139 ((equal arg '(4))
16140 (org-clear-latex-preview
16141 (if (org-before-first-heading-p) (point-min)
16142 (save-excursion
16143 (org-with-limited-levels (org-back-to-heading t) (point))))
16144 (org-with-limited-levels (org-entry-end-position))))
16145 ;; Toggle preview on LaTeX code at point.
16146 ((let ((datum (org-element-context)))
16147 (and (memq (org-element-type datum) '(latex-environment latex-fragment))
16148 (let ((beg (org-element-property :begin datum))
16149 (end (org-element-property :end datum)))
16150 (if (org-clear-latex-preview beg end)
16151 (message "LaTeX preview removed")
16152 (message "Creating LaTeX preview...")
16153 (org--latex-preview-region beg end)
16154 (message "Creating LaTeX preview... done."))
16155 t))))
16156 ;; Preview current section.
16158 (let ((beg (if (org-before-first-heading-p) (point-min)
16159 (save-excursion
16160 (org-with-limited-levels (org-back-to-heading t) (point)))))
16161 (end (org-with-limited-levels (org-entry-end-position))))
16162 (message "Creating LaTeX previews in section...")
16163 (org--latex-preview-region beg end)
16164 (message "Creating LaTeX previews in section... done.")))))
16166 (defun org-format-latex
16167 (prefix &optional beg end dir overlays msg forbuffer processing-type)
16168 "Replace LaTeX fragments with links to an image.
16170 The function takes care of creating the replacement image.
16172 Only consider fragments between BEG and END when those are
16173 provided.
16175 When optional argument OVERLAYS is non-nil, display the image on
16176 top of the fragment instead of replacing it.
16178 PROCESSING-TYPE is the conversion method to use, as a symbol.
16180 Some of the options can be changed using the variable
16181 `org-format-latex-options', which see."
16182 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16183 (unless (eq processing-type 'verbatim)
16184 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
16185 (cnt 0)
16186 checkdir-flag)
16187 (goto-char (or beg (point-min)))
16188 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
16189 (when (and overlays (memq processing-type '(dvipng imagemagick)))
16190 (overlay-recenter (or end (point-max))))
16191 (while (re-search-forward math-regexp end t)
16192 (unless (and overlays
16193 (eq (get-char-property (point) 'org-overlay-type)
16194 'org-latex-overlay))
16195 (let* ((context (org-element-context))
16196 (type (org-element-type context)))
16197 (when (memq type '(latex-environment latex-fragment))
16198 (let ((block-type (eq type 'latex-environment))
16199 (value (org-element-property :value context))
16200 (beg (org-element-property :begin context))
16201 (end (save-excursion
16202 (goto-char (org-element-property :end context))
16203 (skip-chars-backward " \r\t\n")
16204 (point))))
16205 (cond
16206 ((eq processing-type 'mathjax)
16207 ;; Prepare for MathJax processing.
16208 (if (not (string-match "\\`\\$\\$?" value))
16209 (goto-char end)
16210 (delete-region beg end)
16211 (if (string= (match-string 0 value) "$$")
16212 (insert "\\[" (substring value 2 -2) "\\]")
16213 (insert "\\(" (substring value 1 -1) "\\)"))))
16214 ((assq processing-type org-preview-latex-process-alist)
16215 ;; Process to an image.
16216 (cl-incf cnt)
16217 (goto-char beg)
16218 (let* ((processing-info
16219 (cdr (assq processing-type org-preview-latex-process-alist)))
16220 (face (face-at-point))
16221 ;; Get the colors from the face at point.
16223 (let ((color (plist-get org-format-latex-options
16224 :foreground)))
16225 (if (and forbuffer (eq color 'auto))
16226 (face-attribute face :foreground nil 'default)
16227 color)))
16229 (let ((color (plist-get org-format-latex-options
16230 :background)))
16231 (if (and forbuffer (eq color 'auto))
16232 (face-attribute face :background nil 'default)
16233 color)))
16234 (hash (sha1 (prin1-to-string
16235 (list org-format-latex-header
16236 org-latex-default-packages-alist
16237 org-latex-packages-alist
16238 org-format-latex-options
16239 forbuffer value fg bg))))
16240 (imagetype (or (plist-get processing-info :image-output-type) "png"))
16241 (absprefix (expand-file-name prefix dir))
16242 (linkfile (format "%s_%s.%s" prefix hash imagetype))
16243 (movefile (format "%s_%s.%s" absprefix hash imagetype))
16244 (sep (and block-type "\n\n"))
16245 (link (concat sep "[[file:" linkfile "]]" sep))
16246 (options
16247 (org-combine-plists
16248 org-format-latex-options
16249 `(:foreground ,fg :background ,bg))))
16250 (when msg (message msg cnt))
16251 (unless checkdir-flag ; Ensure the directory exists.
16252 (setq checkdir-flag t)
16253 (let ((todir (file-name-directory absprefix)))
16254 (unless (file-directory-p todir)
16255 (make-directory todir t))))
16256 (unless (file-exists-p movefile)
16257 (org-create-formula-image
16258 value movefile options forbuffer processing-type))
16259 (if overlays
16260 (progn
16261 (dolist (o (overlays-in beg end))
16262 (when (eq (overlay-get o 'org-overlay-type)
16263 'org-latex-overlay)
16264 (delete-overlay o)))
16265 (org--make-preview-overlay beg end movefile imagetype)
16266 (goto-char end))
16267 (delete-region beg end)
16268 (insert
16269 (org-add-props link
16270 (list 'org-latex-src
16271 (replace-regexp-in-string "\"" "" value)
16272 'org-latex-src-embed-type
16273 (if block-type 'paragraph 'character)))))))
16274 ((eq processing-type 'mathml)
16275 ;; Process to MathML.
16276 (unless (org-format-latex-mathml-available-p)
16277 (user-error "LaTeX to MathML converter not configured"))
16278 (cl-incf cnt)
16279 (when msg (message msg cnt))
16280 (goto-char beg)
16281 (delete-region beg end)
16282 (insert (org-format-latex-as-mathml
16283 value block-type prefix dir)))
16285 (error "Unknown conversion process %s for LaTeX fragments"
16286 processing-type)))))))))))
16288 (defun org-create-math-formula (latex-frag &optional mathml-file)
16289 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16290 Use `org-latex-to-mathml-convert-command'. If the conversion is
16291 sucessful, return the portion between \"<math...> </math>\"
16292 elements otherwise return nil. When MATHML-FILE is specified,
16293 write the results in to that file. When invoked as an
16294 interactive command, prompt for LATEX-FRAG, with initial value
16295 set to the current active region and echo the results for user
16296 inspection."
16297 (interactive (list (let ((frag (when (org-region-active-p)
16298 (buffer-substring-no-properties
16299 (region-beginning) (region-end)))))
16300 (read-string "LaTeX Fragment: " frag nil frag))))
16301 (unless latex-frag (user-error "Invalid LaTeX fragment"))
16302 (let* ((tmp-in-file
16303 (let ((file (file-relative-name
16304 (make-temp-name (expand-file-name "ltxmathml-in")))))
16305 (write-region latex-frag nil file)
16306 file))
16307 (tmp-out-file (file-relative-name
16308 (make-temp-name (expand-file-name "ltxmathml-out"))))
16309 (cmd (format-spec
16310 org-latex-to-mathml-convert-command
16311 `((?j . ,(and org-latex-to-mathml-jar-file
16312 (shell-quote-argument
16313 (expand-file-name
16314 org-latex-to-mathml-jar-file))))
16315 (?I . ,(shell-quote-argument tmp-in-file))
16316 (?i . ,latex-frag)
16317 (?o . ,(shell-quote-argument tmp-out-file)))))
16318 mathml shell-command-output)
16319 (when (called-interactively-p 'any)
16320 (unless (org-format-latex-mathml-available-p)
16321 (user-error "LaTeX to MathML converter not configured")))
16322 (message "Running %s" cmd)
16323 (setq shell-command-output (shell-command-to-string cmd))
16324 (setq mathml
16325 (when (file-readable-p tmp-out-file)
16326 (with-current-buffer (find-file-noselect tmp-out-file t)
16327 (goto-char (point-min))
16328 (when (re-search-forward
16329 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
16330 (regexp-quote
16331 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
16332 nil t)
16333 (prog1 (match-string 0) (kill-buffer))))))
16334 (cond
16335 (mathml
16336 (setq mathml
16337 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16338 (when mathml-file
16339 (write-region mathml nil mathml-file))
16340 (when (called-interactively-p 'any)
16341 (message mathml)))
16342 ((message "LaTeX to MathML conversion failed")
16343 (message shell-command-output)))
16344 (delete-file tmp-in-file)
16345 (when (file-exists-p tmp-out-file)
16346 (delete-file tmp-out-file))
16347 mathml))
16349 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16350 prefix &optional dir)
16351 "Use `org-create-math-formula' but check local cache first."
16352 (let* ((absprefix (expand-file-name prefix dir))
16353 (print-length nil) (print-level nil)
16354 (formula-id (concat
16355 "formula-"
16356 (sha1
16357 (prin1-to-string
16358 (list latex-frag
16359 org-latex-to-mathml-convert-command)))))
16360 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16361 (formula-cache-dir (file-name-directory formula-cache)))
16363 (unless (file-directory-p formula-cache-dir)
16364 (make-directory formula-cache-dir t))
16366 (unless (file-exists-p formula-cache)
16367 (org-create-math-formula latex-frag formula-cache))
16369 (if (file-exists-p formula-cache)
16370 ;; Successful conversion. Return the link to MathML file.
16371 (org-add-props
16372 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16373 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16374 'org-latex-src-embed-type (if latex-frag-type
16375 'paragraph 'character)))
16376 ;; Failed conversion. Return the LaTeX fragment verbatim
16377 latex-frag)))
16379 (defun org--get-display-dpi ()
16380 "Get the DPI of the display.
16381 The function assumes that the display has the same pixel width in
16382 the horizontal and vertical directions."
16383 (if (display-graphic-p)
16384 (round (/ (display-pixel-height)
16385 (/ (display-mm-height) 25.4)))
16386 (error "Attempt to calculate the dpi of a non-graphic display")))
16388 (defun org-create-formula-image
16389 (string tofile options buffer &optional processing-type)
16390 "Create an image from LaTeX source using external processes.
16392 The LaTeX STRING is saved to a temporary LaTeX file, then
16393 converted to an image file by process PROCESSING-TYPE defined in
16394 `org-preview-latex-process-alist'. A nil value defaults to
16395 `org-preview-latex-default-process'.
16397 The generated image file is eventually moved to TOFILE.
16399 The OPTIONS argument controls the size, foreground color and
16400 background color of the generated image.
16402 When BUFFER non-nil, this function is used for LaTeX previewing.
16403 Otherwise, it is used to deal with LaTeX snippets showed in
16404 a HTML file."
16405 (let* ((processing-type (or processing-type
16406 org-preview-latex-default-process))
16407 (processing-info
16408 (cdr (assq processing-type org-preview-latex-process-alist)))
16409 (programs (plist-get processing-info :programs))
16410 (error-message (or (plist-get processing-info :message) ""))
16411 (image-input-type (plist-get processing-info :image-input-type))
16412 (image-output-type (plist-get processing-info :image-output-type))
16413 (post-clean (or (plist-get processing-info :post-clean)
16414 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
16415 ".svg" ".png" ".jpg" ".jpeg" ".out")))
16416 (latex-header
16417 (or (plist-get processing-info :latex-header)
16418 (org-latex-make-preamble
16419 (org-export-get-environment (org-export-get-backend 'latex))
16420 org-format-latex-header
16421 'snippet)))
16422 (latex-compiler (plist-get processing-info :latex-compiler))
16423 (image-converter (plist-get processing-info :image-converter))
16424 (tmpdir temporary-file-directory)
16425 (texfilebase (make-temp-name
16426 (expand-file-name "orgtex" tmpdir)))
16427 (texfile (concat texfilebase ".tex"))
16428 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
16429 '(1.0 . 1.0)))
16430 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
16431 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
16432 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
16433 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16434 "Black"))
16435 (bg (or (plist-get options (if buffer :background :html-background))
16436 "Transparent"))
16437 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
16438 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
16439 (dolist (program programs)
16440 (org-check-external-command program error-message))
16441 (if (eq fg 'default)
16442 (setq fg (org-latex-color :foreground))
16443 (setq fg (org-latex-color-format fg)))
16444 (if (eq bg 'default)
16445 (setq bg (org-latex-color :background))
16446 (setq bg (org-latex-color-format
16447 (if (string= bg "Transparent") "white" bg))))
16448 (with-temp-file texfile
16449 (insert latex-header)
16450 (insert "\n\\begin{document}\n"
16451 "\\definecolor{fg}{rgb}{" fg "}\n"
16452 "\\definecolor{bg}{rgb}{" bg "}\n"
16453 "\n\\pagecolor{bg}\n"
16454 "\n{\\color{fg}\n"
16455 string
16456 "\n}\n"
16457 "\n\\end{document}\n"))
16458 (let* ((err-msg (format "Please adjust `%s' part of \
16459 `org-preview-latex-process-alist'."
16460 processing-type))
16461 (image-input-file
16462 (org-compile-file
16463 texfile latex-compiler image-input-type err-msg log-buf))
16464 (image-output-file
16465 (org-compile-file
16466 image-input-file image-converter image-output-type err-msg log-buf
16467 `((?D . ,(shell-quote-argument (format "%s" dpi)))
16468 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
16469 (copy-file image-output-file tofile 'replace)
16470 (dolist (e post-clean)
16471 (when (file-exists-p (concat texfilebase e))
16472 (delete-file (concat texfilebase e))))
16473 image-output-file)))
16475 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16476 "Fill a LaTeX header template TPL.
16477 In the template, the following place holders will be recognized:
16479 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16480 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16481 [PACKAGES] \\usepackage statements for PKG
16482 [NO-PACKAGES] do not include PKG
16483 [EXTRA] the string EXTRA
16484 [NO-EXTRA] do not include EXTRA
16486 For backward compatibility, if both the positive and the negative place
16487 holder is missing, the positive one (without the \"NO-\") will be
16488 assumed to be present at the end of the template.
16489 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16490 EXTRA is a string.
16491 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16492 (let (rpl (end ""))
16493 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16494 (setq rpl (if (or (match-end 1) (not def-pkg))
16495 "" (org-latex-packages-to-string def-pkg snippets-p t))
16496 tpl (replace-match rpl t t tpl))
16497 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16499 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16500 (setq rpl (if (or (match-end 1) (not pkg))
16501 "" (org-latex-packages-to-string pkg snippets-p t))
16502 tpl (replace-match rpl t t tpl))
16503 (when pkg (setq end
16504 (concat end "\n"
16505 (org-latex-packages-to-string pkg snippets-p)))))
16507 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16508 (setq rpl (if (or (match-end 1) (not extra))
16509 "" (concat extra "\n"))
16510 tpl (replace-match rpl t t tpl))
16511 (when (and extra (string-match "\\S-" extra))
16512 (setq end (concat end "\n" extra))))
16514 (if (string-match "\\S-" end)
16515 (concat tpl "\n" end)
16516 tpl)))
16518 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16519 "Turn an alist of packages into a string with the \\usepackage macros."
16520 (setq pkg (mapconcat (lambda(p)
16521 (cond
16522 ((stringp p) p)
16523 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16524 (format "%% Package %s omitted" (cadr p)))
16525 ((equal "" (car p))
16526 (format "\\usepackage{%s}" (cadr p)))
16528 (format "\\usepackage[%s]{%s}"
16529 (car p) (cadr p)))))
16531 "\n"))
16532 (if newline (concat pkg "\n") pkg))
16534 (defun org-dvipng-color (attr)
16535 "Return a RGB color specification for dvipng."
16536 (org-dvipng-color-format (face-attribute 'default attr nil)))
16538 (defun org-dvipng-color-format (color-name)
16539 "Convert COLOR-NAME to a RGB color value for dvipng."
16540 (apply #'format "rgb %s %s %s"
16541 (mapcar 'org-normalize-color
16542 (color-values color-name))))
16544 (defun org-latex-color (attr)
16545 "Return a RGB color for the LaTeX color package."
16546 (org-latex-color-format (face-attribute 'default attr nil)))
16548 (defun org-latex-color-format (color-name)
16549 "Convert COLOR-NAME to a RGB color value."
16550 (apply #'format "%s,%s,%s"
16551 (mapcar 'org-normalize-color
16552 (color-values color-name))))
16554 (defun org-normalize-color (value)
16555 "Return string to be used as color value for an RGB component."
16556 (format "%g" (/ value 65535.0)))
16559 ;; Image display
16561 (defvar-local org-inline-image-overlays nil)
16563 (defun org-toggle-inline-images (&optional include-linked)
16564 "Toggle the display of inline images.
16565 INCLUDE-LINKED is passed to `org-display-inline-images'."
16566 (interactive "P")
16567 (if org-inline-image-overlays
16568 (progn
16569 (org-remove-inline-images)
16570 (when (called-interactively-p 'interactive)
16571 (message "Inline image display turned off")))
16572 (org-display-inline-images include-linked)
16573 (when (called-interactively-p 'interactive)
16574 (message (if org-inline-image-overlays
16575 (format "%d images displayed inline"
16576 (length org-inline-image-overlays))
16577 "No images to display inline")))))
16579 (defun org-redisplay-inline-images ()
16580 "Refresh the display of inline images."
16581 (interactive)
16582 (if (not org-inline-image-overlays)
16583 (org-toggle-inline-images)
16584 (org-toggle-inline-images)
16585 (org-toggle-inline-images)))
16587 ;; For without-x builds.
16588 (declare-function image-refresh "image" (spec &optional frame))
16590 (defun org-display-inline-images (&optional include-linked refresh beg end)
16591 "Display inline images.
16593 An inline image is a link which follows either of these
16594 conventions:
16596 1. Its path is a file with an extension matching return value
16597 from `image-file-name-regexp' and it has no contents.
16599 2. Its description consists in a single link of the previous
16600 type. In this case, that link must be a well-formed plain
16601 or angle link, i.e., it must have an explicit \"file\" type.
16603 When optional argument INCLUDE-LINKED is non-nil, also links with
16604 a text description part will be inlined. This can be nice for
16605 a quick look at those images, but it does not reflect what
16606 exported files will look like.
16608 When optional argument REFRESH is non-nil, refresh existing
16609 images between BEG and END. This will create new image displays
16610 only if necessary. BEG and END default to the buffer
16611 boundaries."
16612 (interactive "P")
16613 (when (display-graphic-p)
16614 (unless refresh
16615 (org-remove-inline-images)
16616 (when (fboundp 'clear-image-cache) (clear-image-cache)))
16617 (org-with-point-at (or beg 1)
16618 (let* ((case-fold-search t)
16619 (file-extension-re (image-file-name-regexp))
16620 (link-abbrevs (mapcar #'car
16621 (append org-link-abbrev-alist-local
16622 org-link-abbrev-alist)))
16623 ;; Check absolute, relative file names and explicit
16624 ;; "file:" links. Also check link abbreviations since
16625 ;; some might expand to "file" links.
16626 (file-types-re
16627 (format "\\[\\[\\(?:file%s:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
16628 (if (not link-abbrevs) ""
16629 (concat "\\|" (regexp-opt link-abbrevs))))))
16630 (while (re-search-forward file-types-re end t)
16631 (let* ((link (org-element-lineage
16632 (save-match-data (org-element-context))
16633 '(link) t))
16634 (inner-start (match-beginning 1))
16635 (path
16636 (cond
16637 ;; No link at point; no inline image.
16638 ((not link) nil)
16639 ;; File link without a description. Also handle
16640 ;; INCLUDE-LINKED here since it should have
16641 ;; precedence over the next case. I.e., if link
16642 ;; contains filenames in both the path and the
16643 ;; description, prioritize the path only when
16644 ;; INCLUDE-LINKED is non-nil.
16645 ((or (not (org-element-property :contents-begin link))
16646 include-linked)
16647 (and (equal "file" (org-element-property :type link))
16648 (org-element-property :path link)))
16649 ;; Link with a description. Check if description
16650 ;; is a filename. Even if Org doesn't have syntax
16651 ;; for those -- clickable image -- constructs, fake
16652 ;; them, as in `org-export-insert-image-links'.
16653 ((not inner-start) nil)
16655 (org-with-point-at inner-start
16656 (and (looking-at
16657 (if (char-equal ?< (char-after inner-start))
16658 org-link-angle-re
16659 org-link-plain-re))
16660 ;; File name must fill the whole
16661 ;; description.
16662 (= (org-element-property :contents-end link)
16663 (match-end 0))
16664 (match-string 2)))))))
16665 (when (and path (string-match-p file-extension-re path))
16666 (let ((file (expand-file-name path)))
16667 (when (file-exists-p file)
16668 (let ((width
16669 ;; Apply `org-image-actual-width' specifications.
16670 (cond
16671 ((not (image-type-available-p 'imagemagick)) nil)
16672 ((eq org-image-actual-width t) nil)
16673 ((listp org-image-actual-width)
16675 ;; First try to find a width among
16676 ;; attributes associated to the paragraph
16677 ;; containing link.
16678 (let ((paragraph
16679 (let ((e link))
16680 (while (and (setq e (org-element-property
16681 :parent e))
16682 (not (eq (org-element-type e)
16683 'paragraph))))
16684 e)))
16685 (when paragraph
16686 (save-excursion
16687 (goto-char (org-element-property :begin paragraph))
16688 (when
16689 (re-search-forward
16690 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
16691 (org-element-property
16692 :post-affiliated paragraph)
16694 (string-to-number (match-string 1))))))
16695 ;; Otherwise, fall-back to provided number.
16696 (car org-image-actual-width)))
16697 ((numberp org-image-actual-width)
16698 org-image-actual-width)))
16699 (old (get-char-property-and-overlay
16700 (org-element-property :begin link)
16701 'org-image-overlay)))
16702 (if (and (car-safe old) refresh)
16703 (image-refresh (overlay-get (cdr old) 'display))
16704 (let ((image (create-image file
16705 (and width 'imagemagick)
16707 :width width)))
16708 (when image
16709 (let ((ov (make-overlay
16710 (org-element-property :begin link)
16711 (progn
16712 (goto-char
16713 (org-element-property :end link))
16714 (skip-chars-backward " \t")
16715 (point)))))
16716 (overlay-put ov 'display image)
16717 (overlay-put ov 'face 'default)
16718 (overlay-put ov 'org-image-overlay t)
16719 (overlay-put
16720 ov 'modification-hooks
16721 (list 'org-display-inline-remove-overlay))
16722 (push ov org-inline-image-overlays)))))))))))))))
16724 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
16725 "Remove inline-display overlay if a corresponding region is modified."
16726 (let ((inhibit-modification-hooks t))
16727 (when (and ov after)
16728 (delete ov org-inline-image-overlays)
16729 (delete-overlay ov))))
16731 (defun org-remove-inline-images ()
16732 "Remove inline display of images."
16733 (interactive)
16734 (mapc #'delete-overlay org-inline-image-overlays)
16735 (setq org-inline-image-overlays nil))
16737 (defvar org-self-insert-command-undo-counter 0)
16738 (defvar org-speed-command nil)
16740 (defun org-self-insert-command (N)
16741 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16742 If the cursor is in a table looking at whitespace, the whitespace is
16743 overwritten, and the table is not marked as requiring realignment."
16744 (interactive "p")
16745 (org-check-before-invisible-edit 'insert)
16746 (cond
16747 ((and org-use-speed-commands
16748 (let ((kv (this-command-keys-vector)))
16749 (setq org-speed-command
16750 (run-hook-with-args-until-success
16751 'org-speed-command-hook
16752 (make-string 1 (aref kv (1- (length kv))))))))
16753 (cond
16754 ((commandp org-speed-command)
16755 (setq this-command org-speed-command)
16756 (call-interactively org-speed-command))
16757 ((functionp org-speed-command)
16758 (funcall org-speed-command))
16759 ((and org-speed-command (listp org-speed-command))
16760 (eval org-speed-command))
16761 (t (let (org-use-speed-commands)
16762 (call-interactively 'org-self-insert-command)))))
16763 ((and
16764 (= N 1)
16765 (not (org-region-active-p))
16766 (org-at-table-p)
16767 (progn
16768 ;; Check if we blank the field, and if that triggers align.
16769 (and (featurep 'org-table)
16770 org-table-auto-blank-field
16771 (memq last-command
16772 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
16773 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
16774 ;; Got extra space, this field does not determine
16775 ;; column width.
16776 (let (org-table-may-need-update) (org-table-blank-field))
16777 ;; No extra space, this field may determine column
16778 ;; width.
16779 (org-table-blank-field)))
16781 (looking-at "[^|\n]* |"))
16782 ;; There is room for insertion without re-aligning the table.
16783 (self-insert-command N)
16784 (org-table-with-shrunk-field
16785 (save-excursion
16786 (skip-chars-forward "^|")
16787 ;; Do not delete last space, which is
16788 ;; `org-table-separator-space', but the regular space before
16789 ;; it.
16790 (delete-region (- (point) 2) (1- (point))))))
16792 (setq org-table-may-need-update t)
16793 (self-insert-command N)
16794 (org-fix-tags-on-the-fly)
16795 (when org-self-insert-cluster-for-undo
16796 (if (not (eq last-command 'org-self-insert-command))
16797 (setq org-self-insert-command-undo-counter 1)
16798 (if (>= org-self-insert-command-undo-counter 20)
16799 (setq org-self-insert-command-undo-counter 1)
16800 (and (> org-self-insert-command-undo-counter 0)
16801 buffer-undo-list (listp buffer-undo-list)
16802 (not (cadr buffer-undo-list)) ; remove nil entry
16803 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16804 (setq org-self-insert-command-undo-counter
16805 (1+ org-self-insert-command-undo-counter))))))))
16807 (defun org-check-before-invisible-edit (kind)
16808 "Check is editing if kind KIND would be dangerous with invisible text around.
16809 The detailed reaction depends on the user option `org-catch-invisible-edits'."
16810 ;; First, try to get out of here as quickly as possible, to reduce overhead
16811 (when (and org-catch-invisible-edits
16812 (or (not (boundp 'visible-mode)) (not visible-mode))
16813 (or (get-char-property (point) 'invisible)
16814 (get-char-property (max (point-min) (1- (point))) 'invisible)))
16815 ;; OK, we need to take a closer look. Do not consider
16816 ;; invisibility obtained through text properties (e.g., link
16817 ;; fontification), as it cannot be toggled.
16818 (let* ((invisible-at-point
16819 (pcase (get-char-property-and-overlay (point) 'invisible)
16820 (`(,_ . ,(and (pred overlayp) o)) o)))
16821 ;; Assume that point cannot land in the middle of an
16822 ;; overlay, or between two overlays.
16823 (invisible-before-point
16824 (and (not invisible-at-point)
16825 (not (bobp))
16826 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
16827 (`(,_ . ,(and (pred overlayp) o)) o))))
16828 (border-and-ok-direction
16830 ;; Check if we are acting predictably before invisible
16831 ;; text.
16832 (and invisible-at-point
16833 (memq kind '(insert delete-backward)))
16834 ;; Check if we are acting predictably after invisible text
16835 ;; This works not well, and I have turned it off. It seems
16836 ;; better to always show and stop after invisible text.
16837 ;; (and (not invisible-at-point) invisible-before-point
16838 ;; (memq kind '(insert delete)))
16840 (when (or invisible-at-point invisible-before-point)
16841 (when (eq org-catch-invisible-edits 'error)
16842 (user-error "Editing in invisible areas is prohibited, make them visible first"))
16843 (if (and org-custom-properties-overlays
16844 (y-or-n-p "Display invisible properties in this buffer? "))
16845 (org-toggle-custom-properties-visibility)
16846 ;; Make the area visible
16847 (save-excursion
16848 (when invisible-before-point
16849 (goto-char
16850 (previous-single-char-property-change (point) 'invisible)))
16851 ;; Remove whatever overlay is currently making yet-to-be
16852 ;; edited text invisible. Also remove nested invisibility
16853 ;; related overlays.
16854 (delete-overlay (or invisible-at-point invisible-before-point))
16855 (let ((origin (if invisible-at-point (point) (1- (point)))))
16856 (while (pcase (get-char-property-and-overlay origin 'invisible)
16857 (`(,_ . ,(and (pred overlayp) o))
16858 (delete-overlay o)
16859 t)))))
16860 (cond
16861 ((eq org-catch-invisible-edits 'show)
16862 ;; That's it, we do the edit after showing
16863 (message
16864 "Unfolding invisible region around point before editing")
16865 (sit-for 1))
16866 ((and (eq org-catch-invisible-edits 'smart)
16867 border-and-ok-direction)
16868 (message "Unfolding invisible region around point before editing"))
16870 ;; Don't do the edit, make the user repeat it in full visibility
16871 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
16873 (defun org-fix-tags-on-the-fly ()
16874 "Align tags in headline at point.
16875 Unlike `org-align-tags', this function does nothing if point is
16876 either not currently on a tagged headline or on a tag."
16877 (when (and (org-match-line org-tag-line-re)
16878 (< (point) (match-beginning 1)))
16879 (org-align-tags)))
16881 (defun org-delete-backward-char (N)
16882 "Like `delete-backward-char', insert whitespace at field end in tables.
16883 When deleting backwards, in tables this function will insert whitespace in
16884 front of the next \"|\" separator, to keep the table aligned. The table will
16885 still be marked for re-alignment if the field did fill the entire column,
16886 because, in this case the deletion might narrow the column."
16887 (interactive "p")
16888 (save-match-data
16889 (org-check-before-invisible-edit 'delete-backward)
16890 (if (and (= N 1)
16891 (not overwrite-mode)
16892 (not (org-region-active-p))
16893 (not (eq (char-before) ?|))
16894 (save-excursion (skip-chars-backward " \t") (not (bolp)))
16895 (looking-at-p ".*?|")
16896 (org-at-table-p))
16897 (progn (forward-char -1) (org-delete-char 1))
16898 (backward-delete-char N)
16899 (org-fix-tags-on-the-fly))))
16901 (defun org-delete-char (N)
16902 "Like `delete-char', but insert whitespace at field end in tables.
16903 When deleting characters, in tables this function will insert whitespace in
16904 front of the next \"|\" separator, to keep the table aligned. The table will
16905 still be marked for re-alignment if the field did fill the entire column,
16906 because, in this case the deletion might narrow the column."
16907 (interactive "p")
16908 (save-match-data
16909 (org-check-before-invisible-edit 'delete)
16910 (cond
16911 ((or (/= N 1)
16912 (eq (char-after) ?|)
16913 (save-excursion (skip-chars-backward " \t") (bolp))
16914 (not (org-at-table-p)))
16915 (delete-char N)
16916 (org-fix-tags-on-the-fly))
16917 ((looking-at ".\\(.*?\\)|")
16918 (let* ((update? org-table-may-need-update)
16919 (noalign (looking-at-p ".*? |")))
16920 (delete-char 1)
16921 (org-table-with-shrunk-field
16922 (save-excursion
16923 ;; Last space is `org-table-separator-space', so insert
16924 ;; a regular one before it instead.
16925 (goto-char (- (match-end 0) 2))
16926 (insert " ")))
16927 ;; If there were two spaces at the end, this field does not
16928 ;; determine the width of the column.
16929 (when noalign (setq org-table-may-need-update update?))))
16931 (delete-char N)))))
16933 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
16934 (put 'org-self-insert-command 'delete-selection
16935 (lambda ()
16936 (not (run-hook-with-args-until-success
16937 'self-insert-uses-region-functions))))
16938 (put 'orgtbl-self-insert-command 'delete-selection
16939 (lambda ()
16940 (not (run-hook-with-args-until-success
16941 'self-insert-uses-region-functions))))
16942 (put 'org-delete-char 'delete-selection 'supersede)
16943 (put 'org-delete-backward-char 'delete-selection 'supersede)
16944 (put 'org-yank 'delete-selection 'yank)
16946 ;; Make `flyspell-mode' delay after some commands
16947 (put 'org-self-insert-command 'flyspell-delayed t)
16948 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16949 (put 'org-delete-char 'flyspell-delayed t)
16950 (put 'org-delete-backward-char 'flyspell-delayed t)
16952 ;; Make pabbrev-mode expand after Org mode commands
16953 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16954 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16956 (defun org-transpose-words ()
16957 "Transpose words for Org.
16958 This uses the `org-mode-transpose-word-syntax-table' syntax
16959 table, which interprets characters in `org-emphasis-alist' as
16960 word constituents."
16961 (interactive)
16962 (with-syntax-table org-mode-transpose-word-syntax-table
16963 (call-interactively 'transpose-words)))
16965 (defvar org-ctrl-c-ctrl-c-hook nil
16966 "Hook for functions attaching themselves to `C-c C-c'.
16968 This can be used to add additional functionality to the C-c C-c
16969 key which executes context-dependent commands. This hook is run
16970 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
16971 run after the last test.
16973 Each function will be called with no arguments. The function
16974 must check if the context is appropriate for it to act. If yes,
16975 it should do its thing and then return a non-nil value. If the
16976 context is wrong, just do nothing and return nil.")
16978 (defvar org-ctrl-c-ctrl-c-final-hook nil
16979 "Hook for functions attaching themselves to `C-c C-c'.
16981 This can be used to add additional functionality to the C-c C-c
16982 key which executes context-dependent commands. This hook is run
16983 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
16984 before the first test.
16986 Each function will be called with no arguments. The function
16987 must check if the context is appropriate for it to act. If yes,
16988 it should do its thing and then return a non-nil value. If the
16989 context is wrong, just do nothing and return nil.")
16991 (defvar org-tab-first-hook nil
16992 "Hook for functions to attach themselves to TAB.
16993 See `org-ctrl-c-ctrl-c-hook' for more information.
16994 This hook runs as the first action when TAB is pressed, even before
16995 `org-cycle' messes around with the `outline-regexp' to cater for
16996 inline tasks and plain list item folding.
16997 If any function in this hook returns t, any other actions that
16998 would have been caused by TAB (such as table field motion or visibility
16999 cycling) will not occur.")
17001 (defvar org-tab-after-check-for-table-hook nil
17002 "Hook for functions to attach themselves to TAB.
17003 See `org-ctrl-c-ctrl-c-hook' for more information.
17004 This hook runs after it has been established that the cursor is not in a
17005 table, but before checking if the cursor is in a headline or if global cycling
17006 should be done.
17007 If any function in this hook returns t, not other actions like visibility
17008 cycling will be done.")
17010 (defvar org-tab-after-check-for-cycling-hook nil
17011 "Hook for functions to attach themselves to TAB.
17012 See `org-ctrl-c-ctrl-c-hook' for more information.
17013 This hook runs after it has been established that not table field motion and
17014 not visibility should be done because of current context. This is probably
17015 the place where a package like yasnippets can hook in.")
17017 (defvar org-tab-before-tab-emulation-hook nil
17018 "Hook for functions to attach themselves to TAB.
17019 See `org-ctrl-c-ctrl-c-hook' for more information.
17020 This hook runs after every other options for TAB have been exhausted, but
17021 before indentation and \t insertion takes place.")
17023 (defvar org-metaleft-hook nil
17024 "Hook for functions attaching themselves to `M-left'.
17025 See `org-ctrl-c-ctrl-c-hook' for more information.")
17026 (defvar org-metaright-hook nil
17027 "Hook for functions attaching themselves to `M-right'.
17028 See `org-ctrl-c-ctrl-c-hook' for more information.")
17029 (defvar org-metaup-hook nil
17030 "Hook for functions attaching themselves to `M-up'.
17031 See `org-ctrl-c-ctrl-c-hook' for more information.")
17032 (defvar org-metadown-hook nil
17033 "Hook for functions attaching themselves to `M-down'.
17034 See `org-ctrl-c-ctrl-c-hook' for more information.")
17035 (defvar org-shiftmetaleft-hook nil
17036 "Hook for functions attaching themselves to `M-S-left'.
17037 See `org-ctrl-c-ctrl-c-hook' for more information.")
17038 (defvar org-shiftmetaright-hook nil
17039 "Hook for functions attaching themselves to `M-S-right'.
17040 See `org-ctrl-c-ctrl-c-hook' for more information.")
17041 (defvar org-shiftmetaup-hook nil
17042 "Hook for functions attaching themselves to `M-S-up'.
17043 See `org-ctrl-c-ctrl-c-hook' for more information.")
17044 (defvar org-shiftmetadown-hook nil
17045 "Hook for functions attaching themselves to `M-S-down'.
17046 See `org-ctrl-c-ctrl-c-hook' for more information.")
17047 (defvar org-metareturn-hook nil
17048 "Hook for functions attaching themselves to `M-RET'.
17049 See `org-ctrl-c-ctrl-c-hook' for more information.")
17050 (defvar org-shiftup-hook nil
17051 "Hook for functions attaching themselves to `S-up'.
17052 See `org-ctrl-c-ctrl-c-hook' for more information.")
17053 (defvar org-shiftup-final-hook nil
17054 "Hook for functions attaching themselves to `S-up'.
17055 This one runs after all other options except shift-select have been excluded.
17056 See `org-ctrl-c-ctrl-c-hook' for more information.")
17057 (defvar org-shiftdown-hook nil
17058 "Hook for functions attaching themselves to `S-down'.
17059 See `org-ctrl-c-ctrl-c-hook' for more information.")
17060 (defvar org-shiftdown-final-hook nil
17061 "Hook for functions attaching themselves to `S-down'.
17062 This one runs after all other options except shift-select have been excluded.
17063 See `org-ctrl-c-ctrl-c-hook' for more information.")
17064 (defvar org-shiftleft-hook nil
17065 "Hook for functions attaching themselves to `S-left'.
17066 See `org-ctrl-c-ctrl-c-hook' for more information.")
17067 (defvar org-shiftleft-final-hook nil
17068 "Hook for functions attaching themselves to `S-left'.
17069 This one runs after all other options except shift-select have been excluded.
17070 See `org-ctrl-c-ctrl-c-hook' for more information.")
17071 (defvar org-shiftright-hook nil
17072 "Hook for functions attaching themselves to `S-right'.
17073 See `org-ctrl-c-ctrl-c-hook' for more information.")
17074 (defvar org-shiftright-final-hook nil
17075 "Hook for functions attaching themselves to `S-right'.
17076 This one runs after all other options except shift-select have been excluded.
17077 See `org-ctrl-c-ctrl-c-hook' for more information.")
17079 (defun org-modifier-cursor-error ()
17080 "Throw an error, a modified cursor command was applied in wrong context."
17081 (user-error "This command is active in special context like tables, headlines or items"))
17083 (defun org-shiftselect-error ()
17084 "Throw an error because Shift-Cursor command was applied in wrong context."
17085 (if (and (boundp 'shift-select-mode) shift-select-mode)
17086 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
17087 (user-error "This command works only in special context like headlines or timestamps")))
17089 (defun org-call-for-shift-select (cmd)
17090 (let ((this-command-keys-shift-translated t))
17091 (call-interactively cmd)))
17093 (defun org-shifttab (&optional arg)
17094 "Global visibility cycling or move to previous table field.
17095 Call `org-table-previous-field' within a table.
17096 When ARG is nil, cycle globally through visibility states.
17097 When ARG is a numeric prefix, show contents of this level."
17098 (interactive "P")
17099 (cond
17100 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17101 ((integerp arg)
17102 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17103 (message "Content view to level: %d" arg)
17104 (org-content (prefix-numeric-value arg2))
17105 (org-cycle-show-empty-lines t)
17106 (setq org-cycle-global-status 'overview)))
17107 (t (call-interactively 'org-global-cycle))))
17109 (defun org-shiftmetaleft ()
17110 "Promote subtree or delete table column.
17111 Calls `org-promote-subtree', `org-outdent-item-tree', or
17112 `org-table-delete-column', depending on context. See the
17113 individual commands for more information."
17114 (interactive)
17115 (cond
17116 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17117 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17118 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
17119 ((if (not (org-region-active-p)) (org-at-item-p)
17120 (save-excursion (goto-char (region-beginning))
17121 (org-at-item-p)))
17122 (call-interactively 'org-outdent-item-tree))
17123 (t (org-modifier-cursor-error))))
17125 (defun org-shiftmetaright ()
17126 "Demote subtree or insert table column.
17127 Calls `org-demote-subtree', `org-indent-item-tree', or
17128 `org-table-insert-column', depending on context. See the
17129 individual commands for more information."
17130 (interactive)
17131 (cond
17132 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17133 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17134 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
17135 ((if (not (org-region-active-p)) (org-at-item-p)
17136 (save-excursion (goto-char (region-beginning))
17137 (org-at-item-p)))
17138 (call-interactively 'org-indent-item-tree))
17139 (t (org-modifier-cursor-error))))
17141 (defun org-shiftmetaup (&optional _arg)
17142 "Drag the line at point up.
17143 In a table, kill the current row.
17144 On a clock timestamp, update the value of the timestamp like `S-<up>'
17145 but also adjust the previous clocked item in the clock history.
17146 Everywhere else, drag the line at point up."
17147 (interactive "P")
17148 (cond
17149 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17150 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17151 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
17152 (call-interactively 'org-timestamp-up)))
17153 (t (call-interactively 'org-drag-line-backward))))
17155 (defun org-shiftmetadown (&optional _arg)
17156 "Drag the line at point down.
17157 In a table, insert an empty row at the current line.
17158 On a clock timestamp, update the value of the timestamp like `S-<down>'
17159 but also adjust the previous clocked item in the clock history.
17160 Everywhere else, drag the line at point down."
17161 (interactive "P")
17162 (cond
17163 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17164 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17165 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
17166 (call-interactively 'org-timestamp-down)))
17167 (t (call-interactively 'org-drag-line-forward))))
17169 (defsubst org-hidden-tree-error ()
17170 (user-error
17171 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17173 (defun org-metaleft (&optional _arg)
17174 "Promote heading, list item at point or move table column left.
17176 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
17177 depending on context. With no specific context, calls the Emacs
17178 default `backward-word'. See the individual commands for more
17179 information.
17181 This function runs the hook `org-metaleft-hook' as a first step,
17182 and returns at first non-nil value."
17183 (interactive "P")
17184 (cond
17185 ((run-hook-with-args-until-success 'org-metaleft-hook))
17186 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17187 ((org-with-limited-levels
17188 (or (org-at-heading-p)
17189 (and (org-region-active-p)
17190 (save-excursion
17191 (goto-char (region-beginning))
17192 (org-at-heading-p)))))
17193 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17194 (call-interactively 'org-do-promote))
17195 ;; At an inline task.
17196 ((org-at-heading-p)
17197 (call-interactively 'org-inlinetask-promote))
17198 ((or (org-at-item-p)
17199 (and (org-region-active-p)
17200 (save-excursion
17201 (goto-char (region-beginning))
17202 (org-at-item-p))))
17203 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17204 (call-interactively 'org-outdent-item))
17205 (t (call-interactively 'backward-word))))
17207 (defun org-metaright (&optional _arg)
17208 "Demote heading, list item at point or move table column right.
17210 In front of a drawer or a block keyword, indent it correctly.
17212 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
17213 `org-indent-drawer' or `org-indent-block' depending on context.
17214 With no specific context, calls the Emacs default `forward-word'.
17215 See the individual commands for more information.
17217 This function runs the hook `org-metaright-hook' as a first step,
17218 and returns at first non-nil value."
17219 (interactive "P")
17220 (cond
17221 ((run-hook-with-args-until-success 'org-metaright-hook))
17222 ((org-at-table-p) (call-interactively 'org-table-move-column))
17223 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
17224 ((org-at-block-p) (call-interactively 'org-indent-block))
17225 ((org-with-limited-levels
17226 (or (org-at-heading-p)
17227 (and (org-region-active-p)
17228 (save-excursion
17229 (goto-char (region-beginning))
17230 (org-at-heading-p)))))
17231 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17232 (call-interactively 'org-do-demote))
17233 ;; At an inline task.
17234 ((org-at-heading-p)
17235 (call-interactively 'org-inlinetask-demote))
17236 ((or (org-at-item-p)
17237 (and (org-region-active-p)
17238 (save-excursion
17239 (goto-char (region-beginning))
17240 (org-at-item-p))))
17241 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17242 (call-interactively 'org-indent-item))
17243 (t (call-interactively 'forward-word))))
17245 (defun org-check-for-hidden (what)
17246 "Check if there are hidden headlines/items in the current visual line.
17247 WHAT can be either `headlines' or `items'. If the current line is
17248 an outline or item heading and it has a folded subtree below it,
17249 this function returns t, nil otherwise."
17250 (let ((re (cond
17251 ((eq what 'headlines) org-outline-regexp-bol)
17252 ((eq what 'items) (org-item-beginning-re))
17253 (t (error "This should not happen"))))
17254 beg end)
17255 (save-excursion
17256 (catch 'exit
17257 (unless (org-region-active-p)
17258 (setq beg (point-at-bol))
17259 (beginning-of-line 2)
17260 (while (and (not (eobp)) ;; this is like `next-line'
17261 (get-char-property (1- (point)) 'invisible))
17262 (beginning-of-line 2))
17263 (setq end (point))
17264 (goto-char beg)
17265 (goto-char (point-at-eol))
17266 (setq end (max end (point)))
17267 (while (re-search-forward re end t)
17268 (when (get-char-property (match-beginning 0) 'invisible)
17269 (throw 'exit t))))
17270 nil))))
17272 (defun org-metaup (&optional _arg)
17273 "Move subtree up or move table row up.
17274 Calls `org-move-subtree-up' or `org-table-move-row' or
17275 `org-move-item-up', depending on context. See the individual commands
17276 for more information."
17277 (interactive "P")
17278 (cond
17279 ((run-hook-with-args-until-success 'org-metaup-hook))
17280 ((org-region-active-p)
17281 (let* ((a (save-excursion
17282 (goto-char (min (region-beginning) (region-end)))
17283 (line-beginning-position)))
17284 (b (save-excursion
17285 (goto-char (max (region-beginning) (region-end)))
17286 (if (bolp) (1- (point)) (line-end-position))))
17287 (c (save-excursion
17288 (goto-char a)
17289 (move-beginning-of-line 0)
17290 (point)))
17291 (d (save-excursion
17292 (goto-char a)
17293 (move-end-of-line 0)
17294 (point))))
17295 (transpose-regions a b c d)
17296 (goto-char c)))
17297 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17298 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
17299 ((org-at-item-p) (call-interactively 'org-move-item-up))
17300 (t (org-drag-element-backward))))
17302 (defun org-metadown (&optional _arg)
17303 "Move subtree down or move table row down.
17304 Calls `org-move-subtree-down' or `org-table-move-row' or
17305 `org-move-item-down', depending on context. See the individual
17306 commands for more information."
17307 (interactive "P")
17308 (cond
17309 ((run-hook-with-args-until-success 'org-metadown-hook))
17310 ((org-region-active-p)
17311 (let* ((a (save-excursion
17312 (goto-char (min (region-beginning) (region-end)))
17313 (line-beginning-position)))
17314 (b (save-excursion
17315 (goto-char (max (region-beginning) (region-end)))
17316 (if (bolp) (1- (point)) (line-end-position))))
17317 (c (save-excursion
17318 (goto-char b)
17319 (move-beginning-of-line (if (bolp) 1 2))
17320 (point)))
17321 (d (save-excursion
17322 (goto-char b)
17323 (move-end-of-line (if (bolp) 1 2))
17324 (point))))
17325 (transpose-regions a b c d)
17326 (goto-char d)))
17327 ((org-at-table-p) (call-interactively 'org-table-move-row))
17328 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
17329 ((org-at-item-p) (call-interactively 'org-move-item-down))
17330 (t (org-drag-element-forward))))
17332 (defun org-shiftup (&optional arg)
17333 "Act on current element according to context.
17334 Call `org-timestamp-up' or `org-priority-up', or
17335 `org-previous-item', or `org-table-move-cell-up'. See the
17336 individual commands for more information."
17337 (interactive "P")
17338 (cond
17339 ((run-hook-with-args-until-success 'org-shiftup-hook))
17340 ((and org-support-shift-select (org-region-active-p))
17341 (org-call-for-shift-select 'previous-line))
17342 ((org-at-timestamp-p 'lax)
17343 (call-interactively (if org-edit-timestamp-down-means-later
17344 'org-timestamp-down 'org-timestamp-up)))
17345 ((and (not (eq org-support-shift-select 'always))
17346 org-enable-priority-commands
17347 (org-at-heading-p))
17348 (call-interactively 'org-priority-up))
17349 ((and (not org-support-shift-select) (org-at-item-p))
17350 (call-interactively 'org-previous-item))
17351 ((org-clocktable-try-shift 'up arg))
17352 ((org-at-table-p) (org-table-move-cell-up))
17353 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17354 (org-support-shift-select
17355 (org-call-for-shift-select 'previous-line))
17356 (t (org-shiftselect-error))))
17358 (defun org-shiftdown (&optional arg)
17359 "Act on current element according to context.
17360 Call `org-timestamp-down' or `org-priority-down', or
17361 `org-next-item', or `org-table-move-cell-down'. See the
17362 individual commands for more information."
17363 (interactive "P")
17364 (cond
17365 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17366 ((and org-support-shift-select (org-region-active-p))
17367 (org-call-for-shift-select 'next-line))
17368 ((org-at-timestamp-p 'lax)
17369 (call-interactively (if org-edit-timestamp-down-means-later
17370 'org-timestamp-up 'org-timestamp-down)))
17371 ((and (not (eq org-support-shift-select 'always))
17372 org-enable-priority-commands
17373 (org-at-heading-p))
17374 (call-interactively 'org-priority-down))
17375 ((and (not org-support-shift-select) (org-at-item-p))
17376 (call-interactively 'org-next-item))
17377 ((org-clocktable-try-shift 'down arg))
17378 ((org-at-table-p) (org-table-move-cell-down))
17379 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17380 (org-support-shift-select
17381 (org-call-for-shift-select 'next-line))
17382 (t (org-shiftselect-error))))
17384 (defun org-shiftright (&optional arg)
17385 "Act on the current element according to context.
17386 This does one of the following:
17388 - switch a timestamp at point one day into the future
17389 - on a headline, switch to the next TODO keyword.
17390 - on an item, switch entire list to the next bullet type
17391 - on a property line, switch to the next allowed value
17392 - on a clocktable definition line, move time block into the future
17393 - in a table, move a single cell right"
17394 (interactive "P")
17395 (cond
17396 ((run-hook-with-args-until-success 'org-shiftright-hook))
17397 ((and org-support-shift-select (org-region-active-p))
17398 (org-call-for-shift-select 'forward-char))
17399 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
17400 ((and (not (eq org-support-shift-select 'always))
17401 (org-at-heading-p))
17402 (let ((org-inhibit-logging
17403 (not org-treat-S-cursor-todo-selection-as-state-change))
17404 (org-inhibit-blocking
17405 (not org-treat-S-cursor-todo-selection-as-state-change)))
17406 (org-call-with-arg 'org-todo 'right)))
17407 ((or (and org-support-shift-select
17408 (not (eq org-support-shift-select 'always))
17409 (org-at-item-bullet-p))
17410 (and (not org-support-shift-select) (org-at-item-p)))
17411 (org-call-with-arg 'org-cycle-list-bullet nil))
17412 ((and (not (eq org-support-shift-select 'always))
17413 (org-at-property-p))
17414 (call-interactively 'org-property-next-allowed-value))
17415 ((org-clocktable-try-shift 'right arg))
17416 ((org-at-table-p) (org-table-move-cell-right))
17417 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17418 (org-support-shift-select
17419 (org-call-for-shift-select 'forward-char))
17420 (t (org-shiftselect-error))))
17422 (defun org-shiftleft (&optional arg)
17423 "Act on current element according to context.
17424 This does one of the following:
17426 - switch a timestamp at point one day into the past
17427 - on a headline, switch to the previous TODO keyword.
17428 - on an item, switch entire list to the previous bullet type
17429 - on a property line, switch to the previous allowed value
17430 - on a clocktable definition line, move time block into the past
17431 - in a table, move a single cell left"
17432 (interactive "P")
17433 (cond
17434 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17435 ((and org-support-shift-select (org-region-active-p))
17436 (org-call-for-shift-select 'backward-char))
17437 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
17438 ((and (not (eq org-support-shift-select 'always))
17439 (org-at-heading-p))
17440 (let ((org-inhibit-logging
17441 (not org-treat-S-cursor-todo-selection-as-state-change))
17442 (org-inhibit-blocking
17443 (not org-treat-S-cursor-todo-selection-as-state-change)))
17444 (org-call-with-arg 'org-todo 'left)))
17445 ((or (and org-support-shift-select
17446 (not (eq org-support-shift-select 'always))
17447 (org-at-item-bullet-p))
17448 (and (not org-support-shift-select) (org-at-item-p)))
17449 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17450 ((and (not (eq org-support-shift-select 'always))
17451 (org-at-property-p))
17452 (call-interactively 'org-property-previous-allowed-value))
17453 ((org-clocktable-try-shift 'left arg))
17454 ((org-at-table-p) (org-table-move-cell-left))
17455 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17456 (org-support-shift-select
17457 (org-call-for-shift-select 'backward-char))
17458 (t (org-shiftselect-error))))
17460 (defun org-shiftcontrolright ()
17461 "Switch to next TODO set."
17462 (interactive)
17463 (cond
17464 ((and org-support-shift-select (org-region-active-p))
17465 (org-call-for-shift-select 'forward-word))
17466 ((and (not (eq org-support-shift-select 'always))
17467 (org-at-heading-p))
17468 (org-call-with-arg 'org-todo 'nextset))
17469 (org-support-shift-select
17470 (org-call-for-shift-select 'forward-word))
17471 (t (org-shiftselect-error))))
17473 (defun org-shiftcontrolleft ()
17474 "Switch to previous TODO set."
17475 (interactive)
17476 (cond
17477 ((and org-support-shift-select (org-region-active-p))
17478 (org-call-for-shift-select 'backward-word))
17479 ((and (not (eq org-support-shift-select 'always))
17480 (org-at-heading-p))
17481 (org-call-with-arg 'org-todo 'previousset))
17482 (org-support-shift-select
17483 (org-call-for-shift-select 'backward-word))
17484 (t (org-shiftselect-error))))
17486 (defun org-shiftcontrolup (&optional n)
17487 "Change timestamps synchronously up in CLOCK log lines.
17488 Optional argument N tells to change by that many units."
17489 (interactive "P")
17490 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
17491 (let (org-support-shift-select)
17492 (org-clock-timestamps-up n))
17493 (user-error "Not at a clock log")))
17495 (defun org-shiftcontroldown (&optional n)
17496 "Change timestamps synchronously down in CLOCK log lines.
17497 Optional argument N tells to change by that many units."
17498 (interactive "P")
17499 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
17500 (let (org-support-shift-select)
17501 (org-clock-timestamps-down n))
17502 (user-error "Not at a clock log")))
17504 (defun org-increase-number-at-point (&optional inc)
17505 "Increment the number at point.
17506 With an optional prefix numeric argument INC, increment using
17507 this numeric value."
17508 (interactive "p")
17509 (if (not (number-at-point))
17510 (user-error "Not on a number")
17511 (unless inc (setq inc 1))
17512 (let ((pos (point))
17513 (beg (skip-chars-backward "-+^/*0-9eE."))
17514 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
17515 (setq nap (buffer-substring-no-properties
17516 (+ pos beg) (+ pos beg end)))
17517 (delete-region (+ pos beg) (+ pos beg end))
17518 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
17519 (when (org-at-table-p)
17520 (org-table-align)
17521 (org-table-end-of-field 1))))
17523 (defun org-decrease-number-at-point (&optional inc)
17524 "Decrement the number at point.
17525 With an optional prefix numeric argument INC, decrement using
17526 this numeric value."
17527 (interactive "p")
17528 (org-increase-number-at-point (- (or inc 1))))
17530 (defun org-ctrl-c-ret ()
17531 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17532 (interactive)
17533 (cond
17534 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17535 (t (call-interactively 'org-insert-heading))))
17537 (defun org-find-visible ()
17538 (let ((s (point)))
17539 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17540 (get-char-property s 'invisible)))
17542 (defun org-find-invisible ()
17543 (let ((s (point)))
17544 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17545 (not (get-char-property s 'invisible))))
17548 (defun org-copy-visible (beg end)
17549 "Copy the visible parts of the region."
17550 (interactive "r")
17551 (let ((result ""))
17552 (while (/= beg end)
17553 (when (get-char-property beg 'invisible)
17554 (setq beg (next-single-char-property-change beg 'invisible nil end)))
17555 (let ((next (next-single-char-property-change beg 'invisible nil end)))
17556 (setq result (concat result (buffer-substring beg next)))
17557 (setq beg next)))
17558 (setq deactivate-mark t)
17559 (kill-new result)
17560 (message "Visible strings have been copied to the kill ring.")))
17562 (defun org-copy-special ()
17563 "Copy region in table or copy current subtree.
17564 Calls `org-table-copy-region' or `org-copy-subtree', depending on
17565 context. See the individual commands for more information."
17566 (interactive)
17567 (call-interactively
17568 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
17570 (defun org-cut-special ()
17571 "Cut region in table or cut current subtree.
17572 Calls `org-table-cut-region' or `org-cut-subtree', depending on
17573 context. See the individual commands for more information."
17574 (interactive)
17575 (call-interactively
17576 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
17578 (defun org-paste-special (arg)
17579 "Paste rectangular region into table, or past subtree relative to level.
17580 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17581 See the individual commands for more information."
17582 (interactive "P")
17583 (if (org-at-table-p)
17584 (org-table-paste-rectangle)
17585 (org-paste-subtree arg)))
17587 (defun org-edit-special (&optional arg)
17588 "Call a special editor for the element at point.
17589 When at a table, call the formula editor with `org-table-edit-formulas'.
17590 When in a source code block, call `org-edit-src-code'.
17591 When in a fixed-width region, call `org-edit-fixed-width-region'.
17592 When in an export block, call `org-edit-export-block'.
17593 When in a LaTeX environment, call `org-edit-latex-environment'.
17594 When at an #+INCLUDE keyword, visit the included file.
17595 When at a footnote reference, call `org-edit-footnote-reference'.
17596 When at a planning line call, `org-deadline' and/or `org-schedule'.
17597 When at an active timestamp, call `org-time-stamp'.
17598 When at an inactive timestamp, call `org-time-stamp-inactive'.
17599 On a link, call `ffap' to visit the link at point.
17600 Otherwise, return a user error."
17601 (interactive "P")
17602 (let ((element (org-element-at-point)))
17603 (barf-if-buffer-read-only)
17604 (pcase (org-element-type element)
17605 (`src-block
17606 (if (not arg) (org-edit-src-code)
17607 (let* ((info (org-babel-get-src-block-info))
17608 (lang (nth 0 info))
17609 (params (nth 2 info))
17610 (session (cdr (assq :session params))))
17611 (if (not session) (org-edit-src-code)
17612 ;; At a source block with a session and function called
17613 ;; with an ARG: switch to the buffer related to the
17614 ;; inferior process.
17615 (switch-to-buffer
17616 (funcall (intern (concat "org-babel-prep-session:" lang))
17617 session params))))))
17618 (`keyword
17619 (unless (member (org-element-property :key element)
17620 '("INCLUDE" "SETUPFILE"))
17621 (user-error "No special environment to edit here"))
17622 (let ((value (org-element-property :value element)))
17623 (unless (org-string-nw-p value) (user-error "No file to edit"))
17624 (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
17625 (or (match-string 1 value)
17626 (match-string 0 value)))))
17627 (when (org-file-url-p file)
17628 (user-error "Files located with a URL cannot be edited"))
17629 (org-link-open-from-string
17630 (format "[[%s]]" (expand-file-name file))))))
17631 (`table
17632 (if (eq (org-element-property :type element) 'table.el)
17633 (org-edit-table.el)
17634 (call-interactively 'org-table-edit-formulas)))
17635 ;; Only Org tables contain `table-row' type elements.
17636 (`table-row (call-interactively 'org-table-edit-formulas))
17637 (`example-block (org-edit-src-code))
17638 (`export-block (org-edit-export-block))
17639 (`fixed-width (org-edit-fixed-width-region))
17640 (`latex-environment (org-edit-latex-environment))
17641 (`planning
17642 (let ((proplist (cadr element)))
17643 (mapc #'call-interactively
17644 (remq nil
17645 (list
17646 (when (plist-get proplist :deadline) #'org-deadline)
17647 (when (plist-get proplist :scheduled) #'org-schedule))))))
17649 ;; No notable element at point. Though, we may be at a link or
17650 ;; a footnote reference, which are objects. Thus, scan deeper.
17651 (let ((context (org-element-context element)))
17652 (pcase (org-element-type context)
17653 (`footnote-reference (org-edit-footnote-reference))
17654 (`inline-src-block (org-edit-inline-src-code))
17655 (`timestamp (if (eq 'inactive (org-element-property :type context))
17656 (call-interactively #'org-time-stamp-inactive)
17657 (call-interactively #'org-time-stamp)))
17658 (`link (call-interactively #'ffap))
17659 (_ (user-error "No special environment to edit here"))))))))
17661 (defun org-ctrl-c-ctrl-c (&optional arg)
17662 "Set tags in headline, or update according to changed information at point.
17664 This command does many different things, depending on context:
17666 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17667 this is what we do.
17669 - If the cursor is on a statistics cookie, update it.
17671 - If the cursor is in a headline, prompt for tags and insert them
17672 into the current line, aligned to `org-tags-column'. When called
17673 with prefix arg, realign all tags in the current buffer.
17675 - If the cursor is in one of the special #+KEYWORD lines, this
17676 triggers scanning the buffer for these lines and updating the
17677 information.
17679 - If the cursor is inside a table, realign the table. This command
17680 works even if the automatic table editor has been turned off.
17682 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17683 the entire table.
17685 - If the cursor is at a footnote reference or definition, jump to
17686 the corresponding definition or references, respectively.
17688 - If the cursor is a the beginning of a dynamic block, update it.
17690 - If the current buffer is a capture buffer, close note and file it.
17692 - If the cursor is on a <<<target>>>, update radio targets and
17693 corresponding links in this buffer.
17695 - If the cursor is on a numbered item in a plain list, renumber the
17696 ordered list.
17698 - If the cursor is on a checkbox, toggle it.
17700 - If the cursor is on a code block, evaluate it. The variable
17701 `org-confirm-babel-evaluate' can be used to control prompting
17702 before code block evaluation, by default every code block
17703 evaluation requires confirmation. Code block evaluation can be
17704 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17705 (interactive "P")
17706 (cond
17707 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
17708 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17709 (org-remove-occur-highlights)
17710 (message "Temporary highlights/overlays removed from current buffer"))
17711 ((and (local-variable-p 'org-finish-function)
17712 (fboundp org-finish-function))
17713 (funcall org-finish-function))
17714 ((org-babel-hash-at-point))
17715 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17717 (let* ((context
17718 (org-element-lineage
17719 (org-element-context)
17720 ;; Limit to supported contexts.
17721 '(babel-call clock dynamic-block footnote-definition
17722 footnote-reference inline-babel-call inline-src-block
17723 inlinetask item keyword node-property paragraph
17724 plain-list planning property-drawer radio-target
17725 src-block statistics-cookie table table-cell table-row
17726 timestamp)
17728 (type (org-element-type context)))
17729 ;; For convenience: at the first line of a paragraph on the same
17730 ;; line as an item, apply function on that item instead.
17731 (when (eq type 'paragraph)
17732 (let ((parent (org-element-property :parent context)))
17733 (when (and (eq (org-element-type parent) 'item)
17734 (= (line-beginning-position)
17735 (org-element-property :begin parent)))
17736 (setq context parent)
17737 (setq type 'item))))
17738 ;; Act according to type of element or object at point.
17740 ;; Do nothing on a blank line, except if it is contained in
17741 ;; a source block. Hence, we first check if point is in such
17742 ;; a block and then if it is at a blank line.
17743 (pcase type
17744 ((or `inline-src-block `src-block)
17745 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
17746 (org-babel-eval-wipe-error-buffer)
17747 (org-babel-execute-src-block
17748 current-prefix-arg (org-babel-get-src-block-info nil context))))
17749 ((guard (org-match-line "[ \t]*$"))
17750 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
17751 (user-error
17752 (substitute-command-keys
17753 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
17754 ((or `babel-call `inline-babel-call)
17755 (let ((info (org-babel-lob-get-info context)))
17756 (when info (org-babel-execute-src-block nil info))))
17757 (`clock (org-clock-update-time-maybe))
17758 (`dynamic-block
17759 (save-excursion
17760 (goto-char (org-element-property :post-affiliated context))
17761 (org-update-dblock)))
17762 (`footnote-definition
17763 (goto-char (org-element-property :post-affiliated context))
17764 (call-interactively 'org-footnote-action))
17765 (`footnote-reference (call-interactively #'org-footnote-action))
17766 ((or `headline `inlinetask)
17767 (save-excursion (goto-char (org-element-property :begin context))
17768 (call-interactively #'org-set-tags-command)))
17769 (`item
17770 ;; At an item: `C-u C-u' sets checkbox to "[-]"
17771 ;; unconditionally, whereas `C-u' will toggle its presence.
17772 ;; Without a universal argument, if the item has a checkbox,
17773 ;; toggle it. Otherwise repair the list.
17774 (let* ((box (org-element-property :checkbox context))
17775 (struct (org-element-property :structure context))
17776 (old-struct (copy-tree struct))
17777 (parents (org-list-parents-alist struct))
17778 (prevs (org-list-prevs-alist struct))
17779 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
17780 (org-list-set-checkbox
17781 (org-element-property :begin context) struct
17782 (cond ((equal arg '(16)) "[-]")
17783 ((and (not box) (equal arg '(4))) "[ ]")
17784 ((or (not box) (equal arg '(4))) nil)
17785 ((eq box 'on) "[ ]")
17786 (t "[X]")))
17787 ;; Mimic `org-list-write-struct' but with grabbing a return
17788 ;; value from `org-list-struct-fix-box'.
17789 (org-list-struct-fix-ind struct parents 2)
17790 (org-list-struct-fix-item-end struct)
17791 (org-list-struct-fix-bul struct prevs)
17792 (org-list-struct-fix-ind struct parents)
17793 (let ((block-item
17794 (org-list-struct-fix-box struct parents prevs orderedp)))
17795 (if (and box (equal struct old-struct))
17796 (if (equal arg '(16))
17797 (message "Checkboxes already reset")
17798 (user-error "Cannot toggle this checkbox: %s"
17799 (if (eq box 'on)
17800 "all subitems checked"
17801 "unchecked subitems")))
17802 (org-list-struct-apply-struct struct old-struct)
17803 (org-update-checkbox-count-maybe))
17804 (when block-item
17805 (message "Checkboxes were removed due to empty box at line %d"
17806 (org-current-line block-item))))))
17807 (`keyword
17808 (let ((org-inhibit-startup-visibility-stuff t)
17809 (org-startup-align-all-tables nil))
17810 (when (boundp 'org-table-coordinate-overlays)
17811 (mapc #'delete-overlay org-table-coordinate-overlays)
17812 (setq org-table-coordinate-overlays nil))
17813 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17814 (message "Local setup has been refreshed"))
17815 (`plain-list
17816 ;; At a plain list, with a double C-u argument, set
17817 ;; checkboxes of each item to "[-]", whereas a single one
17818 ;; will toggle their presence according to the state of the
17819 ;; first item in the list. Without an argument, repair the
17820 ;; list.
17821 (let* ((begin (org-element-property :contents-begin context))
17822 (struct (org-element-property :structure context))
17823 (old-struct (copy-tree struct))
17824 (first-box (save-excursion
17825 (goto-char begin)
17826 (looking-at org-list-full-item-re)
17827 (match-string-no-properties 3)))
17828 (new-box (cond ((equal arg '(16)) "[-]")
17829 ((equal arg '(4)) (unless first-box "[ ]"))
17830 ((equal first-box "[X]") "[ ]")
17831 (t "[X]"))))
17832 (cond
17833 (arg
17834 (dolist (pos
17835 (org-list-get-all-items
17836 begin struct (org-list-prevs-alist struct)))
17837 (org-list-set-checkbox pos struct new-box)))
17838 ((and first-box (eq (point) begin))
17839 ;; For convenience, when point is at bol on the first
17840 ;; item of the list and no argument is provided, simply
17841 ;; toggle checkbox of that item, if any.
17842 (org-list-set-checkbox begin struct new-box)))
17843 (when (equal
17844 (org-list-write-struct
17845 struct (org-list-parents-alist struct) old-struct)
17846 old-struct)
17847 (message "Cannot update this checkbox"))
17848 (org-update-checkbox-count-maybe)))
17849 ((or `property-drawer `node-property)
17850 (call-interactively #'org-property-action))
17851 (`radio-target
17852 (call-interactively #'org-update-radio-target-regexp))
17853 (`statistics-cookie
17854 (call-interactively #'org-update-statistics-cookies))
17855 ((or `table `table-cell `table-row)
17856 ;; At a table, recalculate every field and align it. Also
17857 ;; send the table if necessary. If the table has
17858 ;; a `table.el' type, just give up. At a table row or cell,
17859 ;; maybe recalculate line but always align table.
17860 (if (eq (org-element-property :type context) 'table.el)
17861 (message "%s" (substitute-command-keys "\\<org-mode-map>\
17862 Use `\\[org-edit-special]' to edit table.el tables"))
17863 (if (or (eq type 'table)
17864 ;; Check if point is at a TBLFM line.
17865 (and (eq type 'table-row)
17866 (= (point) (org-element-property :end context))))
17867 (save-excursion
17868 (if (org-at-TBLFM-p)
17869 (progn (require 'org-table)
17870 (org-table-calc-current-TBLFM))
17871 (goto-char (org-element-property :contents-begin context))
17872 (org-call-with-arg 'org-table-recalculate (or arg t))
17873 (orgtbl-send-table 'maybe)))
17874 (org-table-maybe-eval-formula)
17875 (cond (arg (call-interactively #'org-table-recalculate))
17876 ((org-table-maybe-recalculate-line))
17877 (t (org-table-align))))))
17878 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
17879 (org-timestamp-change 0 'day))
17880 ((and `nil (guard (org-at-heading-p)))
17881 ;; When point is on an unsupported object type, we can miss
17882 ;; the fact that it also is at a heading. Handle it here.
17883 (call-interactively #'org-set-tags-command))
17884 ((guard
17885 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
17887 (user-error
17888 (substitute-command-keys
17889 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
17891 (defun org-mode-restart ()
17892 (interactive)
17893 (let ((indent-status (bound-and-true-p org-indent-mode)))
17894 (funcall major-mode)
17895 (hack-local-variables)
17896 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
17897 (org-indent-mode -1))
17898 (org-reset-file-cache))
17899 (message "%s restarted" major-mode))
17901 (defun org-kill-note-or-show-branches ()
17902 "Abort storing current note, or call `outline-show-branches'."
17903 (interactive)
17904 (if (not org-finish-function)
17905 (save-excursion
17906 (save-restriction
17907 (org-narrow-to-subtree)
17908 (org-flag-subtree t)
17909 (call-interactively 'outline-show-branches)
17910 (org-hide-archived-subtrees (point-min) (point-max))))
17911 (let ((org-note-abort t))
17912 (funcall org-finish-function))))
17914 (defun org-delete-indentation (&optional arg)
17915 "Join current line to previous and fix whitespace at join.
17917 If previous line is a headline add to headline title. Otherwise
17918 the function calls `delete-indentation'.
17920 With a non-nil optional argument, join it to the following one."
17921 (interactive "*P")
17922 (if (save-excursion
17923 (beginning-of-line (if arg 1 0))
17924 (let ((case-fold-search nil))
17925 (looking-at org-complex-heading-regexp)))
17926 ;; At headline.
17927 (let ((tags-column (when (match-beginning 5)
17928 (save-excursion (goto-char (match-beginning 5))
17929 (current-column))))
17930 (string (concat " " (progn (when arg (forward-line 1))
17931 (org-trim (delete-and-extract-region
17932 (line-beginning-position)
17933 (line-end-position)))))))
17934 (unless (bobp) (delete-region (point) (1- (point))))
17935 (goto-char (or (match-end 4)
17936 (match-beginning 5)
17937 (match-end 0)))
17938 (skip-chars-backward " \t")
17939 (save-excursion (insert string))
17940 ;; Adjust alignment of tags.
17941 (cond
17942 ((not tags-column)) ;no tags
17943 (org-auto-align-tags (org-align-tags))
17944 (t (org--align-tags-here tags-column)))) ;preserve tags column
17945 (delete-indentation arg)))
17947 (defun org-open-line (n)
17948 "Insert a new row in tables, call `open-line' elsewhere.
17949 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
17950 As a special case, when a document starts with a table, allow to
17951 call `open-line' on the very first character."
17952 (interactive "*p")
17953 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
17954 (org-table-insert-row)
17955 (open-line n)))
17957 (defun org-return (&optional indent)
17958 "Goto next table row or insert a newline.
17960 Calls `org-table-next-row' or `newline', depending on context.
17962 When optional INDENT argument is non-nil, call
17963 `newline-and-indent' instead of `newline'.
17965 When `org-return-follows-link' is non-nil and point is on
17966 a timestamp or a link, call `org-open-at-point'. However, it
17967 will not happen if point is in a table or on a \"dead\"
17968 object (e.g., within a comment). In these case, you need to use
17969 `org-open-at-point' directly."
17970 (interactive)
17971 (let ((context (if org-return-follows-link (org-element-context)
17972 (org-element-at-point))))
17973 (cond
17974 ;; In a table, call `org-table-next-row'. However, before first
17975 ;; column or after last one, split the table.
17976 ((or (and (eq 'table (org-element-type context))
17977 (not (eq 'table.el (org-element-property :type context)))
17978 (>= (point) (org-element-property :contents-begin context))
17979 (< (point) (org-element-property :contents-end context)))
17980 (org-element-lineage context '(table-row table-cell) t))
17981 (if (or (looking-at-p "[ \t]*$")
17982 (save-excursion (skip-chars-backward " \t") (bolp)))
17983 (insert "\n")
17984 (org-table-justify-field-maybe)
17985 (call-interactively #'org-table-next-row)))
17986 ;; On a link or a timestamp, call `org-open-at-point' if
17987 ;; `org-return-follows-link' allows it. Tolerate fuzzy
17988 ;; locations, e.g., in a comment, as `org-open-at-point'.
17989 ((and org-return-follows-link
17990 (or (and (eq 'link (org-element-type context))
17991 ;; Ensure point is not on the white spaces after
17992 ;; the link.
17993 (let ((origin (point)))
17994 (org-with-point-at (org-element-property :end context)
17995 (skip-chars-backward " \t")
17996 (> (point) origin))))
17997 (org-in-regexp org-ts-regexp-both nil t)
17998 (org-in-regexp org-tsr-regexp-both nil t)
17999 (org-in-regexp org-link-any-re nil t)))
18000 (call-interactively #'org-open-at-point))
18001 ;; Insert newline in heading, but preserve tags.
18002 ((and (not (bolp))
18003 (let ((case-fold-search nil))
18004 (org-match-line org-complex-heading-regexp)))
18005 ;; At headline. Split line. However, if point is on keyword,
18006 ;; priority cookie or tags, do not break any of them: add
18007 ;; a newline after the headline instead.
18008 (let ((tags-column (and (match-beginning 5)
18009 (save-excursion (goto-char (match-beginning 5))
18010 (current-column))))
18011 (string
18012 (when (and (match-end 4) (org-point-in-group (point) 4))
18013 (delete-and-extract-region (point) (match-end 4)))))
18014 ;; Adjust tag alignment.
18015 (cond
18016 ((not (and tags-column string)))
18017 (org-auto-align-tags (org-align-tags))
18018 (t (org--align-tags-here tags-column))) ;preserve tags column
18019 (end-of-line)
18020 (org-show-entry)
18021 (if indent (newline-and-indent) (newline))
18022 (when string (save-excursion (insert (org-trim string))))))
18023 ;; In a list, make sure indenting keeps trailing text within.
18024 ((and indent
18025 (not (eolp))
18026 (org-element-lineage context '(item)))
18027 (let ((trailing-data
18028 (delete-and-extract-region (point) (line-end-position))))
18029 (newline-and-indent)
18030 (save-excursion (insert trailing-data))))
18032 ;; Do not auto-fill when point is in an Org property drawer.
18033 (let ((auto-fill-function (and (not (org-at-property-p))
18034 auto-fill-function)))
18035 (if indent
18036 (newline-and-indent)
18037 (newline)))))))
18039 (defun org-return-indent ()
18040 "Goto next table row or insert a newline and indent.
18041 Calls `org-table-next-row' or `newline-and-indent', depending on
18042 context. See the individual commands for more information."
18043 (interactive)
18044 (org-return t))
18046 (defun org-ctrl-c-tab (&optional _arg)
18047 "Toggle columns width in a table, or show children.
18048 Call `org-table-toggle-column-width' if point is in a table.
18049 Otherwise, call `org-show-children'."
18050 (interactive "p")
18051 (call-interactively
18052 (if (org-at-table-p) #'org-table-toggle-column-width
18053 #'org-show-children)))
18055 (defun org-ctrl-c-star ()
18056 "Compute table, or change heading status of lines.
18057 Calls `org-table-recalculate' or `org-toggle-heading',
18058 depending on context."
18059 (interactive)
18060 (cond
18061 ((org-at-table-p)
18062 (call-interactively 'org-table-recalculate))
18064 ;; Convert all lines in region to list items
18065 (call-interactively 'org-toggle-heading))))
18067 (defun org-ctrl-c-minus ()
18068 "Insert separator line in table or modify bullet status of line.
18069 Also turns a plain line or a region of lines into list items.
18070 Calls `org-table-insert-hline', `org-toggle-item', or
18071 `org-cycle-list-bullet', depending on context."
18072 (interactive)
18073 (cond
18074 ((org-at-table-p)
18075 (call-interactively 'org-table-insert-hline))
18076 ((org-region-active-p)
18077 (call-interactively 'org-toggle-item))
18078 ((org-in-item-p)
18079 (call-interactively 'org-cycle-list-bullet))
18081 (call-interactively 'org-toggle-item))))
18083 (defun org-toggle-heading (&optional nstars)
18084 "Convert headings to normal text, or items or text to headings.
18085 If there is no active region, only convert the current line.
18087 With a `\\[universal-argument]' prefix, convert the whole list at
18088 point into heading.
18090 In a region:
18092 - If the first non blank line is a headline, remove the stars
18093 from all headlines in the region.
18095 - If it is a normal line, turn each and every normal line (i.e.,
18096 not an heading or an item) in the region into headings. If you
18097 want to convert only the first line of this region, use one
18098 universal prefix argument.
18100 - If it is a plain list item, turn all plain list items into headings.
18102 When converting a line into a heading, the number of stars is chosen
18103 such that the lines become children of the current entry. However,
18104 when a numeric prefix argument is given, its value determines the
18105 number of stars to add."
18106 (interactive "P")
18107 (let ((skip-blanks
18108 (function
18109 ;; Return beginning of first non-blank line, starting from
18110 ;; line at POS.
18111 (lambda (pos)
18112 (save-excursion
18113 (goto-char pos)
18114 (while (org-at-comment-p) (forward-line))
18115 (skip-chars-forward " \r\t\n")
18116 (point-at-bol)))))
18117 beg end toggled)
18118 ;; Determine boundaries of changes. If a universal prefix has
18119 ;; been given, put the list in a region. If region ends at a bol,
18120 ;; do not consider the last line to be in the region.
18122 (when (and current-prefix-arg (org-at-item-p))
18123 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
18124 (org-mark-element))
18126 (if (org-region-active-p)
18127 (setq beg (funcall skip-blanks (region-beginning))
18128 end (copy-marker (save-excursion
18129 (goto-char (region-end))
18130 (if (bolp) (point) (point-at-eol)))))
18131 (setq beg (funcall skip-blanks (point-at-bol))
18132 end (copy-marker (point-at-eol))))
18133 ;; Ensure inline tasks don't count as headings.
18134 (org-with-limited-levels
18135 (save-excursion
18136 (goto-char beg)
18137 (cond
18138 ;; Case 1. Started at an heading: de-star headings.
18139 ((org-at-heading-p)
18140 (while (< (point) end)
18141 (when (org-at-heading-p t)
18142 (looking-at org-outline-regexp) (replace-match "")
18143 (setq toggled t))
18144 (forward-line)))
18145 ;; Case 2. Started at an item: change items into headlines.
18146 ;; One star will be added by `org-list-to-subtree'.
18147 ((org-at-item-p)
18148 (while (< (point) end)
18149 (when (org-at-item-p)
18150 ;; Pay attention to cases when region ends before list.
18151 (let* ((struct (org-list-struct))
18152 (list-end
18153 (min (org-list-get-bottom-point struct) (1+ end))))
18154 (save-restriction
18155 (narrow-to-region (point) list-end)
18156 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
18157 (setq toggled t))
18158 (forward-line)))
18159 ;; Case 3. Started at normal text: make every line an heading,
18160 ;; skipping headlines and items.
18161 (t (let* ((stars
18162 (make-string
18163 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
18164 (add-stars
18165 (cond (nstars "") ; stars from prefix only
18166 ((equal stars "") "*") ; before first heading
18167 (org-odd-levels-only "**") ; inside heading, odd
18168 (t "*"))) ; inside heading, oddeven
18169 (rpl (concat stars add-stars " "))
18170 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
18171 (while (< (point) (if (equal nstars '(4)) lend end))
18172 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
18173 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18174 (replace-match (concat rpl (match-string 2))) (setq toggled t))
18175 (forward-line)))))))
18176 (unless toggled (message "Cannot toggle heading from here"))))
18178 (defun org-meta-return (&optional arg)
18179 "Insert a new heading or wrap a region in a table.
18180 Calls `org-insert-heading', `org-insert-item' or
18181 `org-table-wrap-region', depending on context. When called with
18182 an argument, unconditionally call `org-insert-heading'."
18183 (interactive "P")
18184 (org-check-before-invisible-edit 'insert)
18185 (or (run-hook-with-args-until-success 'org-metareturn-hook)
18186 (call-interactively (cond (arg #'org-insert-heading)
18187 ((org-at-table-p) #'org-table-wrap-region)
18188 ((org-in-item-p) #'org-insert-item)
18189 (t #'org-insert-heading)))))
18191 ;;; Menu entries
18193 (defsubst org-in-subtree-not-table-p ()
18194 "Are we in a subtree and not in a table?"
18195 (and (not (org-before-first-heading-p))
18196 (not (org-at-table-p))))
18198 ;; Define the Org mode menus
18199 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18200 '("Tbl"
18201 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18202 ["Next Field" org-cycle (org-at-table-p)]
18203 ["Previous Field" org-shifttab (org-at-table-p)]
18204 ["Next Row" org-return (org-at-table-p)]
18205 "--"
18206 ["Blank Field" org-table-blank-field (org-at-table-p)]
18207 ["Edit Field" org-table-edit-field (org-at-table-p)]
18208 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18209 "--"
18210 ("Column"
18211 ["Move Column Left" org-metaleft (org-at-table-p)]
18212 ["Move Column Right" org-metaright (org-at-table-p)]
18213 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18214 ["Insert Column" org-shiftmetaright (org-at-table-p)]
18215 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
18216 ("Row"
18217 ["Move Row Up" org-metaup (org-at-table-p)]
18218 ["Move Row Down" org-metadown (org-at-table-p)]
18219 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18220 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18221 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18222 "--"
18223 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18224 ("Rectangle"
18225 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18226 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18227 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18228 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18229 "--"
18230 ("Calculate"
18231 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18232 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18233 ["Edit Formulas" org-edit-special (org-at-table-p)]
18234 "--"
18235 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18236 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18237 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18238 "--"
18239 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18240 "--"
18241 ["Sum Column/Rectangle" org-table-sum
18242 (or (org-at-table-p) (org-region-active-p))]
18243 ["Which Column?" org-table-current-column (org-at-table-p)])
18244 ["Debug Formulas"
18245 org-table-toggle-formula-debugger
18246 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
18247 ["Show Col/Row Numbers"
18248 org-table-toggle-coordinate-overlays
18249 :style toggle
18250 :selected (bound-and-true-p org-table-overlay-coordinates)]
18251 "--"
18252 ["Create" org-table-create (not (org-at-table-p))]
18253 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18254 ["Import from File" org-table-import (not (org-at-table-p))]
18255 ["Export to File" org-table-export (org-at-table-p)]
18256 "--"
18257 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
18258 "--"
18259 ("Plot"
18260 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
18261 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
18263 (easy-menu-define org-org-menu org-mode-map "Org menu"
18264 '("Org"
18265 ("Show/Hide"
18266 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18267 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18268 ["Sparse Tree..." org-sparse-tree t]
18269 ["Reveal Context" org-reveal t]
18270 ["Show All" org-show-all t]
18271 "--"
18272 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18273 "--"
18274 ["New Heading" org-insert-heading t]
18275 ("Navigate Headings"
18276 ["Up" outline-up-heading t]
18277 ["Next" outline-next-visible-heading t]
18278 ["Previous" outline-previous-visible-heading t]
18279 ["Next Same Level" outline-forward-same-level t]
18280 ["Previous Same Level" outline-backward-same-level t]
18281 "--"
18282 ["Jump" org-goto t])
18283 ("Edit Structure"
18284 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
18285 "--"
18286 ["Move Subtree Up" org-metaup (org-at-heading-p)]
18287 ["Move Subtree Down" org-metadown (org-at-heading-p)]
18288 "--"
18289 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
18290 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
18291 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18292 "--"
18293 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18294 "--"
18295 ["Copy visible text" org-copy-visible t]
18296 "--"
18297 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
18298 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
18299 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
18300 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
18301 "--"
18302 ["Sort Region/Children" org-sort t]
18303 "--"
18304 ["Convert to odd levels" org-convert-to-odd-levels t]
18305 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18306 ("Editing"
18307 ["Emphasis..." org-emphasize t]
18308 ["Edit Source Example" org-edit-special t]
18309 "--"
18310 ["Footnote new/jump" org-footnote-action t]
18311 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18312 ("Archive"
18313 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
18314 "--"
18315 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
18316 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
18317 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
18319 "--"
18320 ("Hyperlinks"
18321 ["Store Link (Global)" org-store-link t]
18322 ["Find existing link to here" org-occur-link-in-agenda-files t]
18323 ["Insert Link" org-insert-link t]
18324 ["Follow Link" org-open-at-point t]
18325 "--"
18326 ["Next link" org-next-link t]
18327 ["Previous link" org-previous-link t]
18328 "--"
18329 ["Descriptive Links"
18330 org-toggle-link-display
18331 :style radio
18332 :selected org-descriptive-links
18334 ["Literal Links"
18335 org-toggle-link-display
18336 :style radio
18337 :selected (not org-descriptive-links)])
18338 "--"
18339 ("TODO Lists"
18340 ["TODO/DONE/-" org-todo t]
18341 ("Select keyword"
18342 ["Next keyword" org-shiftright (org-at-heading-p)]
18343 ["Previous keyword" org-shiftleft (org-at-heading-p)]
18344 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18345 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
18346 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
18347 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18348 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
18349 "--"
18350 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18351 :selected org-enforce-todo-dependencies :style toggle :active t]
18352 "Settings for tree at point"
18353 ["Do Children sequentially" org-toggle-ordered-property :style radio
18354 :selected (org-entry-get nil "ORDERED")
18355 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18356 ["Do Children parallel" org-toggle-ordered-property :style radio
18357 :selected (not (org-entry-get nil "ORDERED"))
18358 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18359 "--"
18360 ["Set Priority" org-priority t]
18361 ["Priority Up" org-shiftup t]
18362 ["Priority Down" org-shiftdown t]
18363 "--"
18364 ["Get news from all feeds" org-feed-update-all t]
18365 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18366 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18367 ("TAGS and Properties"
18368 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
18369 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18370 "--"
18371 ["Set property" org-set-property (not (org-before-first-heading-p))]
18372 ["Column view of properties" org-columns t]
18373 ["Insert Column View DBlock" org-columns-insert-dblock t])
18374 ("Dates and Scheduling"
18375 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
18376 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
18377 ("Change Date"
18378 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
18379 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
18380 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
18381 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
18382 ["Compute Time Range" org-evaluate-time-range t]
18383 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
18384 ["Deadline" org-deadline (not (org-before-first-heading-p))]
18385 "--"
18386 ["Custom time format" org-toggle-time-stamp-overlays
18387 :style radio :selected org-display-custom-times]
18388 "--"
18389 ["Goto Calendar" org-goto-calendar t]
18390 ["Date from Calendar" org-date-from-calendar t]
18391 "--"
18392 ["Start/Restart Timer" org-timer-start t]
18393 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18394 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18395 ["Insert Timer String" org-timer t]
18396 ["Insert Timer Item" org-timer-item t])
18397 ("Logging work"
18398 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18399 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18400 ["Clock out" org-clock-out t]
18401 ["Clock cancel" org-clock-cancel t]
18402 "--"
18403 ["Mark as default task" org-clock-mark-default-task t]
18404 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18405 ["Goto running clock" org-clock-goto t]
18406 "--"
18407 ["Display times" org-clock-display t]
18408 ["Create clock table" org-clock-report t]
18409 "--"
18410 ["Record DONE time"
18411 (progn (setq org-log-done (not org-log-done))
18412 (message "Switching to %s will %s record a timestamp"
18413 (car org-done-keywords)
18414 (if org-log-done "automatically" "not")))
18415 :style toggle :selected org-log-done])
18416 "--"
18417 ["Agenda Command..." org-agenda t]
18418 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18419 ("File List for Agenda")
18420 ("Special views current file"
18421 ["TODO Tree" org-show-todo-tree t]
18422 ["Check Deadlines" org-check-deadlines t]
18423 ["Tags/Property tree" org-match-sparse-tree t])
18424 "--"
18425 ["Export/Publish..." org-export-dispatch t]
18426 ("LaTeX"
18427 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
18428 :style toggle :selected org-cdlatex-mode]
18429 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18430 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18431 ["Modify math symbol" org-cdlatex-math-modify
18432 (org-inside-LaTeX-fragment-p)]
18433 ["Insert citation" org-reftex-citation t])
18434 "--"
18435 ("MobileOrg"
18436 ["Push Files and Views" org-mobile-push t]
18437 ["Get Captured and Flagged" org-mobile-pull t]
18438 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
18439 "--"
18440 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18441 "--"
18442 ("Documentation"
18443 ["Show Version" org-version t]
18444 ["Info Documentation" org-info t]
18445 ["Browse Org News" org-browse-news t])
18446 ("Customize"
18447 ["Browse Org Group" org-customize t]
18448 "--"
18449 ["Expand This Menu" org-create-customize-menu
18450 (fboundp 'customize-menu-create)])
18451 ["Send bug report" org-submit-bug-report t]
18452 "--"
18453 ("Refresh/Reload"
18454 ["Refresh setup current buffer" org-mode-restart t]
18455 ["Reload Org (after update)" org-reload t]
18456 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
18458 (defun org-info (&optional node)
18459 "Read documentation for Org in the info system.
18460 With optional NODE, go directly to that node."
18461 (interactive)
18462 (info (format "(org)%s" (or node ""))))
18464 (defun org-browse-news ()
18465 "Browse the news for the latest major release."
18466 (interactive)
18467 (browse-url "https://orgmode.org/Changes.html"))
18469 ;;;###autoload
18470 (defun org-submit-bug-report ()
18471 "Submit a bug report on Org via mail.
18473 Don't hesitate to report any problems or inaccurate documentation.
18475 If you don't have setup sending mail from (X)Emacs, please copy the
18476 output buffer into your mail program, as it gives us important
18477 information about your Org version and configuration."
18478 (interactive)
18479 (require 'reporter)
18480 (defvar reporter-prompt-for-summary-p)
18481 (org-load-modules-maybe)
18482 (org-require-autoloaded-modules)
18483 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18484 (reporter-submit-bug-report
18485 "emacs-orgmode@gnu.org"
18486 (org-version nil 'full)
18487 (let (list)
18488 (save-window-excursion
18489 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18490 (delete-other-windows)
18491 (erase-buffer)
18492 (insert "You are about to submit a bug report to the Org mailing list.
18494 We would like to add your full Org and Outline configuration to the
18495 bug report. This greatly simplifies the work of the maintainer and
18496 other experts on the mailing list.
18498 HOWEVER, some variables you have customized may contain private
18499 information. The names of customers, colleagues, or friends, might
18500 appear in the form of file names, tags, todo states, or search strings.
18501 If you answer yes to the prompt, you might want to check and remove
18502 such private information before sending the email.")
18503 (add-text-properties (point-min) (point-max) '(face org-warning))
18504 (when (yes-or-no-p "Include your Org configuration ")
18505 (mapatoms
18506 (lambda (v)
18507 (and (boundp v)
18508 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18509 (or (and (symbol-value v)
18510 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18511 (and
18512 (get v 'custom-type) (get v 'standard-value)
18513 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18514 (push v list)))))
18515 (kill-buffer (get-buffer "*Warn about privacy*"))
18516 list))
18517 nil nil
18518 "Remember to cover the basics, that is, what you expected to happen and
18519 what in fact did happen. You don't know how to make a good report? See
18521 https://orgmode.org/manual/Feedback.html#Feedback
18523 Your bug report will be posted to the Org mailing list.
18524 ------------------------------------------------------------------------")
18525 (save-excursion
18526 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18527 (replace-match "\\1Bug: \\3 [\\2]")))))
18530 (defun org-install-agenda-files-menu ()
18531 (let ((bl (buffer-list)))
18532 (save-excursion
18533 (while bl
18534 (set-buffer (pop bl))
18535 (when (derived-mode-p 'org-mode) (setq bl nil)))
18536 (when (derived-mode-p 'org-mode)
18537 (easy-menu-change
18538 '("Org") "File List for Agenda"
18539 (append
18540 (list
18541 ["Edit File List" (org-edit-agenda-file-list) t]
18542 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18543 ["Remove Current File from List" org-remove-file t]
18544 ["Cycle through agenda files" org-cycle-agenda-files t]
18545 ["Occur in all agenda files" org-occur-in-agenda-files t]
18546 "--")
18547 (mapcar 'org-file-menu-entry
18548 ;; Prevent initialization from failing.
18549 (ignore-errors (org-agenda-files t)))))))))
18551 ;;;; Documentation
18553 (defun org-require-autoloaded-modules ()
18554 (interactive)
18555 (mapc #'require
18556 '(org-agenda org-archive org-attach org-clock org-colview org-id
18557 org-table org-timer)))
18559 ;;;###autoload
18560 (defun org-reload (&optional uncompiled)
18561 "Reload all Org Lisp files.
18562 With prefix arg UNCOMPILED, load the uncompiled versions."
18563 (interactive "P")
18564 (require 'loadhist)
18565 (let* ((org-dir (org-find-library-dir "org"))
18566 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
18567 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
18568 (remove-re (format "\\`%s\\'"
18569 (regexp-opt '("org" "org-loaddefs" "org-version"))))
18570 (feats (delete-dups
18571 (mapcar 'file-name-sans-extension
18572 (mapcar 'file-name-nondirectory
18573 (delq nil
18574 (mapcar 'feature-file
18575 features))))))
18576 (lfeat (append
18577 (sort
18578 (setq feats
18579 (delq nil (mapcar
18580 (lambda (f)
18581 (if (and (string-match feature-re f)
18582 (not (string-match remove-re f)))
18583 f nil))
18584 feats)))
18585 'string-lessp)
18586 (list "org-version" "org")))
18587 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
18588 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
18589 load-uncore load-misses)
18590 (setq load-misses
18591 (delq 't
18592 (mapcar (lambda (f)
18593 (or (org-load-noerror-mustsuffix (concat org-dir f))
18594 (and (string= org-dir contrib-dir)
18595 (org-load-noerror-mustsuffix (concat contrib-dir f)))
18596 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
18597 (add-to-list 'load-uncore f 'append)
18600 lfeat)))
18601 (when load-uncore
18602 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
18603 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
18604 (if load-misses
18605 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
18606 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
18607 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
18609 ;;;###autoload
18610 (defun org-customize ()
18611 "Call the customize function with org as argument."
18612 (interactive)
18613 (org-load-modules-maybe)
18614 (org-require-autoloaded-modules)
18615 (customize-browse 'org))
18617 (defun org-create-customize-menu ()
18618 "Create a full customization menu for Org mode, insert it into the menu."
18619 (interactive)
18620 (org-load-modules-maybe)
18621 (org-require-autoloaded-modules)
18622 (if (fboundp 'customize-menu-create)
18623 (progn
18624 (easy-menu-change
18625 '("Org") "Customize"
18626 `(["Browse Org group" org-customize t]
18627 "--"
18628 ,(customize-menu-create 'org)
18629 ["Set" Custom-set t]
18630 ["Save" Custom-save t]
18631 ["Reset to Current" Custom-reset-current t]
18632 ["Reset to Saved" Custom-reset-saved t]
18633 ["Reset to Standard Settings" Custom-reset-standard t]))
18634 (message "\"Org\"-menu now contains full customization menu"))
18635 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18637 ;;;; Miscellaneous stuff
18639 ;;; Generally useful functions
18641 (defun org-in-clocktable-p ()
18642 "Check if the cursor is in a clocktable."
18643 (let ((pos (point)) start)
18644 (save-excursion
18645 (end-of-line 1)
18646 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
18647 (setq start (match-beginning 0))
18648 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
18649 (>= (match-end 0) pos)
18650 start))))
18652 (defun org-in-verbatim-emphasis ()
18653 (save-match-data
18654 (and (org-in-regexp org-verbatim-re 2)
18655 (>= (point) (match-beginning 3))
18656 (<= (point) (match-end 4)))))
18658 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18659 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18660 (if (and marker (marker-buffer marker)
18661 (buffer-live-p (marker-buffer marker)))
18662 (progn
18663 (pop-to-buffer-same-window (marker-buffer marker))
18664 (when (or (> marker (point-max)) (< marker (point-min)))
18665 (widen))
18666 (goto-char marker)
18667 (org-show-context 'org-goto))
18668 (if bookmark
18669 (bookmark-jump bookmark)
18670 (error "Cannot find location"))))
18672 (defun org-quote-csv-field (s)
18673 "Quote field for inclusion in CSV material."
18674 (if (string-match "[\",]" s)
18675 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18678 (defun org-force-self-insert (N)
18679 "Needed to enforce self-insert under remapping."
18680 (interactive "p")
18681 (self-insert-command N))
18683 (defun org-quote-vert (s)
18684 "Replace \"|\" with \"\\vert\"."
18685 (while (string-match "|" s)
18686 (setq s (replace-match "\\vert" t t s)))
18689 (defun org-uuidgen-p (s)
18690 "Is S an ID created by UUIDGEN?"
18691 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18693 (defun org-in-src-block-p (&optional inside)
18694 "Whether point is in a code source block.
18695 When INSIDE is non-nil, don't consider we are within a source
18696 block when point is at #+BEGIN_SRC or #+END_SRC."
18697 (let ((case-fold-search t))
18698 (or (and (eq (get-char-property (point) 'src-block) t))
18699 (and (not inside)
18700 (save-match-data
18701 (save-excursion
18702 (beginning-of-line)
18703 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
18705 (defun org-context ()
18706 "Return a list of contexts of the current cursor position.
18707 If several contexts apply, all are returned.
18708 Each context entry is a list with a symbol naming the context, and
18709 two positions indicating start and end of the context. Possible
18710 contexts are:
18712 :headline anywhere in a headline
18713 :headline-stars on the leading stars in a headline
18714 :todo-keyword on a TODO keyword (including DONE) in a headline
18715 :tags on the TAGS in a headline
18716 :priority on the priority cookie in a headline
18717 :item on the first line of a plain list item
18718 :item-bullet on the bullet/number of a plain list item
18719 :checkbox on the checkbox in a plain list item
18720 :table in an Org table
18721 :table-special on a special filed in a table
18722 :table-table in a table.el table
18723 :clocktable in a clocktable
18724 :src-block in a source block
18725 :link on a hyperlink
18726 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
18727 :latex-fragment on a LaTeX fragment
18728 :latex-preview on a LaTeX fragment with overlaid preview image
18730 This function expects the position to be visible because it uses font-lock
18731 faces as a help to recognize the following contexts: :table-special, :link,
18732 and :keyword."
18733 (let* ((f (get-text-property (point) 'face))
18734 (faces (if (listp f) f (list f)))
18735 (case-fold-search t)
18736 (p (point)) clist o)
18737 ;; First the large context
18738 (cond
18739 ((org-at-heading-p t)
18740 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18741 (when (progn
18742 (beginning-of-line 1)
18743 (looking-at org-todo-line-tags-regexp))
18744 (push (org-point-in-group p 1 :headline-stars) clist)
18745 (push (org-point-in-group p 2 :todo-keyword) clist)
18746 (push (org-point-in-group p 4 :tags) clist))
18747 (goto-char p)
18748 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18749 (when (looking-at "\\[#[A-Z0-9]\\]")
18750 (push (org-point-in-group p 0 :priority) clist)))
18752 ((org-at-item-p)
18753 (push (org-point-in-group p 2 :item-bullet) clist)
18754 (push (list :item (point-at-bol)
18755 (save-excursion (org-end-of-item) (point)))
18756 clist)
18757 (and (org-at-item-checkbox-p)
18758 (push (org-point-in-group p 0 :checkbox) clist)))
18760 ((org-at-table-p)
18761 (push (list :table (org-table-begin) (org-table-end)) clist)
18762 (when (memq 'org-formula faces)
18763 (push (list :table-special
18764 (previous-single-property-change p 'face)
18765 (next-single-property-change p 'face)) clist)))
18766 ((org-at-table-p 'any)
18767 (push (list :table-table) clist)))
18768 (goto-char p)
18770 (let ((case-fold-search t))
18771 ;; New the "medium" contexts: clocktables, source blocks
18772 (cond ((org-in-clocktable-p)
18773 (push (list :clocktable
18774 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
18775 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
18776 (match-beginning 1))
18777 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
18778 (match-end 0))) clist))
18779 ((org-in-src-block-p)
18780 (push (list :src-block
18781 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
18782 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
18783 (match-beginning 1))
18784 (and (search-forward "#+END_SRC" nil t)
18785 (match-beginning 0))) clist))))
18786 (goto-char p)
18788 ;; Now the small context
18789 (cond
18790 ((org-at-timestamp-p)
18791 (push (org-point-in-group p 0 :timestamp) clist))
18792 ((memq 'org-link faces)
18793 (push (list :link
18794 (previous-single-property-change p 'face)
18795 (next-single-property-change p 'face)) clist))
18796 ((memq 'org-special-keyword faces)
18797 (push (list :keyword
18798 (previous-single-property-change p 'face)
18799 (next-single-property-change p 'face)) clist))
18800 ((setq o (cl-some
18801 (lambda (o)
18802 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
18804 (overlays-at (point))))
18805 (push (list :latex-fragment
18806 (overlay-start o) (overlay-end o)) clist)
18807 (push (list :latex-preview
18808 (overlay-start o) (overlay-end o)) clist))
18809 ((org-inside-LaTeX-fragment-p)
18810 ;; FIXME: positions wrong.
18811 (push (list :latex-fragment (point) (point)) clist)))
18813 (setq clist (nreverse (delq nil clist)))
18814 clist))
18816 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
18817 "Non-nil when point is between matches of START-RE and END-RE.
18819 Also return a non-nil value when point is on one of the matches.
18821 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
18822 buffer positions. Default values are the positions of headlines
18823 surrounding the point.
18825 The functions returns a cons cell whose car (resp. cdr) is the
18826 position before START-RE (resp. after END-RE)."
18827 (save-match-data
18828 (let ((pos (point))
18829 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
18830 (limit-down (or lim-down (save-excursion (outline-next-heading))))
18831 beg end)
18832 (save-excursion
18833 ;; Point is on a block when on START-RE or if START-RE can be
18834 ;; found before it...
18835 (and (or (org-in-regexp start-re)
18836 (re-search-backward start-re limit-up t))
18837 (setq beg (match-beginning 0))
18838 ;; ... and END-RE after it...
18839 (goto-char (match-end 0))
18840 (re-search-forward end-re limit-down t)
18841 (> (setq end (match-end 0)) pos)
18842 ;; ... without another START-RE in-between.
18843 (goto-char (match-beginning 0))
18844 (not (re-search-backward start-re (1+ beg) t))
18845 ;; Return value.
18846 (cons beg end))))))
18848 (defun org-in-block-p (names)
18849 "Non-nil when point belongs to a block whose name belongs to NAMES.
18851 NAMES is a list of strings containing names of blocks.
18853 Return first block name matched, or nil. Beware that in case of
18854 nested blocks, the returned name may not belong to the closest
18855 block from point."
18856 (save-match-data
18857 (catch 'exit
18858 (let ((case-fold-search t)
18859 (lim-up (save-excursion (outline-previous-heading)))
18860 (lim-down (save-excursion (outline-next-heading))))
18861 (dolist (name names)
18862 (let ((n (regexp-quote name)))
18863 (when (org-between-regexps-p
18864 (concat "^[ \t]*#\\+begin_" n)
18865 (concat "^[ \t]*#\\+end_" n)
18866 lim-up lim-down)
18867 (throw 'exit n)))))
18868 nil)))
18870 (defun org-occur-in-agenda-files (regexp &optional _nlines)
18871 "Call `multi-occur' with buffers for all agenda files."
18872 (interactive "sOrg-files matching: ")
18873 (let* ((files (org-agenda-files))
18874 (tnames (mapcar #'file-truename files))
18875 (extra org-agenda-text-search-extra-files))
18876 (when (eq (car extra) 'agenda-archives)
18877 (setq extra (cdr extra))
18878 (setq files (org-add-archive-files files)))
18879 (dolist (f extra)
18880 (unless (member (file-truename f) tnames)
18881 (unless (member f files) (setq files (append files (list f))))
18882 (setq tnames (append tnames (list (file-truename f))))))
18883 (multi-occur
18884 (mapcar (lambda (x)
18885 (with-current-buffer
18886 ;; FIXME: Why not just (find-file-noselect x)?
18887 ;; Is it to avoid the "revert buffer" prompt?
18888 (or (get-file-buffer x) (find-file-noselect x))
18889 (widen)
18890 (current-buffer)))
18891 files)
18892 regexp)))
18894 (add-hook 'occur-mode-find-occurrence-hook
18895 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
18897 (defun org-occur-link-in-agenda-files ()
18898 "Create a link and search for it in the agendas.
18899 The link is not stored in `org-stored-links', it is just created
18900 for the search purpose."
18901 (interactive)
18902 (let ((link (condition-case nil
18903 (org-store-link nil)
18904 (error "Unable to create a link to here"))))
18905 (org-occur-in-agenda-files (regexp-quote link))))
18907 (defun org-back-over-empty-lines ()
18908 "Move backwards over whitespace, to the beginning of the first empty line.
18909 Returns the number of empty lines passed."
18910 (let ((pos (point)))
18911 (if (cdr (assq 'heading org-blank-before-new-entry))
18912 (skip-chars-backward " \t\n\r")
18913 (unless (eobp)
18914 (forward-line -1)))
18915 (beginning-of-line 2)
18916 (goto-char (min (point) pos))
18917 (count-lines (point) pos)))
18919 ;;; TODO: Only called once, from ox-odt which should probably use
18920 ;;; org-export-inline-image-p or something.
18921 (defun org-file-image-p (file)
18922 "Return non-nil if FILE is an image."
18923 (save-match-data
18924 (string-match (image-file-name-regexp) file)))
18926 (defun org-get-cursor-date (&optional with-time)
18927 "Return the date at cursor in as a time.
18928 This works in the calendar and in the agenda, anywhere else it just
18929 returns the current time.
18930 If WITH-TIME is non-nil, returns the time of the event at point (in
18931 the agenda) or the current time of the day."
18932 (let (date day defd tp hod mod)
18933 (when with-time
18934 (setq tp (get-text-property (point) 'time))
18935 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
18936 (setq hod (string-to-number (match-string 1 tp))
18937 mod (string-to-number (match-string 2 tp))))
18938 (or tp (let ((now (decode-time)))
18939 (setq hod (nth 2 now)
18940 mod (nth 1 now)))))
18941 (cond
18942 ((eq major-mode 'calendar-mode)
18943 (setq date (calendar-cursor-to-date)
18944 defd (encode-time 0 (or mod 0) (or hod 0)
18945 (nth 1 date) (nth 0 date) (nth 2 date))))
18946 ((eq major-mode 'org-agenda-mode)
18947 (setq day (get-text-property (point) 'day))
18948 (when day
18949 (setq date (calendar-gregorian-from-absolute day)
18950 defd (encode-time 0 (or mod 0) (or hod 0)
18951 (nth 1 date) (nth 0 date) (nth 2 date))))))
18952 (or defd (current-time))))
18954 (defun org-mark-subtree (&optional up)
18955 "Mark the current subtree.
18956 This puts point at the start of the current subtree, and mark at
18957 the end. If a numeric prefix UP is given, move up into the
18958 hierarchy of headlines by UP levels before marking the subtree."
18959 (interactive "P")
18960 (org-with-limited-levels
18961 (cond ((org-at-heading-p) (beginning-of-line))
18962 ((org-before-first-heading-p) (user-error "Not in a subtree"))
18963 (t (outline-previous-visible-heading 1))))
18964 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
18965 (if (called-interactively-p 'any)
18966 (call-interactively 'org-mark-element)
18967 (org-mark-element)))
18969 ;;; Indentation
18971 (defvar org-element-greater-elements)
18972 (defun org--get-expected-indentation (element contentsp)
18973 "Expected indentation column for current line, according to ELEMENT.
18974 ELEMENT is an element containing point. CONTENTSP is non-nil
18975 when indentation is to be computed according to contents of
18976 ELEMENT."
18977 (let ((type (org-element-type element))
18978 (start (org-element-property :begin element))
18979 (post-affiliated (org-element-property :post-affiliated element)))
18980 (org-with-wide-buffer
18981 (cond
18982 (contentsp
18983 (cl-case type
18984 ((diary-sexp footnote-definition) 0)
18985 ((headline inlinetask nil)
18986 (if (not org-adapt-indentation) 0
18987 (let ((level (org-current-level)))
18988 (if level (1+ level) 0))))
18989 ((item plain-list) (org-list-item-body-column post-affiliated))
18991 (goto-char start)
18992 (current-indentation))))
18993 ((memq type '(headline inlinetask nil))
18994 (if (org-match-line "[ \t]*$")
18995 (org--get-expected-indentation element t)
18997 ((memq type '(diary-sexp footnote-definition)) 0)
18998 ;; First paragraph of a footnote definition or an item.
18999 ;; Indent like parent.
19000 ((< (line-beginning-position) start)
19001 (org--get-expected-indentation
19002 (org-element-property :parent element) t))
19003 ;; At first line: indent according to previous sibling, if any,
19004 ;; ignoring footnote definitions and inline tasks, or parent's
19005 ;; contents.
19006 ((= (line-beginning-position) start)
19007 (catch 'exit
19008 (while t
19009 (if (= (point-min) start) (throw 'exit 0)
19010 (goto-char (1- start))
19011 (let* ((previous (org-element-at-point))
19012 (parent previous))
19013 (while (and parent (<= (org-element-property :end parent) start))
19014 (setq previous parent
19015 parent (org-element-property :parent parent)))
19016 (cond
19017 ((not previous) (throw 'exit 0))
19018 ((> (org-element-property :end previous) start)
19019 (throw 'exit (org--get-expected-indentation previous t)))
19020 ((memq (org-element-type previous)
19021 '(footnote-definition inlinetask))
19022 (setq start (org-element-property :begin previous)))
19023 (t (goto-char (org-element-property :begin previous))
19024 (throw 'exit
19025 (if (bolp) (current-indentation)
19026 ;; At first paragraph in an item or
19027 ;; a footnote definition.
19028 (org--get-expected-indentation
19029 (org-element-property :parent previous) t))))))))))
19030 ;; Otherwise, move to the first non-blank line above.
19032 (beginning-of-line)
19033 (let ((pos (point)))
19034 (skip-chars-backward " \r\t\n")
19035 (cond
19036 ;; Two blank lines end a footnote definition or a plain
19037 ;; list. When we indent an empty line after them, the
19038 ;; containing list or footnote definition is over, so it
19039 ;; qualifies as a previous sibling. Therefore, we indent
19040 ;; like its first line.
19041 ((and (memq type '(footnote-definition plain-list))
19042 (> (count-lines (point) pos) 2))
19043 (goto-char start)
19044 (current-indentation))
19045 ;; Line above is the first one of a paragraph at the
19046 ;; beginning of an item or a footnote definition. Indent
19047 ;; like parent.
19048 ((< (line-beginning-position) start)
19049 (org--get-expected-indentation
19050 (org-element-property :parent element) t))
19051 ;; Line above is the beginning of an element, i.e., point
19052 ;; was originally on the blank lines between element's start
19053 ;; and contents.
19054 ((= (line-beginning-position) post-affiliated)
19055 (org--get-expected-indentation element t))
19056 ;; POS is after contents in a greater element. Indent like
19057 ;; the beginning of the element.
19058 ((and (memq type org-element-greater-elements)
19059 (let ((cend (org-element-property :contents-end element)))
19060 (and cend (<= cend pos))))
19061 ;; As a special case, if point is at the end of a footnote
19062 ;; definition or an item, indent like the very last element
19063 ;; within. If that last element is an item, indent like
19064 ;; its contents.
19065 (if (memq type '(footnote-definition item plain-list))
19066 (let ((last (org-element-at-point)))
19067 (goto-char pos)
19068 (org--get-expected-indentation
19069 last (eq (org-element-type last) 'item)))
19070 (goto-char start)
19071 (current-indentation)))
19072 ;; In any other case, indent like the current line.
19073 (t (current-indentation)))))))))
19075 (defun org--align-node-property ()
19076 "Align node property at point.
19077 Alignment is done according to `org-property-format', which see."
19078 (when (save-excursion
19079 (beginning-of-line)
19080 (looking-at org-property-re))
19081 (replace-match
19082 (concat (match-string 4)
19083 (org-trim
19084 (format org-property-format (match-string 1) (match-string 3))))
19085 t t)))
19087 (defun org-indent-line ()
19088 "Indent line depending on context.
19090 Indentation is done according to the following rules:
19092 - Footnote definitions, diary sexps, headlines and inline tasks
19093 have to start at column 0.
19095 - On the very first line of an element, consider, in order, the
19096 next rules until one matches:
19098 1. If there's a sibling element before, ignoring footnote
19099 definitions and inline tasks, indent like its first line.
19101 2. If element has a parent, indent like its contents. More
19102 precisely, if parent is an item, indent after the bullet.
19103 Else, indent like parent's first line.
19105 3. Otherwise, indent relatively to current level, if
19106 `org-adapt-indentation' is non-nil, or to left margin.
19108 - On a blank line at the end of an element, indent according to
19109 the type of the element. More precisely
19111 1. If element is a plain list, an item, or a footnote
19112 definition, indent like the very last element within.
19114 2. If element is a paragraph, indent like its last non blank
19115 line.
19117 3. Otherwise, indent like its very first line.
19119 - In the code part of a source block, use language major mode
19120 to indent current line if `org-src-tab-acts-natively' is
19121 non-nil. If it is nil, do nothing.
19123 - Otherwise, indent like the first non-blank line above.
19125 The function doesn't indent an item as it could break the whole
19126 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
19127 `\\[org-shiftmetaright]'.
19129 Also align node properties according to `org-property-format'."
19130 (interactive)
19131 (cond
19132 ((org-at-heading-p) 'noindent)
19134 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
19135 (type (org-element-type element)))
19136 (cond ((and (memq type '(plain-list item))
19137 (= (line-beginning-position)
19138 (org-element-property :post-affiliated element)))
19139 'noindent)
19140 ((and (eq type 'latex-environment)
19141 (>= (point) (org-element-property :post-affiliated element))
19142 (< (point) (org-with-wide-buffer
19143 (goto-char (org-element-property :end element))
19144 (skip-chars-backward " \r\t\n")
19145 (line-beginning-position 2))))
19146 'noindent)
19147 ((and (eq type 'src-block)
19148 org-src-tab-acts-natively
19149 (> (line-beginning-position)
19150 (org-element-property :post-affiliated element))
19151 (< (line-beginning-position)
19152 (org-with-wide-buffer
19153 (goto-char (org-element-property :end element))
19154 (skip-chars-backward " \r\t\n")
19155 (line-beginning-position))))
19156 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
19158 (let ((column (org--get-expected-indentation element nil)))
19159 ;; Preserve current column.
19160 (if (<= (current-column) (current-indentation))
19161 (indent-line-to column)
19162 (save-excursion (indent-line-to column))))
19163 ;; Align node property. Also preserve current column.
19164 (when (eq type 'node-property)
19165 (let ((column (current-column)))
19166 (org--align-node-property)
19167 (org-move-to-column column)))))))))
19169 (defun org-indent-region (start end)
19170 "Indent each non-blank line in the region.
19171 Called from a program, START and END specify the region to
19172 indent. The function will not indent contents of example blocks,
19173 verse blocks and export blocks as leading white spaces are
19174 assumed to be significant there."
19175 (interactive "r")
19176 (save-excursion
19177 (goto-char start)
19178 (skip-chars-forward " \r\t\n")
19179 (unless (eobp) (beginning-of-line))
19180 (let ((indent-to
19181 (lambda (ind pos)
19182 ;; Set IND as indentation for all lines between point and
19183 ;; POS. Blank lines are ignored. Leave point after POS
19184 ;; once done.
19185 (let ((limit (copy-marker pos)))
19186 (while (< (point) limit)
19187 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
19188 (forward-line))
19189 (set-marker limit nil))))
19190 (end (copy-marker end)))
19191 (while (< (point) end)
19192 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
19193 (let* ((element (org-element-at-point))
19194 (type (org-element-type element))
19195 (element-end (copy-marker (org-element-property :end element)))
19196 (ind (org--get-expected-indentation element nil)))
19197 (cond
19198 ;; Element indented as a single block. Example blocks
19199 ;; preserving indentation are a special case since the
19200 ;; "contents" must not be indented whereas the block
19201 ;; boundaries can.
19202 ((or (memq type '(export-block latex-environment))
19203 (and (eq type 'example-block)
19204 (not
19205 (or org-src-preserve-indentation
19206 (org-element-property :preserve-indent element)))))
19207 (let ((offset (- ind (current-indentation))))
19208 (unless (zerop offset)
19209 (indent-rigidly (org-element-property :begin element)
19210 (org-element-property :end element)
19211 offset)))
19212 (goto-char element-end))
19213 ;; Elements indented line wise. Be sure to exclude
19214 ;; example blocks (preserving indentation) and source
19215 ;; blocks from this category as they are treated
19216 ;; specially later.
19217 ((or (memq type '(paragraph table table-row))
19218 (not (or (org-element-property :contents-begin element)
19219 (memq type '(example-block src-block)))))
19220 (when (eq type 'node-property)
19221 (org--align-node-property)
19222 (beginning-of-line))
19223 (funcall indent-to ind (min element-end end)))
19224 ;; Elements consisting of three parts: before the
19225 ;; contents, the contents, and after the contents. The
19226 ;; contents are treated specially, according to the
19227 ;; element type, or not indented at all. Other parts are
19228 ;; indented as a single block.
19230 (let* ((post (copy-marker
19231 (org-element-property :post-affiliated element)))
19232 (cbeg
19233 (copy-marker
19234 (cond
19235 ((not (org-element-property :contents-begin element))
19236 ;; Fake contents for source blocks.
19237 (org-with-wide-buffer
19238 (goto-char post)
19239 (line-beginning-position 2)))
19240 ((memq type '(footnote-definition item plain-list))
19241 ;; Contents in these elements could start on
19242 ;; the same line as the beginning of the
19243 ;; element. Make sure we start indenting
19244 ;; from the second line.
19245 (org-with-wide-buffer
19246 (goto-char post)
19247 (end-of-line)
19248 (skip-chars-forward " \r\t\n")
19249 (if (eobp) (point) (line-beginning-position))))
19250 (t (org-element-property :contents-begin element)))))
19251 (cend (copy-marker
19252 (or (org-element-property :contents-end element)
19253 ;; Fake contents for source blocks.
19254 (org-with-wide-buffer
19255 (goto-char element-end)
19256 (skip-chars-backward " \r\t\n")
19257 (line-beginning-position)))
19258 t)))
19259 ;; Do not change items indentation individually as it
19260 ;; might break the list as a whole. On the other
19261 ;; hand, when at a plain list, indent it as a whole.
19262 (cond ((eq type 'plain-list)
19263 (let ((offset (- ind (current-indentation))))
19264 (unless (zerop offset)
19265 (indent-rigidly (org-element-property :begin element)
19266 (org-element-property :end element)
19267 offset))
19268 (goto-char cbeg)))
19269 ((eq type 'item) (goto-char cbeg))
19270 (t (funcall indent-to ind (min cbeg end))))
19271 (when (< (point) end)
19272 (cl-case type
19273 ((example-block verse-block))
19274 (src-block
19275 ;; In a source block, indent source code
19276 ;; according to language major mode, but only if
19277 ;; `org-src-tab-acts-natively' is non-nil.
19278 (when (and (< (point) end) org-src-tab-acts-natively)
19279 (ignore-errors
19280 (org-babel-do-in-edit-buffer
19281 (indent-region (point-min) (point-max))))))
19282 (t (org-indent-region (point) (min cend end))))
19283 (goto-char (min cend end))
19284 (when (< (point) end)
19285 (funcall indent-to ind (min element-end end))))
19286 (set-marker post nil)
19287 (set-marker cbeg nil)
19288 (set-marker cend nil))))
19289 (set-marker element-end nil))))
19290 (set-marker end nil))))
19292 (defun org-indent-drawer ()
19293 "Indent the drawer at point."
19294 (interactive)
19295 (unless (save-excursion
19296 (beginning-of-line)
19297 (looking-at-p org-drawer-regexp))
19298 (user-error "Not at a drawer"))
19299 (let ((element (org-element-at-point)))
19300 (unless (memq (org-element-type element) '(drawer property-drawer))
19301 (user-error "Not at a drawer"))
19302 (org-with-wide-buffer
19303 (org-indent-region (org-element-property :begin element)
19304 (org-element-property :end element))))
19305 (message "Drawer at point indented"))
19307 (defun org-indent-block ()
19308 "Indent the block at point."
19309 (interactive)
19310 (unless (save-excursion
19311 (beginning-of-line)
19312 (let ((case-fold-search t))
19313 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
19314 (user-error "Not at a block"))
19315 (let ((element (org-element-at-point)))
19316 (unless (memq (org-element-type element)
19317 '(comment-block center-block dynamic-block example-block
19318 export-block quote-block special-block
19319 src-block verse-block))
19320 (user-error "Not at a block"))
19321 (org-with-wide-buffer
19322 (org-indent-region (org-element-property :begin element)
19323 (org-element-property :end element))))
19324 (message "Block at point indented"))
19327 ;;; Filling
19329 ;; We use our own fill-paragraph and auto-fill functions.
19331 ;; `org-fill-paragraph' relies on adaptive filling and context
19332 ;; checking. Appropriate `fill-prefix' is computed with
19333 ;; `org-adaptive-fill-function'.
19335 ;; `org-auto-fill-function' takes care of auto-filling. It calls
19336 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
19337 ;; `org-adaptive-fill-function' value. Internally,
19338 ;; `org-comment-line-break-function' breaks the line.
19340 ;; `org-setup-filling' installs filling and auto-filling related
19341 ;; variables during `org-mode' initialization.
19343 (defun org-setup-filling ()
19344 (require 'org-element)
19345 ;; Prevent auto-fill from inserting unwanted new items.
19346 (when (boundp 'fill-nobreak-predicate)
19347 (setq-local
19348 fill-nobreak-predicate
19349 (org-uniquify
19350 (append fill-nobreak-predicate
19351 '(org-fill-line-break-nobreak-p
19352 org-fill-n-macro-as-item-nobreak-p
19353 org-fill-paragraph-with-timestamp-nobreak-p)))))
19354 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
19355 (setq-local paragraph-start paragraph-ending)
19356 (setq-local paragraph-separate paragraph-ending))
19357 (setq-local fill-paragraph-function 'org-fill-paragraph)
19358 (setq-local auto-fill-inhibit-regexp nil)
19359 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
19360 (setq-local normal-auto-fill-function 'org-auto-fill-function)
19361 (setq-local comment-line-break-function 'org-comment-line-break-function))
19363 (defun org-fill-line-break-nobreak-p ()
19364 "Non-nil when a new line at point would create an Org line break."
19365 (save-excursion
19366 (skip-chars-backward "[ \t]")
19367 (skip-chars-backward "\\\\")
19368 (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
19370 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
19371 "Non-nil when a new line at point would split a timestamp."
19372 (and (org-at-timestamp-p 'lax)
19373 (not (looking-at org-ts-regexp-both))))
19375 (defun org-fill-n-macro-as-item-nobreak-p ()
19376 "Non-nil when a new line at point would create a new list."
19377 ;; During export, a "n" macro followed by a dot or a closing
19378 ;; parenthesis can end up being parsed as a new list item.
19379 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
19381 (defun org-adaptive-fill-function ()
19382 "Compute a fill prefix for the current line.
19383 Return fill prefix, as a string, or nil if current line isn't
19384 meant to be filled. For convenience, if `adaptive-fill-regexp'
19385 matches in paragraphs or comments, use it."
19386 (org-with-wide-buffer
19387 (unless (org-at-heading-p)
19388 (let* ((p (line-beginning-position))
19389 (element (save-excursion
19390 (beginning-of-line)
19391 (org-element-at-point)))
19392 (type (org-element-type element))
19393 (post-affiliated (org-element-property :post-affiliated element)))
19394 (unless (< p post-affiliated)
19395 (cl-case type
19396 (comment
19397 (save-excursion
19398 (beginning-of-line)
19399 (looking-at "[ \t]*")
19400 (concat (match-string 0) "# ")))
19401 (footnote-definition "")
19402 ((item plain-list)
19403 (make-string (org-list-item-body-column post-affiliated) ?\s))
19404 (paragraph
19405 ;; Fill prefix is usually the same as the current line,
19406 ;; unless the paragraph is at the beginning of an item.
19407 (let ((parent (org-element-property :parent element)))
19408 (save-excursion
19409 (beginning-of-line)
19410 (cond ((eq (org-element-type parent) 'item)
19411 (make-string (org-list-item-body-column
19412 (org-element-property :begin parent))
19413 ?\s))
19414 ((and adaptive-fill-regexp
19415 ;; Locally disable
19416 ;; `adaptive-fill-function' to let
19417 ;; `fill-context-prefix' handle
19418 ;; `adaptive-fill-regexp' variable.
19419 (let (adaptive-fill-function)
19420 (fill-context-prefix
19421 post-affiliated
19422 (org-element-property :end element)))))
19423 ((looking-at "[ \t]+") (match-string 0))
19424 (t "")))))
19425 (comment-block
19426 ;; Only fill contents if P is within block boundaries.
19427 (let* ((cbeg (save-excursion (goto-char post-affiliated)
19428 (forward-line)
19429 (point)))
19430 (cend (save-excursion
19431 (goto-char (org-element-property :end element))
19432 (skip-chars-backward " \r\t\n")
19433 (line-beginning-position))))
19434 (when (and (>= p cbeg) (< p cend))
19435 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
19436 (match-string 0)
19437 ""))))))))))
19439 (defun org-fill-element (&optional justify)
19440 "Fill element at point, when applicable.
19442 This function only applies to comment blocks, comments, example
19443 blocks and paragraphs. Also, as a special case, re-align table
19444 when point is at one.
19446 If JUSTIFY is non-nil (interactively, with prefix argument),
19447 justify as well. If `sentence-end-double-space' is non-nil, then
19448 period followed by one space does not end a sentence, so don't
19449 break a line there. The variable `fill-column' controls the
19450 width for filling.
19452 For convenience, when point is at a plain list, an item or
19453 a footnote definition, try to fill the first paragraph within."
19454 (with-syntax-table org-mode-transpose-word-syntax-table
19455 ;; Move to end of line in order to get the first paragraph within
19456 ;; a plain list or a footnote definition.
19457 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
19458 ;; First check if point is in a blank line at the beginning of
19459 ;; the buffer. In that case, ignore filling.
19460 (cl-case (org-element-type element)
19461 ;; Use major mode filling function is source blocks.
19462 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
19463 ;; Align Org tables, leave table.el tables as-is.
19464 (table-row (org-table-align) t)
19465 (table
19466 (when (eq (org-element-property :type element) 'org)
19467 (save-excursion
19468 (goto-char (org-element-property :post-affiliated element))
19469 (org-table-align)))
19471 (paragraph
19472 ;; Paragraphs may contain `line-break' type objects.
19473 (let ((beg (max (point-min)
19474 (org-element-property :contents-begin element)))
19475 (end (min (point-max)
19476 (org-element-property :contents-end element))))
19477 ;; Do nothing if point is at an affiliated keyword.
19478 (if (< (line-end-position) beg) t
19479 ;; Fill paragraph, taking line breaks into account.
19480 (save-excursion
19481 (goto-char beg)
19482 (let ((cuts (list beg)))
19483 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
19484 (when (eq 'line-break
19485 (org-element-type
19486 (save-excursion (backward-char)
19487 (org-element-context))))
19488 (push (point) cuts)))
19489 (dolist (c (delq end cuts))
19490 (fill-region-as-paragraph c end justify)
19491 (setq end c))))
19492 t)))
19493 ;; Contents of `comment-block' type elements should be
19494 ;; filled as plain text, but only if point is within block
19495 ;; markers.
19496 (comment-block
19497 (let* ((case-fold-search t)
19498 (beg (save-excursion
19499 (goto-char (org-element-property :begin element))
19500 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
19501 (forward-line)
19502 (point)))
19503 (end (save-excursion
19504 (goto-char (org-element-property :end element))
19505 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
19506 (line-beginning-position))))
19507 (if (or (< (point) beg) (> (point) end)) t
19508 (fill-region-as-paragraph
19509 (save-excursion (end-of-line)
19510 (re-search-backward "^[ \t]*$" beg 'move)
19511 (line-beginning-position))
19512 (save-excursion (beginning-of-line)
19513 (re-search-forward "^[ \t]*$" end 'move)
19514 (line-beginning-position))
19515 justify))))
19516 ;; Fill comments.
19517 (comment
19518 (let ((begin (org-element-property :post-affiliated element))
19519 (end (org-element-property :end element)))
19520 (when (and (>= (point) begin) (<= (point) end))
19521 (let ((begin (save-excursion
19522 (end-of-line)
19523 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
19524 (progn (forward-line) (point))
19525 begin)))
19526 (end (save-excursion
19527 (end-of-line)
19528 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
19529 (1- (line-beginning-position))
19530 (skip-chars-backward " \r\t\n")
19531 (line-end-position)))))
19532 ;; Do not fill comments when at a blank line.
19533 (when (> end begin)
19534 (let ((fill-prefix
19535 (save-excursion
19536 (beginning-of-line)
19537 (looking-at "[ \t]*#")
19538 (let ((comment-prefix (match-string 0)))
19539 (goto-char (match-end 0))
19540 (if (looking-at adaptive-fill-regexp)
19541 (concat comment-prefix (match-string 0))
19542 (concat comment-prefix " "))))))
19543 (save-excursion
19544 (fill-region-as-paragraph begin end justify))))))
19546 ;; Ignore every other element.
19547 (otherwise t)))))
19549 (defun org-fill-paragraph (&optional justify region)
19550 "Fill element at point, when applicable.
19552 This function only applies to comment blocks, comments, example
19553 blocks and paragraphs. Also, as a special case, re-align table
19554 when point is at one.
19556 For convenience, when point is at a plain list, an item or
19557 a footnote definition, try to fill the first paragraph within.
19559 If JUSTIFY is non-nil (interactively, with prefix argument),
19560 justify as well. If `sentence-end-double-space' is non-nil, then
19561 period followed by one space does not end a sentence, so don't
19562 break a line there. The variable `fill-column' controls the
19563 width for filling.
19565 The REGION argument is non-nil if called interactively; in that
19566 case, if Transient Mark mode is enabled and the mark is active,
19567 fill each of the elements in the active region, instead of just
19568 filling the current element."
19569 (interactive (progn
19570 (barf-if-buffer-read-only)
19571 (list (when current-prefix-arg 'full) t)))
19572 (let ((hash (and (not (buffer-modified-p))
19573 (org-buffer-hash))))
19574 (cond
19575 ((and region transient-mark-mode mark-active
19576 (not (eq (region-beginning) (region-end))))
19577 (let ((origin (point-marker))
19578 (start (region-beginning)))
19579 (unwind-protect
19580 (progn
19581 (goto-char (region-end))
19582 (while (> (point) start)
19583 (org-backward-paragraph)
19584 (org-fill-element justify)))
19585 (goto-char origin)
19586 (set-marker origin nil))))
19587 (t (org-fill-element justify)))
19588 ;; If we didn't change anything in the buffer (and the buffer was
19589 ;; previously unmodified), then flip the modification status back
19590 ;; to "unchanged".
19591 (when (and hash (equal hash (org-buffer-hash)))
19592 (set-buffer-modified-p nil))))
19594 (defun org-auto-fill-function ()
19595 "Auto-fill function."
19596 ;; Check if auto-filling is meaningful.
19597 (let ((fc (current-fill-column)))
19598 (when (and fc (> (current-column) fc))
19599 (let* ((fill-prefix (org-adaptive-fill-function))
19600 ;; Enforce empty fill prefix, if required. Otherwise, it
19601 ;; will be computed again.
19602 (adaptive-fill-mode (not (equal fill-prefix ""))))
19603 (when fill-prefix (do-auto-fill))))))
19605 (defun org-comment-line-break-function (&optional soft)
19606 "Break line at point and indent, continuing comment if within one.
19607 The inserted newline is marked hard if variable
19608 `use-hard-newlines' is true, unless optional argument SOFT is
19609 non-nil."
19610 (if soft (insert-and-inherit ?\n) (newline 1))
19611 (save-excursion (forward-char -1) (delete-horizontal-space))
19612 (delete-horizontal-space)
19613 (indent-to-left-margin)
19614 (insert-before-markers-and-inherit fill-prefix))
19617 ;;; Fixed Width Areas
19619 (defun org-toggle-fixed-width ()
19620 "Toggle fixed-width markup.
19622 Add or remove fixed-width markup on current line, whenever it
19623 makes sense. Return an error otherwise.
19625 If a region is active and if it contains only fixed-width areas
19626 or blank lines, remove all fixed-width markup in it. If the
19627 region contains anything else, convert all non-fixed-width lines
19628 to fixed-width ones.
19630 Blank lines at the end of the region are ignored unless the
19631 region only contains such lines."
19632 (interactive)
19633 (if (not (org-region-active-p))
19634 ;; No region:
19636 ;; Remove fixed width marker only in a fixed-with element.
19638 ;; Add fixed width maker in paragraphs, in blank lines after
19639 ;; elements or at the beginning of a headline or an inlinetask,
19640 ;; and before any one-line elements (e.g., a clock).
19641 (progn
19642 (beginning-of-line)
19643 (let* ((element (org-element-at-point))
19644 (type (org-element-type element)))
19645 (cond
19646 ((and (eq type 'fixed-width)
19647 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
19648 (replace-match
19649 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
19650 ((and (memq type '(babel-call clock comment diary-sexp headline
19651 horizontal-rule keyword paragraph
19652 planning))
19653 (<= (org-element-property :post-affiliated element) (point)))
19654 (skip-chars-forward " \t")
19655 (insert ": "))
19656 ((and (looking-at-p "[ \t]*$")
19657 (or (eq type 'inlinetask)
19658 (save-excursion
19659 (skip-chars-forward " \r\t\n")
19660 (<= (org-element-property :end element) (point)))))
19661 (delete-region (point) (line-end-position))
19662 (org-indent-line)
19663 (insert ": "))
19664 (t (user-error "Cannot insert a fixed-width line here")))))
19665 ;; Region active.
19666 (let* ((begin (save-excursion
19667 (goto-char (region-beginning))
19668 (line-beginning-position)))
19669 (end (copy-marker
19670 (save-excursion
19671 (goto-char (region-end))
19672 (unless (eolp) (beginning-of-line))
19673 (if (save-excursion (re-search-backward "\\S-" begin t))
19674 (progn (skip-chars-backward " \r\t\n") (point))
19675 (point)))))
19676 (all-fixed-width-p
19677 (catch 'not-all-p
19678 (save-excursion
19679 (goto-char begin)
19680 (skip-chars-forward " \r\t\n")
19681 (when (eobp) (throw 'not-all-p nil))
19682 (while (< (point) end)
19683 (let ((element (org-element-at-point)))
19684 (if (eq (org-element-type element) 'fixed-width)
19685 (goto-char (org-element-property :end element))
19686 (throw 'not-all-p nil))))
19687 t))))
19688 (if all-fixed-width-p
19689 (save-excursion
19690 (goto-char begin)
19691 (while (< (point) end)
19692 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
19693 (replace-match
19694 "" nil nil nil
19695 (if (= (line-end-position) (match-end 0)) 0 1)))
19696 (forward-line)))
19697 (let ((min-ind (point-max)))
19698 ;; Find minimum indentation across all lines.
19699 (save-excursion
19700 (goto-char begin)
19701 (if (not (save-excursion (re-search-forward "\\S-" end t)))
19702 (setq min-ind 0)
19703 (catch 'zerop
19704 (while (< (point) end)
19705 (unless (looking-at-p "[ \t]*$")
19706 (let ((ind (current-indentation)))
19707 (setq min-ind (min min-ind ind))
19708 (when (zerop ind) (throw 'zerop t))))
19709 (forward-line)))))
19710 ;; Loop over all lines and add fixed-width markup everywhere
19711 ;; but in fixed-width lines.
19712 (save-excursion
19713 (goto-char begin)
19714 (while (< (point) end)
19715 (cond
19716 ((org-at-heading-p)
19717 (insert ": ")
19718 (forward-line)
19719 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
19720 (insert ":")
19721 (forward-line)))
19722 ((looking-at-p "[ \t]*:\\( \\|$\\)")
19723 (let* ((element (org-element-at-point))
19724 (element-end (org-element-property :end element)))
19725 (if (eq (org-element-type element) 'fixed-width)
19726 (progn (goto-char element-end)
19727 (skip-chars-backward " \r\t\n")
19728 (forward-line))
19729 (let ((limit (min end element-end)))
19730 (while (< (point) limit)
19731 (org-move-to-column min-ind t)
19732 (insert ": ")
19733 (forward-line))))))
19735 (org-move-to-column min-ind t)
19736 (insert ": ")
19737 (forward-line)))))))
19738 (set-marker end nil))))
19741 ;;; Blocks
19743 (defun org-block-map (function &optional start end)
19744 "Call FUNCTION at the head of all source blocks in the current buffer.
19745 Optional arguments START and END can be used to limit the range."
19746 (let ((start (or start (point-min)))
19747 (end (or end (point-max))))
19748 (save-excursion
19749 (goto-char start)
19750 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
19751 (save-excursion
19752 (save-match-data
19753 (goto-char (match-beginning 0))
19754 (funcall function)))))))
19756 (defun org-next-block (arg &optional backward block-regexp)
19757 "Jump to the next block.
19759 With a prefix argument ARG, jump forward ARG many blocks.
19761 When BACKWARD is non-nil, jump to the previous block.
19763 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
19764 Match data is set according to this regexp when the function
19765 returns.
19767 Return point at beginning of the opening line of found block.
19768 Throw an error if no block is found."
19769 (interactive "p")
19770 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
19771 (case-fold-search t)
19772 (search-fn (if backward #'re-search-backward #'re-search-forward))
19773 (count (or arg 1))
19774 (origin (point))
19775 last-element)
19776 (if backward (beginning-of-line) (end-of-line))
19777 (while (and (> count 0) (funcall search-fn re nil t))
19778 (let ((element (save-excursion
19779 (goto-char (match-beginning 0))
19780 (save-match-data (org-element-at-point)))))
19781 (when (and (memq (org-element-type element)
19782 '(center-block comment-block dynamic-block
19783 example-block export-block quote-block
19784 special-block src-block verse-block))
19785 (<= (match-beginning 0)
19786 (org-element-property :post-affiliated element)))
19787 (setq last-element element)
19788 (cl-decf count))))
19789 (if (= count 0)
19790 (prog1 (goto-char (org-element-property :post-affiliated last-element))
19791 (save-match-data (org-show-context)))
19792 (goto-char origin)
19793 (user-error "No %s code blocks" (if backward "previous" "further")))))
19795 (defun org-previous-block (arg &optional block-regexp)
19796 "Jump to the previous block.
19797 With a prefix argument ARG, jump backward ARG many source blocks.
19798 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
19799 (interactive "p")
19800 (org-next-block arg t block-regexp))
19803 ;;; Comments
19805 ;; Org comments syntax is quite complex. It requires the entire line
19806 ;; to be just a comment. Also, even with the right syntax at the
19807 ;; beginning of line, some elements (e.g., verse-block or
19808 ;; example-block) don't accept comments. Usual Emacs comment commands
19809 ;; cannot cope with those requirements. Therefore, Org replaces them.
19811 ;; Org still relies on `comment-dwim', but cannot trust
19812 ;; `comment-only-p'. So, `comment-region-function' and
19813 ;; `uncomment-region-function' both point
19814 ;; to`org-comment-or-uncomment-region'. Eventually,
19815 ;; `org-insert-comment' takes care of insertion of comments at the
19816 ;; beginning of line.
19818 ;; `org-setup-comments-handling' install comments related variables
19819 ;; during `org-mode' initialization.
19821 (defun org-setup-comments-handling ()
19822 (interactive)
19823 (setq-local comment-use-syntax nil)
19824 (setq-local comment-start "# ")
19825 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
19826 (setq-local comment-insert-comment-function 'org-insert-comment)
19827 (setq-local comment-region-function 'org-comment-or-uncomment-region)
19828 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
19830 (defun org-insert-comment ()
19831 "Insert an empty comment above current line.
19832 If the line is empty, insert comment at its beginning. When
19833 point is within a source block, comment according to the related
19834 major mode."
19835 (if (let ((element (org-element-at-point)))
19836 (and (eq (org-element-type element) 'src-block)
19837 (< (save-excursion
19838 (goto-char (org-element-property :post-affiliated element))
19839 (line-end-position))
19840 (point))
19841 (> (save-excursion
19842 (goto-char (org-element-property :end element))
19843 (skip-chars-backward " \r\t\n")
19844 (line-beginning-position))
19845 (point))))
19846 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
19847 (beginning-of-line)
19848 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
19849 (open-line 1))
19850 (org-indent-line)
19851 (insert "# ")))
19853 (defvar comment-empty-lines) ; From newcomment.el.
19854 (defun org-comment-or-uncomment-region (beg end &rest _)
19855 "Comment or uncomment each non-blank line in the region.
19856 Uncomment each non-blank line between BEG and END if it only
19857 contains commented lines. Otherwise, comment them. If region is
19858 strictly within a source block, use appropriate comment syntax."
19859 (if (let ((element (org-element-at-point)))
19860 (and (eq (org-element-type element) 'src-block)
19861 (< (save-excursion
19862 (goto-char (org-element-property :post-affiliated element))
19863 (line-end-position))
19864 beg)
19865 (>= (save-excursion
19866 (goto-char (org-element-property :end element))
19867 (skip-chars-backward " \r\t\n")
19868 (line-beginning-position))
19869 end)))
19870 ;; Translate region boundaries for the Org buffer to the source
19871 ;; buffer.
19872 (let ((offset (- end beg)))
19873 (save-excursion
19874 (goto-char beg)
19875 (org-babel-do-in-edit-buffer
19876 (comment-or-uncomment-region (point) (+ offset (point))))))
19877 (save-restriction
19878 ;; Restrict region
19879 (narrow-to-region (save-excursion (goto-char beg)
19880 (skip-chars-forward " \r\t\n" end)
19881 (line-beginning-position))
19882 (save-excursion (goto-char end)
19883 (skip-chars-backward " \r\t\n" beg)
19884 (line-end-position)))
19885 (let ((uncommentp
19886 ;; UNCOMMENTP is non-nil when every non blank line between
19887 ;; BEG and END is a comment.
19888 (save-excursion
19889 (goto-char (point-min))
19890 (while (and (not (eobp))
19891 (let ((element (org-element-at-point)))
19892 (and (eq (org-element-type element) 'comment)
19893 (goto-char (min (point-max)
19894 (org-element-property
19895 :end element)))))))
19896 (eobp))))
19897 (if uncommentp
19898 ;; Only blank lines and comments in region: uncomment it.
19899 (save-excursion
19900 (goto-char (point-min))
19901 (while (not (eobp))
19902 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
19903 (replace-match "" nil nil nil 1))
19904 (forward-line)))
19905 ;; Comment each line in region.
19906 (let ((min-indent (point-max)))
19907 ;; First find the minimum indentation across all lines.
19908 (save-excursion
19909 (goto-char (point-min))
19910 (while (and (not (eobp)) (not (zerop min-indent)))
19911 (unless (looking-at "[ \t]*$")
19912 (setq min-indent (min min-indent (current-indentation))))
19913 (forward-line)))
19914 ;; Then loop over all lines.
19915 (save-excursion
19916 (goto-char (point-min))
19917 (while (not (eobp))
19918 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
19919 ;; Don't get fooled by invisible text (e.g. link path)
19920 ;; when moving to column MIN-INDENT.
19921 (let ((buffer-invisibility-spec nil))
19922 (org-move-to-column min-indent t))
19923 (insert comment-start))
19924 (forward-line)))))))))
19926 (defun org-comment-dwim (_arg)
19927 "Call the comment command you mean.
19928 Call `org-toggle-comment' if on a heading, otherwise call
19929 `comment-dwim', within a source edit buffer if needed."
19930 (interactive "*P")
19931 (cond ((org-at-heading-p)
19932 (call-interactively #'org-toggle-comment))
19933 ((org-in-src-block-p)
19934 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
19935 (t (call-interactively #'comment-dwim))))
19938 ;;; Timestamps API
19940 ;; This section contains tools to operate on, or create, timestamp
19941 ;; objects, as returned by, e.g. `org-element-context'.
19943 (defun org-timestamp-from-string (s)
19944 "Convert Org timestamp S, as a string, into a timestamp object.
19945 Return nil if S is not a valid timestamp string."
19946 (when (org-string-nw-p s)
19947 (with-temp-buffer
19948 (save-excursion (insert s))
19949 (org-element-timestamp-parser))))
19951 (defun org-timestamp-from-time (time &optional with-time inactive)
19952 "Convert a time value into a timestamp object.
19954 TIME is an Emacs internal time representation, as returned, e.g.,
19955 by `current-time'.
19957 When optional argument WITH-TIME is non-nil, return a timestamp
19958 object with a time part, i.e., with hours and minutes.
19960 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
19961 return an active timestamp."
19962 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
19963 (org-element-create 'timestamp
19964 (list :type (if inactive 'inactive 'active)
19965 :year-start year
19966 :month-start month
19967 :day-start day
19968 :hour-start (and with-time hour)
19969 :minute-start (and with-time minute)))))
19971 (defun org-timestamp-to-time (timestamp &optional end)
19972 "Convert TIMESTAMP object into an Emacs internal time value.
19973 Use end of date range or time range when END is non-nil.
19974 Otherwise, use its start."
19975 (apply #'encode-time
19976 (cons 0
19977 (mapcar
19978 (lambda (prop) (or (org-element-property prop timestamp) 0))
19979 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
19980 '(:minute-start :hour-start :day-start :month-start
19981 :year-start))))))
19983 (defun org-timestamp-has-time-p (timestamp)
19984 "Non-nil when TIMESTAMP has a time specified."
19985 (org-element-property :hour-start timestamp))
19987 (defun org-timestamp-format (timestamp format &optional end utc)
19988 "Format a TIMESTAMP object into a string.
19990 FORMAT is a format specifier to be passed to
19991 `format-time-string'.
19993 When optional argument END is non-nil, use end of date-range or
19994 time-range, if possible.
19996 When optional argument UTC is non-nil, time is be expressed as
19997 Universal Time."
19998 (format-time-string format (org-timestamp-to-time timestamp end)
19999 (and utc t)))
20001 (defun org-timestamp-split-range (timestamp &optional end)
20002 "Extract a TIMESTAMP object from a date or time range.
20004 END, when non-nil, means extract the end of the range.
20005 Otherwise, extract its start.
20007 Return a new timestamp object."
20008 (let ((type (org-element-property :type timestamp)))
20009 (if (memq type '(active inactive diary)) timestamp
20010 (let ((split-ts (org-element-copy timestamp)))
20011 ;; Set new type.
20012 (org-element-put-property
20013 split-ts :type (if (eq type 'active-range) 'active 'inactive))
20014 ;; Copy start properties over end properties if END is
20015 ;; non-nil. Otherwise, copy end properties over `start' ones.
20016 (let ((p-alist '((:minute-start . :minute-end)
20017 (:hour-start . :hour-end)
20018 (:day-start . :day-end)
20019 (:month-start . :month-end)
20020 (:year-start . :year-end))))
20021 (dolist (p-cell p-alist)
20022 (org-element-put-property
20023 split-ts
20024 (funcall (if end #'car #'cdr) p-cell)
20025 (org-element-property
20026 (funcall (if end #'cdr #'car) p-cell) split-ts)))
20027 ;; Eventually refresh `:raw-value'.
20028 (org-element-put-property split-ts :raw-value nil)
20029 (org-element-put-property
20030 split-ts :raw-value (org-element-interpret-data split-ts)))))))
20032 (defun org-timestamp-translate (timestamp &optional boundary)
20033 "Translate TIMESTAMP object to custom format.
20035 Format string is defined in `org-time-stamp-custom-formats',
20036 which see.
20038 When optional argument BOUNDARY is non-nil, it is either the
20039 symbol `start' or `end'. In this case, only translate the
20040 starting or ending part of TIMESTAMP if it is a date or time
20041 range. Otherwise, translate both parts.
20043 Return timestamp as-is if `org-display-custom-times' is nil or if
20044 it has a `diary' type."
20045 (let ((type (org-element-property :type timestamp)))
20046 (if (or (not org-display-custom-times) (eq type 'diary))
20047 (org-element-interpret-data timestamp)
20048 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
20049 org-time-stamp-custom-formats)))
20050 (if (and (not boundary) (memq type '(active-range inactive-range)))
20051 (concat (org-timestamp-format timestamp fmt)
20052 "--"
20053 (org-timestamp-format timestamp fmt t))
20054 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
20056 ;;; Other stuff
20058 (defvar reftex-docstruct-symbol)
20059 (defvar org--rds)
20061 (defun org-reftex-citation ()
20062 "Use reftex-citation to insert a citation into the buffer.
20063 This looks for a line like
20065 #+BIBLIOGRAPHY: foo plain option:-d
20067 and derives from it that foo.bib is the bibliography file relevant
20068 for this document. It then installs the necessary environment for RefTeX
20069 to work in this buffer and calls `reftex-citation' to insert a citation
20070 into the buffer.
20072 Export of such citations to both LaTeX and HTML is handled by the contributed
20073 package ox-bibtex by Taru Karttunen."
20074 (interactive)
20075 (let ((reftex-docstruct-symbol 'org--rds)
20076 org--rds bib)
20077 (org-with-wide-buffer
20078 (let ((case-fold-search t)
20079 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
20080 (if (not (save-excursion
20081 (or (re-search-forward re nil t)
20082 (re-search-backward re nil t))))
20083 (user-error "No bibliography defined in file")
20084 (setq bib (concat (match-string 1) ".bib")
20085 org--rds (list (list 'bib bib))))))
20086 (call-interactively 'reftex-citation)))
20088 ;;;; Functions extending outline functionality
20090 (defun org-beginning-of-line (&optional n)
20091 "Go to the beginning of the current visible line.
20093 If this is a headline, and `org-special-ctrl-a/e' is not nil or
20094 symbol `reversed', on the first attempt move to where the
20095 headline text starts, and only move to beginning of line when the
20096 cursor is already before the start of the text of the headline.
20098 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
20099 start of the text on the second attempt.
20101 With argument N not nil or 1, move forward N - 1 lines first."
20102 (interactive "^p")
20103 (let ((origin (point))
20104 (special (pcase org-special-ctrl-a/e
20105 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
20106 deactivate-mark)
20107 ;; First move to a visible line.
20108 (if (bound-and-true-p visual-line-mode)
20109 (beginning-of-visual-line n)
20110 (move-beginning-of-line n)
20111 ;; `move-beginning-of-line' may leave point after invisible
20112 ;; characters if line starts with such of these (e.g., with
20113 ;; a link at column 0). Really move to the beginning of the
20114 ;; current visible line.
20115 (beginning-of-line))
20116 (cond
20117 ;; No special behavior. Point is already at the beginning of
20118 ;; a line, logical or visual.
20119 ((not special))
20120 ;; `beginning-of-visual-line' left point before logical beginning
20121 ;; of line: point is at the beginning of a visual line. Bail
20122 ;; out.
20123 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
20124 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
20125 ;; At a headline, special position is before the title, but
20126 ;; after any TODO keyword or priority cookie.
20127 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20128 (line-end-position)))
20129 (bol (point)))
20130 (if (eq special 'reversed)
20131 (when (and (= origin bol) (eq last-command this-command))
20132 (goto-char refpos))
20133 (when (or (> origin refpos) (= origin bol))
20134 (goto-char refpos)))))
20135 ((and (looking-at org-list-full-item-re)
20136 (memq (org-element-type (save-match-data (org-element-at-point)))
20137 '(item plain-list)))
20138 ;; Set special position at first white space character after
20139 ;; bullet, and check-box, if any.
20140 (let ((after-bullet
20141 (let ((box (match-end 3)))
20142 (cond ((not box) (match-end 1))
20143 ((eq (char-after box) ?\s) (1+ box))
20144 (t box)))))
20145 (if (eq special 'reversed)
20146 (when (and (= (point) origin) (eq last-command this-command))
20147 (goto-char after-bullet))
20148 (when (or (> origin after-bullet) (= (point) origin))
20149 (goto-char after-bullet)))))
20150 ;; No special context. Point is already at beginning of line.
20151 (t nil))))
20153 (defun org-end-of-line (&optional n)
20154 "Go to the end of the line, but before ellipsis, if any.
20156 If this is a headline, and `org-special-ctrl-a/e' is not nil or
20157 symbol `reversed', ignore tags on the first attempt, and only
20158 move to after the tags when the cursor is already beyond the end
20159 of the headline.
20161 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
20162 on the second attempt.
20164 With argument N not nil or 1, move forward N - 1 lines first."
20165 (interactive "^p")
20166 (let ((origin (point))
20167 (special (pcase org-special-ctrl-a/e
20168 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
20169 deactivate-mark)
20170 ;; First move to a visible line.
20171 (if (bound-and-true-p visual-line-mode)
20172 (beginning-of-visual-line n)
20173 (move-beginning-of-line n))
20174 (cond
20175 ;; At a headline, with tags.
20176 ((and special
20177 (save-excursion
20178 (beginning-of-line)
20179 (let ((case-fold-search nil))
20180 (looking-at org-complex-heading-regexp)))
20181 (match-end 5))
20182 (let ((tags (save-excursion
20183 (goto-char (match-beginning 5))
20184 (skip-chars-backward " \t")
20185 (point)))
20186 (visual-end (and (bound-and-true-p visual-line-mode)
20187 (save-excursion
20188 (end-of-visual-line)
20189 (point)))))
20190 ;; If `end-of-visual-line' brings us before end of line or
20191 ;; even tags, i.e., the headline spans over multiple visual
20192 ;; lines, move there.
20193 (cond ((and visual-end
20194 (< visual-end tags)
20195 (<= origin visual-end))
20196 (goto-char visual-end))
20197 ((eq special 'reversed)
20198 (if (and (= origin (line-end-position))
20199 (eq this-command last-command))
20200 (goto-char tags)
20201 (end-of-line)))
20203 (if (or (< origin tags) (= origin (line-end-position)))
20204 (goto-char tags)
20205 (end-of-line))))))
20206 ((bound-and-true-p visual-line-mode)
20207 (let ((bol (line-beginning-position)))
20208 (end-of-visual-line)
20209 ;; If `end-of-visual-line' gets us past the ellipsis at the
20210 ;; end of a line, backtrack and use `end-of-line' instead.
20211 (when (/= bol (line-beginning-position))
20212 (goto-char bol)
20213 (end-of-line))))
20214 (t (end-of-line)))))
20216 (defun org-backward-sentence (&optional _arg)
20217 "Go to beginning of sentence, or beginning of table field.
20218 This will call `backward-sentence' or `org-table-beginning-of-field',
20219 depending on context."
20220 (interactive)
20221 (let* ((element (org-element-at-point))
20222 (contents-begin (org-element-property :contents-begin element))
20223 (table (org-element-lineage element '(table) t)))
20224 (if (and table
20225 (> (point) contents-begin)
20226 (<= (point) (org-element-property :contents-end table)))
20227 (call-interactively #'org-table-beginning-of-field)
20228 (save-restriction
20229 (when (and contents-begin
20230 (< (point-min) contents-begin)
20231 (> (point) contents-begin))
20232 (narrow-to-region contents-begin
20233 (org-element-property :contents-end element)))
20234 (call-interactively #'backward-sentence)))))
20236 (defun org-forward-sentence (&optional _arg)
20237 "Go to end of sentence, or end of table field.
20238 This will call `forward-sentence' or `org-table-end-of-field',
20239 depending on context."
20240 (interactive)
20241 (if (and (org-at-heading-p)
20242 (save-restriction (skip-chars-forward " \t") (not (eolp))))
20243 (save-restriction
20244 (narrow-to-region (line-beginning-position) (line-end-position))
20245 (call-interactively #'forward-sentence))
20246 (let* ((element (org-element-at-point))
20247 (contents-end (org-element-property :contents-end element))
20248 (table (org-element-lineage element '(table) t)))
20249 (if (and table
20250 (>= (point) (org-element-property :contents-begin table))
20251 (< (point) contents-end))
20252 (call-interactively #'org-table-end-of-field)
20253 (save-restriction
20254 (when (and contents-end
20255 (> (point-max) contents-end)
20256 ;; Skip blank lines between elements.
20257 (< (org-element-property :end element)
20258 (save-excursion (goto-char contents-end)
20259 (skip-chars-forward " \r\t\n"))))
20260 (narrow-to-region (org-element-property :contents-begin element)
20261 contents-end))
20262 ;; End of heading is considered as the end of a sentence.
20263 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
20264 (call-interactively #'forward-sentence)))))))
20266 (defun org-kill-line (&optional _arg)
20267 "Kill line, to tags or end of line."
20268 (interactive)
20269 (cond
20270 ((or (not org-special-ctrl-k)
20271 (bolp)
20272 (not (org-at-heading-p)))
20273 (when (and (get-char-property (line-end-position) 'invisible)
20274 org-ctrl-k-protect-subtree
20275 (or (eq org-ctrl-k-protect-subtree 'error)
20276 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
20277 (user-error
20278 (substitute-command-keys
20279 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
20280 (call-interactively
20281 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
20282 ((org-match-line org-tag-line-re)
20283 (let ((end (save-excursion
20284 (goto-char (match-beginning 1))
20285 (skip-chars-backward " \t")
20286 (point))))
20287 (if (<= end (point)) ;on tags part
20288 (kill-region (point) (line-end-position))
20289 (kill-region (point) end)))
20290 (org-align-tags))
20291 (t (kill-region (point) (line-end-position)))))
20293 (defun org-yank (&optional arg)
20294 "Yank. If the kill is a subtree, treat it specially.
20295 This command will look at the current kill and check if is a single
20296 subtree, or a series of subtrees[1]. If it passes the test, and if the
20297 cursor is at the beginning of a line or after the stars of a currently
20298 empty headline, then the yank is handled specially. How exactly depends
20299 on the value of the following variables.
20301 `org-yank-folded-subtrees'
20302 By default, this variable is non-nil, which results in
20303 subtree(s) being folded after insertion, except if doing so
20304 would swallow text after the yanked text.
20306 `org-yank-adjusted-subtrees'
20307 When non-nil (the default value is nil), the subtree will be
20308 promoted or demoted in order to fit into the local outline tree
20309 structure, which means that the level will be adjusted so that it
20310 becomes the smaller one of the two *visible* surrounding headings.
20312 Any prefix to this command will cause `yank' to be called directly with
20313 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
20314 will just
20315 plainly yank the text as it is.
20317 \[1] The test checks if the first non-white line is a heading
20318 and if there are no other headings with fewer stars."
20319 (interactive "P")
20320 (org-yank-generic 'yank arg))
20322 (defun org-yank-generic (command arg)
20323 "Perform some yank-like command.
20325 This function implements the behavior described in the `org-yank'
20326 documentation. However, it has been generalized to work for any
20327 interactive command with similar behavior."
20329 ;; pretend to be command COMMAND
20330 (setq this-command command)
20332 (if arg
20333 (call-interactively command)
20335 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20336 (and (org-kill-is-subtree-p)
20337 (or (bolp)
20338 (and (looking-at "[ \t]*$")
20339 (string-match
20340 "\\`\\*+\\'"
20341 (buffer-substring (point-at-bol) (point)))))))
20342 swallowp)
20343 (cond
20344 ((and subtreep org-yank-folded-subtrees)
20345 (let ((beg (point))
20346 end)
20347 (if (and subtreep org-yank-adjusted-subtrees)
20348 (org-paste-subtree nil nil 'for-yank)
20349 (call-interactively command))
20351 (setq end (point))
20352 (goto-char beg)
20353 (when (and (bolp) subtreep
20354 (not (setq swallowp
20355 (org-yank-folding-would-swallow-text beg end))))
20356 (org-with-limited-levels
20357 (or (looking-at org-outline-regexp)
20358 (re-search-forward org-outline-regexp-bol end t))
20359 (while (and (< (point) end) (looking-at org-outline-regexp))
20360 (outline-hide-subtree)
20361 (org-cycle-show-empty-lines 'folded)
20362 (condition-case nil
20363 (outline-forward-same-level 1)
20364 (error (goto-char end))))))
20365 (when swallowp
20366 (message
20367 "Inserted text not folded because that would swallow text"))
20369 (goto-char end)
20370 (skip-chars-forward " \t\n\r")
20371 (beginning-of-line 1)
20372 (push-mark beg 'nomsg)))
20373 ((and subtreep org-yank-adjusted-subtrees)
20374 (let ((beg (point-at-bol)))
20375 (org-paste-subtree nil nil 'for-yank)
20376 (push-mark beg 'nomsg)))
20378 (call-interactively command))))))
20380 (defun org-yank-folding-would-swallow-text (beg end)
20381 "Would hide-subtree at BEG swallow any text after END?"
20382 (let (level)
20383 (org-with-limited-levels
20384 (save-excursion
20385 (goto-char beg)
20386 (when (or (looking-at org-outline-regexp)
20387 (re-search-forward org-outline-regexp-bol end t))
20388 (setq level (org-outline-level)))
20389 (goto-char end)
20390 (skip-chars-forward " \t\r\n\v\f")
20391 (not (or (eobp)
20392 (and (bolp) (looking-at-p org-outline-regexp)
20393 (<= (org-outline-level) level))))))))
20395 (defun org-back-to-heading (&optional invisible-ok)
20396 "Call `outline-back-to-heading', but provide a better error message."
20397 (condition-case nil
20398 (outline-back-to-heading invisible-ok)
20399 (error (error "Before first headline at position %d in buffer %s"
20400 (point) (current-buffer)))))
20402 (defun org-before-first-heading-p ()
20403 "Before first heading?"
20404 (org-with-limited-levels
20405 (save-excursion
20406 (end-of-line)
20407 (null (re-search-backward org-outline-regexp-bol nil t)))))
20409 (defun org-at-heading-p (&optional _)
20410 "Non-nil when on a headline."
20411 (outline-on-heading-p t))
20413 (defun org-in-commented-heading-p (&optional no-inheritance)
20414 "Non-nil if point is under a commented heading.
20415 This function also checks ancestors of the current headline,
20416 unless optional argument NO-INHERITANCE is non-nil."
20417 (cond
20418 ((org-before-first-heading-p) nil)
20419 ((let ((headline (nth 4 (org-heading-components))))
20420 (and headline
20421 (let ((case-fold-search nil))
20422 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
20423 headline)))))
20424 (no-inheritance nil)
20426 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
20428 (defun org-at-comment-p nil
20429 "Is cursor in a commented line?"
20430 (save-excursion
20431 (save-match-data
20432 (beginning-of-line)
20433 (looking-at "^[ \t]*# "))))
20435 (defun org-at-drawer-p nil
20436 "Is cursor at a drawer keyword?"
20437 (save-excursion
20438 (move-beginning-of-line 1)
20439 (looking-at org-drawer-regexp)))
20441 (defun org-at-block-p nil
20442 "Is cursor at a block keyword?"
20443 (save-excursion
20444 (move-beginning-of-line 1)
20445 (looking-at org-block-regexp)))
20447 (defun org-point-at-end-of-empty-headline ()
20448 "If point is at the end of an empty headline, return t, else nil.
20449 If the heading only contains a TODO keyword, it is still still considered
20450 empty."
20451 (let ((case-fold-search nil))
20452 (and (looking-at "[ \t]*$")
20453 org-todo-line-regexp
20454 (save-excursion
20455 (beginning-of-line)
20456 (looking-at org-todo-line-regexp)
20457 (string= (match-string 3) "")))))
20459 (defun org-at-heading-or-item-p ()
20460 (or (org-at-heading-p) (org-at-item-p)))
20462 (defun org-up-heading-all (arg)
20463 "Move to the heading line of which the present line is a subheading.
20464 This function considers both visible and invisible heading lines.
20465 With argument, move up ARG levels."
20466 (outline-up-heading arg t))
20468 (defun org-up-heading-safe ()
20469 "Move to the heading line of which the present line is a subheading.
20470 This version will not throw an error. It will return the level of the
20471 headline found, or nil if no higher level is found.
20473 Also, this function will be a lot faster than `outline-up-heading',
20474 because it relies on stars being the outline starters. This can really
20475 make a significant difference in outlines with very many siblings."
20476 (when (ignore-errors (org-back-to-heading t))
20477 (let ((level-up (1- (funcall outline-level))))
20478 (and (> level-up 0)
20479 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
20480 (funcall outline-level)))))
20482 (defun org-first-sibling-p ()
20483 "Is this heading the first child of its parents?"
20484 (interactive)
20485 (let ((re org-outline-regexp-bol)
20486 level l)
20487 (unless (org-at-heading-p t)
20488 (user-error "Not at a heading"))
20489 (setq level (funcall outline-level))
20490 (save-excursion
20491 (if (not (re-search-backward re nil t))
20493 (setq l (funcall outline-level))
20494 (< l level)))))
20496 (defun org-goto-sibling (&optional previous)
20497 "Goto the next sibling, even if it is invisible.
20498 When PREVIOUS is set, go to the previous sibling instead. Returns t
20499 when a sibling was found. When none is found, return nil and don't
20500 move point."
20501 (let ((fun (if previous 're-search-backward 're-search-forward))
20502 (pos (point))
20503 (re org-outline-regexp-bol)
20504 level l)
20505 (when (ignore-errors (org-back-to-heading t))
20506 (setq level (funcall outline-level))
20507 (catch 'exit
20508 (or previous (forward-char 1))
20509 (while (funcall fun re nil t)
20510 (setq l (funcall outline-level))
20511 (when (< l level) (goto-char pos) (throw 'exit nil))
20512 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20513 (goto-char pos)
20514 nil))))
20516 (defun org-show-siblings ()
20517 "Show all siblings of the current headline."
20518 (save-excursion
20519 (while (org-goto-sibling) (org-flag-heading nil)))
20520 (save-excursion
20521 (while (org-goto-sibling 'previous)
20522 (org-flag-heading nil))))
20524 (defun org-goto-first-child ()
20525 "Goto the first child, even if it is invisible.
20526 Return t when a child was found. Otherwise don't move point and
20527 return nil."
20528 (let (level (pos (point)) (re org-outline-regexp-bol))
20529 (when (ignore-errors (org-back-to-heading t))
20530 (setq level (outline-level))
20531 (forward-char 1)
20532 (if (and (re-search-forward re nil t) (> (outline-level) level))
20533 (progn (goto-char (match-beginning 0)) t)
20534 (goto-char pos) nil))))
20536 (defun org-show-hidden-entry ()
20537 "Show an entry where even the heading is hidden."
20538 (save-excursion
20539 (org-show-entry)))
20541 (defun org-flag-heading (flag &optional entry)
20542 "Flag the current heading. FLAG non-nil means make invisible.
20543 When ENTRY is non-nil, show the entire entry."
20544 (save-excursion
20545 (org-back-to-heading t)
20546 ;; Check if we should show the entire entry
20547 (if (not entry)
20548 (org-flag-region
20549 (line-end-position 0) (line-end-position) flag 'outline)
20550 (org-show-entry)
20551 (save-excursion
20552 (and (outline-next-heading)
20553 (org-flag-heading nil))))))
20555 (defun org-get-next-sibling ()
20556 "Move to next heading of the same level, and return point.
20557 If there is no such heading, return nil.
20558 This is like outline-next-sibling, but invisible headings are ok."
20559 (let ((level (funcall outline-level)))
20560 (outline-next-heading)
20561 (while (and (not (eobp)) (> (funcall outline-level) level))
20562 (outline-next-heading))
20563 (unless (or (eobp) (< (funcall outline-level) level))
20564 (point))))
20566 (defun org-get-last-sibling ()
20567 "Move to previous heading of the same level, and return point.
20568 If there is no such heading, return nil."
20569 (let ((opoint (point))
20570 (level (funcall outline-level)))
20571 (outline-previous-heading)
20572 (when (and (/= (point) opoint) (outline-on-heading-p t))
20573 (while (and (> (funcall outline-level) level)
20574 (not (bobp)))
20575 (outline-previous-heading))
20576 (unless (< (funcall outline-level) level)
20577 (point)))))
20579 (defun org-end-of-subtree (&optional invisible-ok to-heading)
20580 "Goto to the end of a subtree."
20581 ;; This contains an exact copy of the original function, but it uses
20582 ;; `org-back-to-heading', to make it work also in invisible
20583 ;; trees. And is uses an invisible-ok argument.
20584 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20585 ;; Furthermore, when used inside Org, finding the end of a large subtree
20586 ;; with many children and grandchildren etc, this can be much faster
20587 ;; than the outline version.
20588 (org-back-to-heading invisible-ok)
20589 (let ((first t)
20590 (level (funcall outline-level)))
20591 (if (and (derived-mode-p 'org-mode) (< level 1000))
20592 ;; A true heading (not a plain list item), in Org
20593 ;; This means we can easily find the end by looking
20594 ;; only for the right number of stars. Using a regexp to do
20595 ;; this is so much faster than using a Lisp loop.
20596 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20597 (forward-char 1)
20598 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20599 ;; something else, do it the slow way
20600 (while (and (not (eobp))
20601 (or first (> (funcall outline-level) level)))
20602 (setq first nil)
20603 (outline-next-heading)))
20604 (unless to-heading
20605 (when (memq (preceding-char) '(?\n ?\^M))
20606 ;; Go to end of line before heading
20607 (forward-char -1)
20608 (when (memq (preceding-char) '(?\n ?\^M))
20609 ;; leave blank line before heading
20610 (forward-char -1)))))
20611 (point))
20613 (defun org-end-of-meta-data (&optional full)
20614 "Skip planning line and properties drawer in current entry.
20615 When optional argument FULL is non-nil, also skip empty lines,
20616 clocking lines and regular drawers at the beginning of the
20617 entry."
20618 (org-back-to-heading t)
20619 (forward-line)
20620 (when (looking-at-p org-planning-line-re) (forward-line))
20621 (when (looking-at org-property-drawer-re)
20622 (goto-char (match-end 0))
20623 (forward-line))
20624 (when (and full (not (org-at-heading-p)))
20625 (catch 'exit
20626 (let ((end (save-excursion (outline-next-heading) (point)))
20627 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
20628 (while (not (eobp))
20629 (cond ((looking-at-p org-drawer-regexp)
20630 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
20631 (forward-line)
20632 (throw 'exit t)))
20633 ((looking-at-p re) (forward-line))
20634 (t (throw 'exit t))))))))
20636 (defun org-forward-heading-same-level (arg &optional invisible-ok)
20637 "Move forward to the ARG'th subheading at same level as this one.
20638 Stop at the first and last subheadings of a superior heading.
20639 Normally this only looks at visible headings, but when INVISIBLE-OK is
20640 non-nil it will also look at invisible ones."
20641 (interactive "p")
20642 (let ((backward? (and arg (< arg 0))))
20643 (if (org-before-first-heading-p)
20644 (if backward? (goto-char (point-min)) (outline-next-heading))
20645 (org-back-to-heading invisible-ok)
20646 (unless backward? (end-of-line)) ;do not match current headline
20647 (let ((level (- (match-end 0) (match-beginning 0) 1))
20648 (f (if backward? #'re-search-backward #'re-search-forward))
20649 (count (if arg (abs arg) 1))
20650 (result (point)))
20651 (while (and (> count 0)
20652 (funcall f org-outline-regexp-bol nil 'move))
20653 (let ((l (- (match-end 0) (match-beginning 0) 1)))
20654 (cond ((< l level) (setq count 0))
20655 ((and (= l level)
20656 (or invisible-ok
20657 (not (org-invisible-p
20658 (line-beginning-position)))))
20659 (cl-decf count)
20660 (when (= l level) (setq result (point)))))))
20661 (goto-char result))
20662 (beginning-of-line))))
20664 (defun org-backward-heading-same-level (arg &optional invisible-ok)
20665 "Move backward to the ARG'th subheading at same level as this one.
20666 Stop at the first and last subheadings of a superior heading."
20667 (interactive "p")
20668 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
20670 (defun org-next-visible-heading (arg)
20671 "Move to the next visible heading.
20673 This function wraps `outline-next-visible-heading' with
20674 `org-with-limited-levels' in order to skip over inline tasks and
20675 respect customization of `org-odd-levels-only'."
20676 (interactive "p")
20677 (org-with-limited-levels
20678 (outline-next-visible-heading arg)))
20680 (defun org-previous-visible-heading (arg)
20681 "Move to the previous visible heading.
20683 This function wraps `outline-previous-visible-heading' with
20684 `org-with-limited-levels' in order to skip over inline tasks and
20685 respect customization of `org-odd-levels-only'."
20686 (interactive "p")
20687 (org-with-limited-levels
20688 (outline-previous-visible-heading arg)))
20690 (defun org-forward-paragraph ()
20691 "Move forward to beginning of next paragraph or equivalent.
20693 The function moves point to the beginning of the next visible
20694 structural element, which can be a paragraph, a table, a list
20695 item, etc. It also provides some special moves for convenience:
20697 - On an affiliated keyword, jump to the beginning of the
20698 relative element.
20699 - On an item or a footnote definition, move to the second
20700 element inside, if any.
20701 - On a table or a property drawer, jump after it.
20702 - On a verse or source block, stop after blank lines."
20703 (interactive)
20704 (unless (eobp)
20705 (let* ((deactivate-mark nil)
20706 (element (org-element-at-point))
20707 (type (org-element-type element))
20708 (post-affiliated (org-element-property :post-affiliated element))
20709 (contents-begin (org-element-property :contents-begin element))
20710 (contents-end (org-element-property :contents-end element))
20711 (end (let ((end (org-element-property :end element)) (parent element))
20712 (while (and (setq parent (org-element-property :parent parent))
20713 (= (org-element-property :contents-end parent) end))
20714 (setq end (org-element-property :end parent)))
20715 end)))
20716 (cond ((not element)
20717 (skip-chars-forward " \r\t\n")
20718 (or (eobp) (beginning-of-line)))
20719 ;; On affiliated keywords, move to element's beginning.
20720 ((< (point) post-affiliated)
20721 (goto-char post-affiliated))
20722 ;; At a table row, move to the end of the table. Similarly,
20723 ;; at a node property, move to the end of the property
20724 ;; drawer.
20725 ((memq type '(node-property table-row))
20726 (goto-char (org-element-property
20727 :end (org-element-property :parent element))))
20728 ((memq type '(property-drawer table)) (goto-char end))
20729 ;; Consider blank lines as separators in verse and source
20730 ;; blocks to ease editing.
20731 ((memq type '(src-block verse-block))
20732 (when (eq type 'src-block)
20733 (setq contents-end
20734 (save-excursion (goto-char end)
20735 (skip-chars-backward " \r\t\n")
20736 (line-beginning-position))))
20737 (beginning-of-line)
20738 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
20739 (if (not (re-search-forward "^[ \t]*$" contents-end t))
20740 (goto-char end)
20741 (skip-chars-forward " \r\t\n")
20742 (if (= (point) contents-end) (goto-char end)
20743 (beginning-of-line))))
20744 ;; With no contents, just skip element.
20745 ((not contents-begin) (goto-char end))
20746 ;; If contents are invisible, skip the element altogether.
20747 ((org-invisible-p (line-end-position))
20748 (cl-case type
20749 (headline
20750 (org-with-limited-levels (outline-next-visible-heading 1)))
20751 ;; At a plain list, make sure we move to the next item
20752 ;; instead of skipping the whole list.
20753 (plain-list (forward-char)
20754 (org-forward-paragraph))
20755 (otherwise (goto-char end))))
20756 ((>= (point) contents-end) (goto-char end))
20757 ((>= (point) contents-begin)
20758 ;; This can only happen on paragraphs and plain lists.
20759 (cl-case type
20760 (paragraph (goto-char end))
20761 ;; At a plain list, try to move to second element in
20762 ;; first item, if possible.
20763 (plain-list (end-of-line)
20764 (org-forward-paragraph))))
20765 ;; When contents start on the middle of a line (e.g. in
20766 ;; items and footnote definitions), try to reach first
20767 ;; element starting after current line.
20768 ((> (line-end-position) contents-begin)
20769 (end-of-line)
20770 (org-forward-paragraph))
20771 (t (goto-char contents-begin))))))
20773 (defun org-backward-paragraph ()
20774 "Move backward to start of previous paragraph or equivalent.
20776 The function moves point to the beginning of the current
20777 structural element, which can be a paragraph, a table, a list
20778 item, etc., or to the beginning of the previous visible one if
20779 point is already there. It also provides some special moves for
20780 convenience:
20782 - On an affiliated keyword, jump to the first one.
20783 - On a table or a property drawer, move to its beginning.
20784 - On comment, example, export, src and verse blocks, stop
20785 before blank lines."
20786 (interactive)
20787 (unless (bobp)
20788 (let* ((deactivate-mark nil)
20789 (element (org-element-at-point))
20790 (type (org-element-type element))
20791 (contents-end (org-element-property :contents-end element))
20792 (post-affiliated (org-element-property :post-affiliated element))
20793 (begin (org-element-property :begin element))
20794 (special? ;blocks handled specially
20795 (memq type '(comment-block example-block export-block src-block
20796 verse-block)))
20797 (contents-begin
20798 (if special?
20799 ;; These types have no proper contents. Fake line
20800 ;; below the block opening line as contents beginning.
20801 (save-excursion (goto-char begin) (line-beginning-position 2))
20802 (org-element-property :contents-begin element))))
20803 (cond
20804 ((not element) (goto-char (point-min)))
20805 ((= (point) begin)
20806 (backward-char)
20807 (org-backward-paragraph))
20808 ((<= (point) post-affiliated) (goto-char begin))
20809 ;; Special behavior: on a table or a property drawer, move to
20810 ;; its beginning.
20811 ((memq type '(node-property table-row))
20812 (goto-char (org-element-property
20813 :post-affiliated (org-element-property :parent element))))
20814 (special?
20815 (if (<= (point) contents-begin) (goto-char post-affiliated)
20816 ;; Inside a verse block, see blank lines as paragraph
20817 ;; separators.
20818 (let ((origin (point)))
20819 (skip-chars-backward " \r\t\n" contents-begin)
20820 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
20821 (skip-chars-forward " \r\t\n" origin)
20822 (if (= (point) origin) (goto-char contents-begin)
20823 (beginning-of-line))))))
20824 ((eq type 'paragraph) (goto-char contents-begin)
20825 ;; When at first paragraph in an item or a footnote definition,
20826 ;; move directly to beginning of line.
20827 (let ((parent-contents
20828 (org-element-property
20829 :contents-begin (org-element-property :parent element))))
20830 (when (and parent-contents (= parent-contents contents-begin))
20831 (beginning-of-line))))
20832 ;; At the end of a greater element, move to the beginning of
20833 ;; the last element within.
20834 ((and contents-end (>= (point) contents-end))
20835 (goto-char (1- contents-end))
20836 (org-backward-paragraph))
20837 (t (goto-char (or post-affiliated begin))))
20838 ;; Ensure we never leave point invisible.
20839 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
20841 (defun org-forward-element ()
20842 "Move forward by one element.
20843 Move to the next element at the same level, when possible."
20844 (interactive)
20845 (cond ((eobp) (user-error "Cannot move further down"))
20846 ((org-with-limited-levels (org-at-heading-p))
20847 (let ((origin (point)))
20848 (goto-char (org-end-of-subtree nil t))
20849 (unless (org-with-limited-levels (org-at-heading-p))
20850 (goto-char origin)
20851 (user-error "Cannot move further down"))))
20853 (let* ((elem (org-element-at-point))
20854 (end (org-element-property :end elem))
20855 (parent (org-element-property :parent elem)))
20856 (cond ((and parent (= (org-element-property :contents-end parent) end))
20857 (goto-char (org-element-property :end parent)))
20858 ((integer-or-marker-p end) (goto-char end))
20859 (t (message "No element at point")))))))
20861 (defun org-backward-element ()
20862 "Move backward by one element.
20863 Move to the previous element at the same level, when possible."
20864 (interactive)
20865 (cond ((bobp) (user-error "Cannot move further up"))
20866 ((org-with-limited-levels (org-at-heading-p))
20867 ;; At a headline, move to the previous one, if any, or stay
20868 ;; here.
20869 (let ((origin (point)))
20870 (org-with-limited-levels (org-backward-heading-same-level 1))
20871 ;; When current headline has no sibling above, move to its
20872 ;; parent.
20873 (when (= (point) origin)
20874 (or (org-with-limited-levels (org-up-heading-safe))
20875 (progn (goto-char origin)
20876 (user-error "Cannot move further up"))))))
20878 (let* ((elem (org-element-at-point))
20879 (beg (org-element-property :begin elem)))
20880 (cond
20881 ;; Move to beginning of current element if point isn't
20882 ;; there already.
20883 ((null beg) (message "No element at point"))
20884 ((/= (point) beg) (goto-char beg))
20885 (t (goto-char beg)
20886 (skip-chars-backward " \r\t\n")
20887 (unless (bobp)
20888 (let ((prev (org-element-at-point)))
20889 (goto-char (org-element-property :begin prev))
20890 (while (and (setq prev (org-element-property :parent prev))
20891 (<= (org-element-property :end prev) beg))
20892 (goto-char (org-element-property :begin prev)))))))))))
20894 (defun org-up-element ()
20895 "Move to upper element."
20896 (interactive)
20897 (if (org-with-limited-levels (org-at-heading-p))
20898 (unless (org-up-heading-safe) (user-error "No surrounding element"))
20899 (let* ((elem (org-element-at-point))
20900 (parent (org-element-property :parent elem)))
20901 (if parent (goto-char (org-element-property :begin parent))
20902 (if (org-with-limited-levels (org-before-first-heading-p))
20903 (user-error "No surrounding element")
20904 (org-with-limited-levels (org-back-to-heading)))))))
20906 (defun org-down-element ()
20907 "Move to inner element."
20908 (interactive)
20909 (let ((element (org-element-at-point)))
20910 (cond
20911 ((memq (org-element-type element) '(plain-list table))
20912 (goto-char (org-element-property :contents-begin element))
20913 (forward-char))
20914 ((memq (org-element-type element) org-element-greater-elements)
20915 ;; If contents are hidden, first disclose them.
20916 (when (org-invisible-p (line-end-position)) (org-cycle))
20917 (goto-char (or (org-element-property :contents-begin element)
20918 (user-error "No content for this element"))))
20919 (t (user-error "No inner element")))))
20921 (defun org-drag-element-backward ()
20922 "Move backward element at point."
20923 (interactive)
20924 (let ((elem (or (org-element-at-point)
20925 (user-error "No element at point"))))
20926 (if (eq (org-element-type elem) 'headline)
20927 ;; Preserve point when moving a whole tree, even if point was
20928 ;; on blank lines below the headline.
20929 (let ((offset (skip-chars-backward " \t\n")))
20930 (unwind-protect (org-move-subtree-up)
20931 (forward-char (- offset))))
20932 (let ((prev-elem
20933 (save-excursion
20934 (goto-char (org-element-property :begin elem))
20935 (skip-chars-backward " \r\t\n")
20936 (unless (bobp)
20937 (let* ((beg (org-element-property :begin elem))
20938 (prev (org-element-at-point))
20939 (up prev))
20940 (while (and (setq up (org-element-property :parent up))
20941 (<= (org-element-property :end up) beg))
20942 (setq prev up))
20943 prev)))))
20944 ;; Error out if no previous element or previous element is
20945 ;; a parent of the current one.
20946 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
20947 (user-error "Cannot drag element backward")
20948 (let ((pos (point)))
20949 (org-element-swap-A-B prev-elem elem)
20950 (goto-char (+ (org-element-property :begin prev-elem)
20951 (- pos (org-element-property :begin elem))))))))))
20953 (defun org-drag-element-forward ()
20954 "Move forward element at point."
20955 (interactive)
20956 (let* ((pos (point))
20957 (elem (or (org-element-at-point)
20958 (user-error "No element at point"))))
20959 (when (= (point-max) (org-element-property :end elem))
20960 (user-error "Cannot drag element forward"))
20961 (goto-char (org-element-property :end elem))
20962 (let ((next-elem (org-element-at-point)))
20963 (when (or (org-element-nested-p elem next-elem)
20964 (and (eq (org-element-type next-elem) 'headline)
20965 (not (eq (org-element-type elem) 'headline))))
20966 (goto-char pos)
20967 (user-error "Cannot drag element forward"))
20968 ;; Compute new position of point: it's shifted by NEXT-ELEM
20969 ;; body's length (without final blanks) and by the length of
20970 ;; blanks between ELEM and NEXT-ELEM.
20971 (let ((size-next (- (save-excursion
20972 (goto-char (org-element-property :end next-elem))
20973 (skip-chars-backward " \r\t\n")
20974 (forward-line)
20975 ;; Small correction if buffer doesn't end
20976 ;; with a newline character.
20977 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
20978 (org-element-property :begin next-elem)))
20979 (size-blank (- (org-element-property :end elem)
20980 (save-excursion
20981 (goto-char (org-element-property :end elem))
20982 (skip-chars-backward " \r\t\n")
20983 (forward-line)
20984 (point)))))
20985 (org-element-swap-A-B elem next-elem)
20986 (goto-char (+ pos size-next size-blank))))))
20988 (defun org-drag-line-forward (arg)
20989 "Drag the line at point ARG lines forward."
20990 (interactive "p")
20991 (dotimes (_ (abs arg))
20992 (let ((c (current-column)))
20993 (if (< 0 arg)
20994 (progn
20995 (beginning-of-line 2)
20996 (transpose-lines 1)
20997 (beginning-of-line 0))
20998 (transpose-lines 1)
20999 (beginning-of-line -1))
21000 (org-move-to-column c))))
21002 (defun org-drag-line-backward (arg)
21003 "Drag the line at point ARG lines backward."
21004 (interactive "p")
21005 (org-drag-line-forward (- arg)))
21007 (defun org-mark-element ()
21008 "Put point at beginning of this element, mark at end.
21010 Interactively, if this command is repeated or (in Transient Mark
21011 mode) if the mark is active, it marks the next element after the
21012 ones already marked."
21013 (interactive)
21014 (let (deactivate-mark)
21015 (if (and (called-interactively-p 'any)
21016 (or (and (eq last-command this-command) (mark t))
21017 (and transient-mark-mode mark-active)))
21018 (set-mark
21019 (save-excursion
21020 (goto-char (mark))
21021 (goto-char (org-element-property :end (org-element-at-point)))))
21022 (let ((element (org-element-at-point)))
21023 (end-of-line)
21024 (push-mark (org-element-property :end element) t t)
21025 (goto-char (org-element-property :begin element))))))
21027 (defun org-narrow-to-element ()
21028 "Narrow buffer to current element."
21029 (interactive)
21030 (let ((elem (org-element-at-point)))
21031 (cond
21032 ((eq (car elem) 'headline)
21033 (narrow-to-region
21034 (org-element-property :begin elem)
21035 (org-element-property :end elem)))
21036 ((memq (car elem) org-element-greater-elements)
21037 (narrow-to-region
21038 (org-element-property :contents-begin elem)
21039 (org-element-property :contents-end elem)))
21041 (narrow-to-region
21042 (org-element-property :begin elem)
21043 (org-element-property :end elem))))))
21045 (defun org-transpose-element ()
21046 "Transpose current and previous elements, keeping blank lines between.
21047 Point is moved after both elements."
21048 (interactive)
21049 (org-skip-whitespace)
21050 (let ((end (org-element-property :end (org-element-at-point))))
21051 (org-drag-element-backward)
21052 (goto-char end)))
21054 (defun org-unindent-buffer ()
21055 "Un-indent the visible part of the buffer.
21056 Relative indentation (between items, inside blocks, etc.) isn't
21057 modified."
21058 (interactive)
21059 (unless (eq major-mode 'org-mode)
21060 (user-error "Cannot un-indent a buffer not in Org mode"))
21061 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
21062 (unindent-tree
21063 (lambda (contents)
21064 (dolist (element (reverse contents))
21065 (if (memq (org-element-type element) '(headline section))
21066 (funcall unindent-tree (org-element-contents element))
21067 (save-excursion
21068 (save-restriction
21069 (narrow-to-region
21070 (org-element-property :begin element)
21071 (org-element-property :end element))
21072 (org-do-remove-indentation))))))))
21073 (funcall unindent-tree (org-element-contents parse-tree))))
21075 (defun org-make-options-regexp (kwds &optional extra)
21076 "Make a regular expression for keyword lines.
21077 KWDS is a list of keywords, as strings. Optional argument EXTRA,
21078 when non-nil, is a regexp matching keywords names."
21079 (concat "^[ \t]*#\\+\\("
21080 (regexp-opt kwds)
21081 (and extra (concat (and kwds "\\|") extra))
21082 "\\):[ \t]*\\(.*\\)"))
21085 ;;; Conveniently switch to Info nodes
21087 (defun org-info-find-node (&optional nodename)
21088 "Find Info documentation NODENAME or Org documentation according context.
21089 Started from `gnus-info-find-node'."
21090 (interactive)
21091 (Info-goto-node
21092 (or nodename
21093 (let ((default-org-info-node "(org) Top"))
21094 (cond
21095 ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
21096 ((eq 'org-mode major-mode)
21097 (let* ((context (org-element-at-point))
21098 (element-info-nodes ; compare to `org-element-all-elements'.
21099 `((babel-call . "(org) Evaluating Code Blocks")
21100 (center-block . "(org) Paragraphs")
21101 (clock . ,default-org-info-node)
21102 (comment . "(org) Comment Lines")
21103 (comment-block . "(org) Comment Lines")
21104 (diary-sexp . ,default-org-info-node)
21105 (drawer . "(org) Drawers")
21106 (dynamic-block . "(org) Dynamic Blocks")
21107 (example-block . "(org) Literal Examples")
21108 (export-block . "(org) ASCII/Latin-1/UTF-8 export")
21109 (fixed-width . ,default-org-info-node)
21110 (footnote-definition . "(org) Creating Footnotes")
21111 (headline . "(org) Document Structure")
21112 (horizontal-rule . "(org) Built-in Table Editor")
21113 (inlinetask . ,default-org-info-node)
21114 (item . "(org) Plain Lists")
21115 (keyword . "(org) Per-file keywords")
21116 (latex-environment . "(org) LaTeX Export")
21117 (node-property . "(org) Properties and Columns")
21118 (paragraph . "(org) Paragraphs")
21119 (plain-list . "(org) Plain Lists")
21120 (planning . "(org) Deadlines and Scheduling")
21121 (property-drawer . "(org) Properties and Columns")
21122 (quote-block . "(org) Paragraphs")
21123 (section . ,default-org-info-node)
21124 (special-block . ,default-org-info-node)
21125 (src-block . "(org) Working with Source Code")
21126 (table . "(org) Tables")
21127 (table-row . "(org) Tables")
21128 (verse-block . "(org) Paragraphs"))))
21129 (or (cdr (assoc (car context) element-info-nodes))
21130 default-org-info-node)))
21131 (t default-org-info-node))))))
21134 ;;; Finish up
21136 (add-hook 'org-mode-hook ;remove overlays when changing major mode
21137 (lambda () (add-hook 'change-major-mode-hook
21138 'org-show-all 'append 'local)))
21140 (provide 'org)
21142 (run-hooks 'org-load-hook)
21144 ;;; org.el ends here