Fix alphabetic sorting for headlines, tags
[org-mode/org-tableheadings.git] / lisp / org.el
blob7f0f11f12b0c26459ae6c20e2c11900f3a293207
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: https://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; https://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; https://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (defvar org-inlinetask-min-level)
71 ;;;; Require other packages
73 (require 'cl-lib)
75 (eval-when-compile (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (or (eq this-command 'eval-buffer)
82 (condition-case nil
83 (load (concat (file-name-directory load-file-name)
84 "org-loaddefs.el")
85 nil t t t)
86 (error
87 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
88 (sit-for 3)
89 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
90 (sit-for 3))))
92 (require 'org-macs)
93 (require 'org-compat)
95 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
96 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 (defvar org-outline-regexp "\\*+ "
98 "Regexp to match Org headlines.")
100 (defvar org-outline-regexp-bol "^\\*+ "
101 "Regexp to match Org headlines.
102 This is similar to `org-outline-regexp' but additionally makes
103 sure that we are at the beginning of the line.")
105 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
106 "Matches a headline, putting stars and text into groups.
107 Stars are put in group 1 and the trimmed body in group 2.")
109 (declare-function calendar-check-holidays "holidays" (date))
110 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
111 (declare-function cdlatex-math-symbol "ext:cdlatex")
112 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
113 (declare-function org-add-archive-files "org-archive" (files))
114 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
115 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
116 (declare-function org-agenda-redo "org-agenda" (&optional all))
117 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
118 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
119 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
120 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
122 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
123 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
126 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
127 (declare-function org-clock-update-time-maybe "org-clock" ())
128 (declare-function org-clocking-buffer "org-clock" ())
129 (declare-function org-clocktable-shift "org-clock" (dir n))
130 (declare-function
131 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-link-parser "org-element" ())
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
170 (declare-function org-table-recalculate "org-table" (&optional all noalign))
171 (declare-function
172 org-table-sort-lines "org-table"
173 (&optional with-case sorting-type getkey-func compare-func interactive?))
174 (declare-function org-table-shrink "org-table" (&optional begin end))
175 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
176 (declare-function org-table-wrap-region "org-table" (arg))
177 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
178 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
179 (declare-function orgtbl-mode "org-table" (&optional arg))
180 (declare-function org-export-get-backend "ox" (name))
181 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
182 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
184 (defvar ffap-url-regexp)
185 (defvar org-element-paragraph-separate)
187 ;; load languages based on value of `org-babel-load-languages'
188 (defvar org-babel-load-languages)
190 ;;;###autoload
191 (defun org-babel-do-load-languages (sym value)
192 "Load the languages defined in `org-babel-load-languages'."
193 (set-default sym value)
194 (dolist (pair org-babel-load-languages)
195 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
196 (if active
197 (require (intern (concat "ob-" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-execute:" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-expand-body:" lang)))))))
203 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
204 ;;;###autoload
205 (defun org-babel-load-file (file &optional compile)
206 "Load Emacs Lisp source code blocks in the Org FILE.
207 This function exports the source code using `org-babel-tangle'
208 and then loads the resulting file using `load-file'. With prefix
209 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
210 file to byte-code before it is loaded."
211 (interactive "fFile to load: \nP")
212 (let* ((age (lambda (file)
213 (float-time
214 (time-subtract (current-time)
215 (nth 5 (or (file-attributes (file-truename file))
216 (file-attributes file)))))))
217 (base-name (file-name-sans-extension file))
218 (exported-file (concat base-name ".el")))
219 ;; tangle if the Org file is newer than the elisp file
220 (unless (and (file-exists-p exported-file)
221 (> (funcall age file) (funcall age exported-file)))
222 ;; Tangle-file traversal returns reversed list of tangled files
223 ;; and we want to evaluate the first target.
224 (setq exported-file
225 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
226 (message "%s %s"
227 (if compile
228 (progn (byte-compile-file exported-file 'load)
229 "Compiled and loaded")
230 (progn (load-file exported-file) "Loaded"))
231 exported-file)))
233 (defcustom org-babel-load-languages '((emacs-lisp . t))
234 "Languages which can be evaluated in Org buffers.
235 This list can be used to load support for any of the languages
236 below, note that each language will depend on a different set of
237 system executables and/or Emacs modes. When a language is
238 \"loaded\", then code blocks in that language can be evaluated
239 with `org-babel-execute-src-block' bound by default to C-c
240 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
241 be set to remove code block evaluation from the C-c C-c
242 keybinding. By default only Emacs Lisp (which has no
243 requirements) is loaded."
244 :group 'org-babel
245 :set 'org-babel-do-load-languages
246 :version "24.1"
247 :type '(alist :tag "Babel Languages"
248 :key-type
249 (choice
250 (const :tag "Awk" awk)
251 (const :tag "C" C)
252 (const :tag "R" R)
253 (const :tag "Asymptote" asymptote)
254 (const :tag "Calc" calc)
255 (const :tag "Clojure" clojure)
256 (const :tag "CSS" css)
257 (const :tag "Ditaa" ditaa)
258 (const :tag "Dot" dot)
259 (const :tag "Ebnf2ps" ebnf2ps)
260 (const :tag "Emacs Lisp" emacs-lisp)
261 (const :tag "Forth" forth)
262 (const :tag "Fortran" fortran)
263 (const :tag "Gnuplot" gnuplot)
264 (const :tag "Haskell" haskell)
265 (const :tag "hledger" hledger)
266 (const :tag "IO" io)
267 (const :tag "J" J)
268 (const :tag "Java" java)
269 (const :tag "Javascript" js)
270 (const :tag "LaTeX" latex)
271 (const :tag "Ledger" ledger)
272 (const :tag "Lilypond" lilypond)
273 (const :tag "Lisp" lisp)
274 (const :tag "Makefile" makefile)
275 (const :tag "Maxima" maxima)
276 (const :tag "Matlab" matlab)
277 (const :tag "Mscgen" mscgen)
278 (const :tag "Ocaml" ocaml)
279 (const :tag "Octave" octave)
280 (const :tag "Org" org)
281 (const :tag "Perl" perl)
282 (const :tag "Pico Lisp" picolisp)
283 (const :tag "PlantUML" plantuml)
284 (const :tag "Python" python)
285 (const :tag "Ruby" ruby)
286 (const :tag "Sass" sass)
287 (const :tag "Scala" scala)
288 (const :tag "Scheme" scheme)
289 (const :tag "Screen" screen)
290 (const :tag "Shell Script" shell)
291 (const :tag "Shen" shen)
292 (const :tag "Sql" sql)
293 (const :tag "Sqlite" sqlite)
294 (const :tag "Stan" stan)
295 (const :tag "Vala" vala))
296 :value-type (boolean :tag "Activate" :value t)))
298 ;;;; Customization variables
299 (defcustom org-clone-delete-id nil
300 "Remove ID property of clones of a subtree.
301 When non-nil, clones of a subtree don't inherit the ID property.
302 Otherwise they inherit the ID property with a new unique
303 identifier."
304 :type 'boolean
305 :version "24.1"
306 :group 'org-id)
308 ;;; Version
309 (org-check-version)
311 ;;;###autoload
312 (defun org-version (&optional here full message)
313 "Show the Org version.
314 Interactively, or when MESSAGE is non-nil, show it in echo area.
315 With prefix argument, or when HERE is non-nil, insert it at point.
316 In non-interactive uses, a reduced version string is output unless
317 FULL is given."
318 (interactive (list current-prefix-arg t (not current-prefix-arg)))
319 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
320 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
321 (load-suffixes (list ".el"))
322 (org-install-dir
323 (ignore-errors (org-find-library-dir "org-loaddefs"))))
324 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
325 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
326 (let* ((load-suffixes save-load-suffixes)
327 (release (org-release))
328 (git-version (org-git-version))
329 (version (format "Org mode version %s (%s @ %s)"
330 release
331 git-version
332 (if org-install-dir
333 (if (string= org-dir org-install-dir)
334 org-install-dir
335 (concat "mixed installation! "
336 org-install-dir
337 " and "
338 org-dir))
339 "org-loaddefs.el can not be found!")))
340 (version1 (if full version release)))
341 (when here (insert version1))
342 (when message (message "%s" version1))
343 version1)))
345 (defconst org-version (org-version))
348 ;;; Syntax Constants
350 ;;;; Block
352 (defconst org-block-regexp
353 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
354 "Regular expression for hiding blocks.")
356 (defconst org-dblock-start-re
357 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
358 "Matches the start line of a dynamic block, with parameters.")
360 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
361 "Matches the end of a dynamic block.")
363 ;;;; Clock and Planning
365 (defconst org-clock-string "CLOCK:"
366 "String used as prefix for timestamps clocking work hours on an item.")
368 (defvar org-closed-string "CLOSED:"
369 "String used as the prefix for timestamps logging closing a TODO entry.")
371 (defvar org-deadline-string "DEADLINE:"
372 "String to mark deadline entries.
373 \\<org-mode-map>
374 A deadline is this string, followed by a time stamp. It must be
375 a word, terminated by a colon. You can insert a schedule keyword
376 and a timestamp with `\\[org-deadline]'.")
378 (defvar org-scheduled-string "SCHEDULED:"
379 "String to mark scheduled TODO entries.
380 \\<org-mode-map>
381 A schedule is this string, followed by a time stamp. It must be
382 a word, terminated by a colon. You can insert a schedule keyword
383 and a timestamp with `\\[org-schedule]'.")
385 (defconst org-ds-keyword-length
386 (+ 2
387 (apply #'max
388 (mapcar #'length
389 (list org-deadline-string org-scheduled-string
390 org-clock-string org-closed-string))))
391 "Maximum length of the DEADLINE and SCHEDULED keywords.")
393 (defconst org-planning-line-re
394 (concat "^[ \t]*"
395 (regexp-opt
396 (list org-closed-string org-deadline-string org-scheduled-string)
398 "Matches a line with planning info.
399 Matched keyword is in group 1.")
401 (defconst org-clock-line-re
402 (concat "^[ \t]*" org-clock-string)
403 "Matches a line with clock info.")
405 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
406 "Matches the DEADLINE keyword.")
408 (defconst org-deadline-time-regexp
409 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
410 "Matches the DEADLINE keyword together with a time stamp.")
412 (defconst org-deadline-time-hour-regexp
413 (concat "\\<" org-deadline-string
414 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
415 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
417 (defconst org-deadline-line-regexp
418 (concat "\\<\\(" org-deadline-string "\\).*")
419 "Matches the DEADLINE keyword and the rest of the line.")
421 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
422 "Matches the SCHEDULED keyword.")
424 (defconst org-scheduled-time-regexp
425 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
426 "Matches the SCHEDULED keyword together with a time stamp.")
428 (defconst org-scheduled-time-hour-regexp
429 (concat "\\<" org-scheduled-string
430 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
431 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
433 (defconst org-closed-time-regexp
434 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
435 "Matches the CLOSED keyword together with a time stamp.")
437 (defconst org-keyword-time-regexp
438 (concat "\\<"
439 (regexp-opt
440 (list org-scheduled-string org-deadline-string org-closed-string
441 org-clock-string)
443 " *[[<]\\([^]>]+\\)[]>]")
444 "Matches any of the 4 keywords, together with the time stamp.")
446 (defconst org-keyword-time-not-clock-regexp
447 (concat
448 "\\<"
449 (regexp-opt
450 (list org-scheduled-string org-deadline-string org-closed-string) t)
451 " *[[<]\\([^]>]+\\)[]>]")
452 "Matches any of the 3 keywords, together with the time stamp.")
454 (defconst org-maybe-keyword-time-regexp
455 (concat "\\(\\<"
456 (regexp-opt
457 (list org-scheduled-string org-deadline-string org-closed-string
458 org-clock-string)
460 "\\)?"
461 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
462 "\\|"
463 "<%%([^\r\n>]*>\\)")
464 "Matches a timestamp, possibly preceded by a keyword.")
466 (defconst org-all-time-keywords
467 (mapcar (lambda (w) (substring w 0 -1))
468 (list org-scheduled-string org-deadline-string
469 org-clock-string org-closed-string))
470 "List of time keywords.")
472 ;;;; Drawer
474 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
475 "Matches first or last line of a hidden block.
476 Group 1 contains drawer's name or \"END\".")
478 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
479 "Regular expression matching the first line of a property drawer.")
481 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a property drawer.")
484 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
485 "Regular expression matching the first line of a clock drawer.")
487 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a clock drawer.")
490 (defconst org-property-drawer-re
491 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
492 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
493 "[ \t]*:END:[ \t]*$")
494 "Matches an entire property drawer.")
496 (defconst org-clock-drawer-re
497 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
498 org-clock-drawer-end-re "\\)\n?")
499 "Matches an entire clock drawer.")
501 ;;;; Headline
503 (defconst org-heading-keyword-regexp-format
504 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
505 "Printf format for a regexp matching a headline with some keyword.
506 This regexp will match the headline of any node which has the
507 exact keyword that is put into the format. The keyword isn't in
508 any group by default, but the stars and the body are.")
510 (defconst org-heading-keyword-maybe-regexp-format
511 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
512 "Printf format for a regexp matching a headline, possibly with some keyword.
513 This regexp can match any headline with the specified keyword, or
514 without a keyword. The keyword isn't in any group by default,
515 but the stars and the body are.")
517 (defconst org-archive-tag "ARCHIVE"
518 "The tag that marks a subtree as archived.
519 An archived subtree does not open during visibility cycling, and does
520 not contribute to the agenda listings.")
522 (eval-and-compile
523 (defconst org-comment-string "COMMENT"
524 "Entries starting with this keyword will never be exported.
525 \\<org-mode-map>
526 An entry can be toggled between COMMENT and normal with
527 `\\[org-toggle-comment]'."))
530 ;;;; LaTeX Environments and Fragments
532 (defconst org-latex-regexps
533 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
534 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
535 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
536 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
537 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
538 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
539 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
540 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
541 "Regular expressions for matching embedded LaTeX.")
543 ;;;; Node Property
545 (defconst org-effort-property "Effort"
546 "The property that is being used to keep track of effort estimates.
547 Effort estimates given in this property need to have the format H:MM.")
549 ;;;; Table
551 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
552 "Detect an org-type or table-type table.")
554 (defconst org-table-line-regexp "^[ \t]*|"
555 "Detect an org-type table line.")
557 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
558 "Detect an org-type table line.")
560 (defconst org-table-hline-regexp "^[ \t]*|-"
561 "Detect an org-type table hline.")
563 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
564 "Detect a table-type table hline.")
566 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
567 "Detect the first line outside a table when searching from within it.
568 This works for both table types.")
570 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
571 "Detect a #+TBLFM line.")
573 ;;;; Timestamp
575 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
576 "Regular expression for fast time stamp matching.")
578 (defconst org-ts-regexp-inactive
579 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
580 "Regular expression for fast inactive time stamp matching.")
582 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
583 "Regular expression for fast time stamp matching.")
585 (defconst org-ts-regexp0
586 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
587 "Regular expression matching time strings for analysis.
588 This one does not require the space after the date, so it can be used
589 on a string that terminates immediately after the date.")
591 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
592 "Regular expression matching time strings for analysis.")
594 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
595 "Regular expression matching time stamps, with groups.")
597 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
598 "Regular expression matching time stamps (also [..]), with groups.")
600 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
601 "Regular expression matching a time stamp range.")
603 (defconst org-tr-regexp-both
604 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
605 "Regular expression matching a time stamp range.")
607 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
608 org-ts-regexp "\\)?")
609 "Regular expression matching a time stamp or time stamp range.")
611 (defconst org-tsr-regexp-both
612 (concat org-ts-regexp-both "\\(--?-?"
613 org-ts-regexp-both "\\)?")
614 "Regular expression matching a time stamp or time stamp range.
615 The time stamps may be either active or inactive.")
617 (defconst org-repeat-re
618 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
619 "Regular expression for specifying repeated events.
620 After a match, group 1 contains the repeat expression.")
622 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
623 "Formats for `format-time-string' which are used for time stamps.")
626 ;;; The custom variables
628 (defgroup org nil
629 "Outline-based notes management and organizer."
630 :tag "Org"
631 :group 'outlines
632 :group 'calendar)
634 (defcustom org-mode-hook nil
635 "Mode hook for Org mode, run after the mode was turned on."
636 :group 'org
637 :type 'hook)
639 (defcustom org-load-hook nil
640 "Hook that is run after org.el has been loaded."
641 :group 'org
642 :type 'hook)
644 (defcustom org-log-buffer-setup-hook nil
645 "Hook that is run after an Org log buffer is created."
646 :group 'org
647 :version "24.1"
648 :type 'hook)
650 (defvar org-modules) ; defined below
651 (defvar org-modules-loaded nil
652 "Have the modules been loaded already?")
654 (defun org-load-modules-maybe (&optional force)
655 "Load all extensions listed in `org-modules'."
656 (when (or force (not org-modules-loaded))
657 (dolist (ext org-modules)
658 (condition-case nil (require ext)
659 (error (message "Problems while trying to load feature `%s'" ext))))
660 (setq org-modules-loaded t)))
662 (defun org-set-modules (var value)
663 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
664 (set var value)
665 (when (featurep 'org)
666 (org-load-modules-maybe 'force)
667 (org-element-cache-reset 'all)))
669 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
670 "Modules that should always be loaded together with org.el.
672 If a description starts with <C>, the file is not part of Emacs
673 and loading it will require that you have downloaded and properly
674 installed the Org mode distribution.
676 You can also use this system to load external packages (i.e. neither Org
677 core modules, nor modules from the CONTRIB directory). Just add symbols
678 to the end of the list. If the package is called org-xyz.el, then you need
679 to add the symbol `xyz', and the package must have a call to:
681 (provide \\='org-xyz)
683 For export specific modules, see also `org-export-backends'."
684 :group 'org
685 :set 'org-set-modules
686 :version "24.4"
687 :package-version '(Org . "8.0")
688 :type
689 '(set :greedy t
690 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
691 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
692 (const :tag " crypt: Encryption of subtrees" org-crypt)
693 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
694 (const :tag " docview: Links to doc-view buffers" org-docview)
695 (const :tag " eww: Store link to url of eww" org-eww)
696 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
697 (const :tag " habit: Track your consistency with habits" org-habit)
698 (const :tag " id: Global IDs for identifying entries" org-id)
699 (const :tag " info: Links to Info nodes" org-info)
700 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
701 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
702 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
703 (const :tag " mouse: Additional mouse support" org-mouse)
704 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
705 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
706 (const :tag " tempo: Fast completion for structures" org-tempo)
707 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
709 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
710 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
711 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
712 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
713 (const :tag "C collector: Collect properties into tables" org-collector)
714 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
715 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
716 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
717 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
718 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
719 (const :tag "C eval: Include command output as text" org-eval)
720 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
721 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
722 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
723 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
724 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
725 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
726 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
727 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
728 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
729 (const :tag "C man: Support for links to manpages in Org mode" org-man)
730 (const :tag "C mew: Links to Mew folders/messages" org-mew)
731 (const :tag "C mtags: Support for muse-like tags" org-mtags)
732 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
733 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
734 (const :tag "C registry: A registry for Org links" org-registry)
735 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
736 (const :tag "C secretary: Team management with Org" org-secretary)
737 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
738 (const :tag "C toc: Table of contents for Org buffer" org-toc)
739 (const :tag "C track: Keep up with Org mode development" org-track)
740 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
741 (const :tag "C vm: Links to VM folders/messages" org-vm)
742 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
743 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
744 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
746 (defvar org-export-registered-backends) ; From ox.el.
747 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
748 (declare-function org-export-backend-name "ox" (backend) t)
749 (defcustom org-export-backends '(ascii html icalendar latex odt)
750 "List of export back-ends that should be always available.
752 If a description starts with <C>, the file is not part of Emacs
753 and loading it will require that you have downloaded and properly
754 installed the Org mode distribution.
756 Unlike to `org-modules', libraries in this list will not be
757 loaded along with Org, but only once the export framework is
758 needed.
760 This variable needs to be set before org.el is loaded. If you
761 need to make a change while Emacs is running, use the customize
762 interface or run the following code, where VAL stands for the new
763 value of the variable, after updating it:
765 (progn
766 (setq org-export-registered-backends
767 (cl-remove-if-not
768 (lambda (backend)
769 (let ((name (org-export-backend-name backend)))
770 (or (memq name val)
771 (catch \\='parentp
772 (dolist (b val)
773 (and (org-export-derived-backend-p b name)
774 (throw \\='parentp t)))))))
775 org-export-registered-backends))
776 (let ((new-list (mapcar #\\='org-export-backend-name
777 org-export-registered-backends)))
778 (dolist (backend val)
779 (cond
780 ((not (load (format \"ox-%s\" backend) t t))
781 (message \"Problems while trying to load export back-end \\=`%s\\='\"
782 backend))
783 ((not (memq backend new-list)) (push backend new-list))))
784 (set-default \\='org-export-backends new-list)))
786 Adding a back-end to this list will also pull the back-end it
787 depends on, if any."
788 :group 'org
789 :group 'org-export
790 :version "26.1"
791 :package-version '(Org . "9.0")
792 :initialize 'custom-initialize-set
793 :set (lambda (var val)
794 (if (not (featurep 'ox)) (set-default var val)
795 ;; Any back-end not required anymore (not present in VAL and not
796 ;; a parent of any back-end in the new value) is removed from the
797 ;; list of registered back-ends.
798 (setq org-export-registered-backends
799 (cl-remove-if-not
800 (lambda (backend)
801 (let ((name (org-export-backend-name backend)))
802 (or (memq name val)
803 (catch 'parentp
804 (dolist (b val)
805 (and (org-export-derived-backend-p b name)
806 (throw 'parentp t)))))))
807 org-export-registered-backends))
808 ;; Now build NEW-LIST of both new back-ends and required
809 ;; parents.
810 (let ((new-list (mapcar #'org-export-backend-name
811 org-export-registered-backends)))
812 (dolist (backend val)
813 (cond
814 ((not (load (format "ox-%s" backend) t t))
815 (message "Problems while trying to load export back-end `%s'"
816 backend))
817 ((not (memq backend new-list)) (push backend new-list))))
818 ;; Set VAR to that list with fixed dependencies.
819 (set-default var new-list))))
820 :type '(set :greedy t
821 (const :tag " ascii Export buffer to ASCII format" ascii)
822 (const :tag " beamer Export buffer to Beamer presentation" beamer)
823 (const :tag " html Export buffer to HTML format" html)
824 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
825 (const :tag " latex Export buffer to LaTeX format" latex)
826 (const :tag " man Export buffer to MAN format" man)
827 (const :tag " md Export buffer to Markdown format" md)
828 (const :tag " odt Export buffer to ODT format" odt)
829 (const :tag " org Export buffer to Org format" org)
830 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
831 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
832 (const :tag "C deck Export buffer to deck.js presentations" deck)
833 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
834 (const :tag "C groff Export buffer to Groff format" groff)
835 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
836 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
837 (const :tag "C s5 Export buffer to s5 presentations" s5)
838 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
840 (eval-after-load 'ox
841 '(dolist (backend org-export-backends)
842 (condition-case nil (require (intern (format "ox-%s" backend)))
843 (error (message "Problems while trying to load export back-end `%s'"
844 backend)))))
846 (defcustom org-support-shift-select nil
847 "Non-nil means make shift-cursor commands select text when possible.
848 \\<org-mode-map>\
850 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
851 start selecting a region, or enlarge regions started in this way.
852 In Org mode, in special contexts, these same keys are used for
853 other purposes, important enough to compete with shift selection.
854 Org tries to balance these needs by supporting `shift-select-mode'
855 outside these special contexts, under control of this variable.
857 The default of this variable is nil, to avoid confusing behavior. Shifted
858 cursor keys will then execute Org commands in the following contexts:
859 - on a headline, changing TODO state (left/right) and priority (up/down)
860 - on a time stamp, changing the time
861 - in a plain list item, changing the bullet type
862 - in a property definition line, switching between allowed values
863 - in the BEGIN line of a clock table (changing the time block).
864 Outside these contexts, the commands will throw an error.
866 When this variable is t and the cursor is not in a special
867 context, Org mode will support shift-selection for making and
868 enlarging regions. To make this more effective, the bullet
869 cycling will no longer happen anywhere in an item line, but only
870 if the cursor is exactly on the bullet.
872 If you set this variable to the symbol `always', then the keys
873 will not be special in headlines, property lines, and item lines,
874 to make shift selection work there as well. If this is what you
875 want, you can use the following alternative commands:
876 `\\[org-todo]' and `\\[org-priority]' \
877 to change TODO state and priority,
878 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
879 can be used to switch TODO sets,
880 `\\[org-ctrl-c-minus]' to cycle item bullet types,
881 and properties can be edited by hand or in column view.
883 However, when the cursor is on a timestamp, shift-cursor commands
884 will still edit the time stamp - this is just too good to give up."
885 :group 'org
886 :type '(choice
887 (const :tag "Never" nil)
888 (const :tag "When outside special context" t)
889 (const :tag "Everywhere except timestamps" always)))
891 (defcustom org-loop-over-headlines-in-active-region nil
892 "Shall some commands act upon headlines in the active region?
894 When set to t, some commands will be performed in all headlines
895 within the active region.
897 When set to `start-level', some commands will be performed in all
898 headlines within the active region, provided that these headlines
899 are of the same level than the first one.
901 When set to a string, those commands will be performed on the
902 matching headlines within the active region. Such string must be
903 a tags/property/todo match as it is used in the agenda tags view.
905 The list of commands is: `org-schedule', `org-deadline',
906 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
907 `org-archive-to-archive-sibling'. The archiving commands skip
908 already archived entries."
909 :type '(choice (const :tag "Don't loop" nil)
910 (const :tag "All headlines in active region" t)
911 (const :tag "In active region, headlines at the same level than the first one" start-level)
912 (string :tag "Tags/Property/Todo matcher"))
913 :version "24.1"
914 :group 'org-todo
915 :group 'org-archive)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org mode will switch to OVERVIEW.
920 This can also be configured on a per-file basis by adding one of
921 the following lines anywhere in the buffer:
923 #+STARTUP: fold (or `overview', this is equivalent)
924 #+STARTUP: nofold (or `showall', this is equivalent)
925 #+STARTUP: content
926 #+STARTUP: showeverything
928 Set `org-agenda-inhibit-startup' to a non-nil value if you want
929 to ignore this option when Org opens agenda files for the first
930 time."
931 :group 'org-startup
932 :type '(choice
933 (const :tag "nofold: show all" nil)
934 (const :tag "fold: overview" t)
935 (const :tag "content: all headlines" content)
936 (const :tag "show everything, even drawers" showeverything)))
938 (defcustom org-startup-truncated t
939 "Non-nil means entering Org mode will set `truncate-lines'.
940 This is useful since some lines containing links can be very long and
941 uninteresting. Also tables look terrible when wrapped.
943 The variable `org-startup-truncated' allows to configure
944 truncation for Org mode different to the other modes that use the
945 variable `truncate-lines' and as a shortcut instead of putting
946 the variable `truncate-lines' into the `org-mode-hook'. If one
947 wants to configure truncation for Org mode not statically but
948 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
949 the variable `truncate-lines' has to be used because in such a
950 case it is too late to set the variable `org-startup-truncated'."
951 :group 'org-startup
952 :type 'boolean)
954 (defcustom org-startup-indented nil
955 "Non-nil means turn on `org-indent-mode' on startup.
956 This can also be configured on a per-file basis by adding one of
957 the following lines anywhere in the buffer:
959 #+STARTUP: indent
960 #+STARTUP: noindent"
961 :group 'org-structure
962 :type '(choice
963 (const :tag "Not" nil)
964 (const :tag "Globally (slow on startup in large files)" t)))
966 (defcustom org-use-sub-superscripts t
967 "Non-nil means interpret \"_\" and \"^\" for display.
969 If you want to control how Org exports those characters, see
970 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
971 used to be an alias for `org-export-with-sub-superscripts' in
972 Org <8.0, it is not anymore.
974 When this option is turned on, you can use TeX-like syntax for
975 sub- and superscripts within the buffer. Several characters after
976 \"_\" or \"^\" will be considered as a single item - so grouping
977 with {} is normally not needed. For example, the following things
978 will be parsed as single sub- or superscripts:
980 10^24 or 10^tau several digits will be considered 1 item.
981 10^-12 or 10^-tau a leading sign with digits or a word
982 x^2-y^3 will be read as x^2 - y^3, because items are
983 terminated by almost any nonword/nondigit char.
984 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
986 Still, ambiguity is possible. So when in doubt, use {} to enclose
987 the sub/superscript. If you set this variable to the symbol `{}',
988 the braces are *required* in order to trigger interpretations as
989 sub/superscript. This can be helpful in documents that need \"_\"
990 frequently in plain text."
991 :group 'org-startup
992 :version "24.4"
993 :package-version '(Org . "8.0")
994 :type '(choice
995 (const :tag "Always interpret" t)
996 (const :tag "Only with braces" {})
997 (const :tag "Never interpret" nil)))
999 (defcustom org-startup-with-beamer-mode nil
1000 "Non-nil means turn on `org-beamer-mode' on startup.
1001 This can also be configured on a per-file basis by adding one of
1002 the following lines anywhere in the buffer:
1004 #+STARTUP: beamer"
1005 :group 'org-startup
1006 :version "24.1"
1007 :type 'boolean)
1009 (defcustom org-startup-align-all-tables nil
1010 "Non-nil means align all tables when visiting a file.
1011 This can also be configured on a per-file basis by adding one of
1012 the following lines anywhere in the buffer:
1013 #+STARTUP: align
1014 #+STARTUP: noalign"
1015 :group 'org-startup
1016 :type 'boolean)
1018 (defcustom org-startup-shrink-all-tables nil
1019 "Non-nil means shrink all table columns with a width cookie.
1020 This can also be configured on a per-file basis by adding one of
1021 the following lines anywhere in the buffer:
1022 #+STARTUP: shrink"
1023 :group 'org-startup
1024 :type 'boolean
1025 :version "27.1"
1026 :package-version '(Org . "9.2")
1027 :safe #'booleanp)
1029 (defcustom org-startup-with-inline-images nil
1030 "Non-nil means show inline images when loading a new Org file.
1031 This can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: inlineimages
1034 #+STARTUP: noinlineimages"
1035 :group 'org-startup
1036 :version "24.1"
1037 :type 'boolean)
1039 (defcustom org-startup-with-latex-preview nil
1040 "Non-nil means preview LaTeX fragments when loading a new Org file.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: latexpreview
1045 #+STARTUP: nolatexpreview"
1046 :group 'org-startup
1047 :version "24.4"
1048 :package-version '(Org . "8.0")
1049 :type 'boolean)
1051 (defcustom org-insert-mode-line-in-empty-file nil
1052 "Non-nil means insert the first line setting Org mode in empty files.
1053 When the function `org-mode' is called interactively in an empty file, this
1054 normally means that the file name does not automatically trigger Org mode.
1055 To ensure that the file will always be in Org mode in the future, a
1056 line enforcing Org mode will be inserted into the buffer, if this option
1057 has been set."
1058 :group 'org-startup
1059 :type 'boolean)
1061 (defcustom org-replace-disputed-keys nil
1062 "Non-nil means use alternative key bindings for some keys.
1064 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1065 These keys are also used by other packages like Shift Select mode,
1066 CUA mode or Windmove. If you want to use Org mode together with
1067 one of these other modes, or more generally if you would like to
1068 move some Org mode commands to other keys, set this variable and
1069 configure the keys with the variable `org-disputed-keys'.
1071 This option is only relevant at load-time of Org mode, and must be set
1072 *before* org.el is loaded. Changing it requires a restart of Emacs to
1073 become effective."
1074 :group 'org-startup
1075 :type 'boolean)
1077 (defcustom org-use-extra-keys nil
1078 "Non-nil means use extra key sequence definitions for certain commands.
1079 This happens automatically if `window-system' is nil. This
1080 variable lets you do the same manually. You must set it before
1081 loading Org."
1082 :group 'org-startup
1083 :type 'boolean)
1085 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1087 (defcustom org-disputed-keys
1088 '(([(shift up)] . [(meta p)])
1089 ([(shift down)] . [(meta n)])
1090 ([(shift left)] . [(meta -)])
1091 ([(shift right)] . [(meta +)])
1092 ([(control shift right)] . [(meta shift +)])
1093 ([(control shift left)] . [(meta shift -)]))
1094 "Keys for which Org mode and other modes compete.
1095 This is an alist, cars are the default keys, second element specifies
1096 the alternative to use when `org-replace-disputed-keys' is t.
1098 Keys can be specified in any syntax supported by `define-key'.
1099 The value of this option takes effect only at Org mode startup,
1100 therefore you'll have to restart Emacs to apply it after changing."
1101 :group 'org-startup
1102 :type 'alist)
1104 (defun org-key (key)
1105 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1106 Or return the original if not disputed."
1107 (when org-replace-disputed-keys
1108 (let* ((nkey (key-description key))
1109 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1110 org-disputed-keys)))
1111 (setq key (if x (cdr x) key))))
1112 key)
1114 (defun org-defkey (keymap key def)
1115 "Define a key, possibly translated, as returned by `org-key'."
1116 (define-key keymap (org-key key) def))
1118 (defcustom org-ellipsis nil
1119 "The ellipsis to use in the Org mode outline.
1121 When nil, just use the standard three dots. When a non-empty string,
1122 use that string instead.
1124 The change affects only Org mode (which will then use its own display table).
1125 Changing this requires executing `\\[org-mode]' in a buffer to become
1126 effective."
1127 :group 'org-startup
1128 :type '(choice (const :tag "Default" nil)
1129 (string :tag "String" :value "...#"))
1130 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1132 (defvar org-display-table nil
1133 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1135 (defgroup org-keywords nil
1136 "Keywords in Org mode."
1137 :tag "Org Keywords"
1138 :group 'org)
1140 (defcustom org-closed-keep-when-no-todo nil
1141 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1142 :group 'org-todo
1143 :group 'org-keywords
1144 :version "24.4"
1145 :package-version '(Org . "8.0")
1146 :type 'boolean)
1148 (defgroup org-structure nil
1149 "Options concerning the general structure of Org files."
1150 :tag "Org Structure"
1151 :group 'org)
1153 (defgroup org-reveal-location nil
1154 "Options about how to make context of a location visible."
1155 :tag "Org Reveal Location"
1156 :group 'org-structure)
1158 (defcustom org-show-context-detail '((agenda . local)
1159 (bookmark-jump . lineage)
1160 (isearch . lineage)
1161 (default . ancestors))
1162 "Alist between context and visibility span when revealing a location.
1164 \\<org-mode-map>Some actions may move point into invisible
1165 locations. As a consequence, Org always expose a neighborhood
1166 around point. How much is shown depends on the initial action,
1167 or context. Valid contexts are
1169 agenda when exposing an entry from the agenda
1170 org-goto when using the command `org-goto' (`\\[org-goto]')
1171 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1172 tags-tree when constructing a sparse tree based on tags matches
1173 link-search when exposing search matches associated with a link
1174 mark-goto when exposing the jump goal of a mark
1175 bookmark-jump when exposing a bookmark location
1176 isearch when exiting from an incremental search
1177 default default for all contexts not set explicitly
1179 Allowed visibility spans are
1181 minimal show current headline; if point is not on headline,
1182 also show entry
1184 local show current headline, entry and next headline
1186 ancestors show current headline and its direct ancestors; if
1187 point is not on headline, also show entry
1189 lineage show current headline, its direct ancestors and all
1190 their children; if point is not on headline, also show
1191 entry and first child
1193 tree show current headline, its direct ancestors and all
1194 their children; if point is not on headline, also show
1195 entry and all children
1197 canonical show current headline, its direct ancestors along with
1198 their entries and children; if point is not located on
1199 the headline, also show current entry and all children
1201 As special cases, a nil or t value means show all contexts in
1202 `minimal' or `canonical' view, respectively.
1204 Some views can make displayed information very compact, but also
1205 make it harder to edit the location of the match. In such
1206 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1207 more context."
1208 :group 'org-reveal-location
1209 :version "26.1"
1210 :package-version '(Org . "9.0")
1211 :type '(choice
1212 (const :tag "Canonical" t)
1213 (const :tag "Minimal" nil)
1214 (repeat :greedy t :tag "Individual contexts"
1215 (cons
1216 (choice :tag "Context"
1217 (const agenda)
1218 (const org-goto)
1219 (const occur-tree)
1220 (const tags-tree)
1221 (const link-search)
1222 (const mark-goto)
1223 (const bookmark-jump)
1224 (const isearch)
1225 (const default))
1226 (choice :tag "Detail level"
1227 (const minimal)
1228 (const local)
1229 (const ancestors)
1230 (const lineage)
1231 (const tree)
1232 (const canonical))))))
1234 (defcustom org-indirect-buffer-display 'other-window
1235 "How should indirect tree buffers be displayed?
1237 This applies to indirect buffers created with the commands
1238 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1240 Valid values are:
1241 current-window Display in the current window
1242 other-window Just display in another window.
1243 dedicated-frame Create one new frame, and re-use it each time.
1244 new-frame Make a new frame each time. Note that in this case
1245 previously-made indirect buffers are kept, and you need to
1246 kill these buffers yourself."
1247 :group 'org-structure
1248 :group 'org-agenda-windows
1249 :type '(choice
1250 (const :tag "In current window" current-window)
1251 (const :tag "In current frame, other window" other-window)
1252 (const :tag "Each time a new frame" new-frame)
1253 (const :tag "One dedicated frame" dedicated-frame)))
1255 (defcustom org-use-speed-commands nil
1256 "Non-nil means activate single letter commands at beginning of a headline.
1257 This may also be a function to test for appropriate locations where speed
1258 commands should be active.
1260 For example, to activate speed commands when the point is on any
1261 star at the beginning of the headline, you can do this:
1263 (setq org-use-speed-commands
1264 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1265 :group 'org-structure
1266 :type '(choice
1267 (const :tag "Never" nil)
1268 (const :tag "At beginning of headline stars" t)
1269 (function)))
1271 (defcustom org-speed-commands-user nil
1272 "Alist of additional speed commands.
1273 This list will be checked before `org-speed-commands-default'
1274 when the variable `org-use-speed-commands' is non-nil
1275 and when the cursor is at the beginning of a headline.
1276 The car of each entry is a string with a single letter, which must
1277 be assigned to `self-insert-command' in the global map.
1278 The cdr is either a command to be called interactively, a function
1279 to be called, or a form to be evaluated.
1280 An entry that is just a list with a single string will be interpreted
1281 as a descriptive headline that will be added when listing the speed
1282 commands in the Help buffer using the `?' speed command."
1283 :group 'org-structure
1284 :type '(repeat :value ("k" . ignore)
1285 (choice :value ("k" . ignore)
1286 (list :tag "Descriptive Headline" (string :tag "Headline"))
1287 (cons :tag "Letter and Command"
1288 (string :tag "Command letter")
1289 (choice
1290 (function)
1291 (sexp))))))
1293 (defcustom org-bookmark-names-plist
1294 '(:last-capture "org-capture-last-stored"
1295 :last-refile "org-refile-last-stored"
1296 :last-capture-marker "org-capture-last-stored-marker")
1297 "Names for bookmarks automatically set by some Org commands.
1298 This can provide strings as names for a number of bookmarks Org sets
1299 automatically. The following keys are currently implemented:
1300 :last-capture
1301 :last-capture-marker
1302 :last-refile
1303 When a key does not show up in the property list, the corresponding bookmark
1304 is not set."
1305 :group 'org-structure
1306 :type 'plist)
1308 (defgroup org-cycle nil
1309 "Options concerning visibility cycling in Org mode."
1310 :tag "Org Cycle"
1311 :group 'org-structure)
1313 (defcustom org-cycle-skip-children-state-if-no-children t
1314 "Non-nil means skip CHILDREN state in entries that don't have any."
1315 :group 'org-cycle
1316 :type 'boolean)
1318 (defcustom org-cycle-max-level nil
1319 "Maximum level which should still be subject to visibility cycling.
1320 Levels higher than this will, for cycling, be treated as text, not a headline.
1321 When `org-odd-levels-only' is set, a value of N in this variable actually
1322 means 2N-1 stars as the limiting headline.
1323 When nil, cycle all levels.
1324 Note that the limiting level of cycling is also influenced by
1325 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1326 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1327 than its value."
1328 :group 'org-cycle
1329 :type '(choice
1330 (const :tag "No limit" nil)
1331 (integer :tag "Maximum level")))
1333 (defcustom org-hide-block-startup nil
1334 "Non-nil means entering Org mode will fold all blocks.
1335 This can also be set in on a per-file basis with
1337 #+STARTUP: hideblocks
1338 #+STARTUP: showblocks"
1339 :group 'org-startup
1340 :group 'org-cycle
1341 :type 'boolean)
1343 (defcustom org-cycle-global-at-bob nil
1344 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1346 This makes it possible to do global cycling without having to use `S-TAB'
1347 or `\\[universal-argument] TAB'. For this special case to work, the first \
1348 line of the buffer
1349 must not be a headline -- it may be empty or some other text.
1351 When used in this way, `org-cycle-hook' is disabled temporarily to make
1352 sure the cursor stays at the beginning of the buffer.
1354 When this option is nil, don't do anything special at the beginning of
1355 the buffer."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-level-after-item/entry-creation t
1360 "Non-nil means cycle entry level or item indentation in new empty entries.
1362 When the cursor is at the end of an empty headline, i.e., with only stars
1363 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1364 and then all possible ancestor states, before returning to the original state.
1365 This makes data entry extremely fast: M-RET to create a new headline,
1366 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1368 When the cursor is at the end of an empty plain list item, one TAB will
1369 make it a subitem, two or more tabs will back up to make this an item
1370 higher up in the item hierarchy."
1371 :group 'org-cycle
1372 :type 'boolean)
1374 (defcustom org-cycle-emulate-tab t
1375 "Where should `org-cycle' emulate TAB.
1376 nil Never
1377 white Only in completely white lines
1378 whitestart Only at the beginning of lines, before the first non-white char
1379 t Everywhere except in headlines
1380 exc-hl-bol Everywhere except at the start of a headline
1381 If TAB is used in a place where it does not emulate TAB, the current subtree
1382 visibility is cycled."
1383 :group 'org-cycle
1384 :type '(choice (const :tag "Never" nil)
1385 (const :tag "Only in completely white lines" white)
1386 (const :tag "Before first char in a line" whitestart)
1387 (const :tag "Everywhere except in headlines" t)
1388 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1390 (defcustom org-cycle-separator-lines 2
1391 "Number of empty lines needed to keep an empty line between collapsed trees.
1392 If you leave an empty line between the end of a subtree and the following
1393 headline, this empty line is hidden when the subtree is folded.
1394 Org mode will leave (exactly) one empty line visible if the number of
1395 empty lines is equal or larger to the number given in this variable.
1396 So the default 2 means at least 2 empty lines after the end of a subtree
1397 are needed to produce free space between a collapsed subtree and the
1398 following headline.
1400 If the number is negative, and the number of empty lines is at least -N,
1401 all empty lines are shown.
1403 Special case: when 0, never leave empty lines in collapsed view."
1404 :group 'org-cycle
1405 :type 'integer)
1406 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1408 (defcustom org-pre-cycle-hook nil
1409 "Hook that is run before visibility cycling is happening.
1410 The function(s) in this hook must accept a single argument which indicates
1411 the new state that will be set right after running this hook. The
1412 argument is a symbol. Before a global state change, it can have the values
1413 `overview', `content', or `all'. Before a local state change, it can have
1414 the values `folded', `children', or `subtree'."
1415 :group 'org-cycle
1416 :type 'hook)
1418 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1419 org-cycle-show-empty-lines
1420 org-optimize-window-after-visibility-change)
1421 "Hook that is run after `org-cycle' has changed the buffer visibility.
1422 The function(s) in this hook must accept a single argument which indicates
1423 the new state that was set by the most recent `org-cycle' command. The
1424 argument is a symbol. After a global state change, it can have the values
1425 `overview', `contents', or `all'. After a local state change, it can have
1426 the values `folded', `children', or `subtree'."
1427 :group 'org-cycle
1428 :type 'hook
1429 :version "26.1"
1430 :package-version '(Org . "8.3"))
1432 (defgroup org-edit-structure nil
1433 "Options concerning structure editing in Org mode."
1434 :tag "Org Edit Structure"
1435 :group 'org-structure)
1437 (defcustom org-odd-levels-only nil
1438 "Non-nil means skip even levels and only use odd levels for the outline.
1439 This has the effect that two stars are being added/taken away in
1440 promotion/demotion commands. It also influences how levels are
1441 handled by the exporters.
1442 Changing it requires restart of `font-lock-mode' to become effective
1443 for fontification also in regions already fontified.
1444 You may also set this on a per-file basis by adding one of the following
1445 lines to the buffer:
1447 #+STARTUP: odd
1448 #+STARTUP: oddeven"
1449 :group 'org-edit-structure
1450 :group 'org-appearance
1451 :type 'boolean)
1453 (defcustom org-adapt-indentation t
1454 "Non-nil means adapt indentation to outline node level.
1456 When this variable is set, Org assumes that you write outlines by
1457 indenting text in each node to align with the headline (after the
1458 stars). The following issues are influenced by this variable:
1460 - The indentation is increased by one space in a demotion
1461 command, and decreased by one in a promotion command. However,
1462 in the latter case, if shifting some line in the entry body
1463 would alter document structure (e.g., insert a new headline),
1464 indentation is not changed at all.
1466 - Property drawers and planning information is inserted indented
1467 when this variable is set. When nil, they will not be indented.
1469 - TAB indents a line relative to current level. The lines below
1470 a headline will be indented when this variable is set.
1472 Note that this is all about true indentation, by adding and
1473 removing space characters. See also \"org-indent.el\" which does
1474 level-dependent indentation in a virtual way, i.e. at display
1475 time in Emacs."
1476 :group 'org-edit-structure
1477 :type 'boolean
1478 :safe #'booleanp)
1480 (defcustom org-special-ctrl-a/e nil
1481 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1483 When t, `C-a' will bring back the cursor to the beginning of the
1484 headline text, i.e. after the stars and after a possible TODO
1485 keyword. In an item, this will be the position after bullet and
1486 check-box, if any. When the cursor is already at that position,
1487 another `C-a' will bring it to the beginning of the line.
1489 `C-e' will jump to the end of the headline, ignoring the presence
1490 of tags in the headline. A second `C-e' will then jump to the
1491 true end of the line, after any tags. This also means that, when
1492 this variable is non-nil, `C-e' also will never jump beyond the
1493 end of the heading of a folded section, i.e. not after the
1494 ellipses.
1496 When set to the symbol `reversed', the first `C-a' or `C-e' works
1497 normally, going to the true line boundary first. Only a directly
1498 following, identical keypress will bring the cursor to the
1499 special positions.
1501 This may also be a cons cell where the behavior for `C-a' and
1502 `C-e' is set separately."
1503 :group 'org-edit-structure
1504 :type '(choice
1505 (const :tag "off" nil)
1506 (const :tag "on: after stars/bullet and before tags first" t)
1507 (const :tag "reversed: true line boundary first" reversed)
1508 (cons :tag "Set C-a and C-e separately"
1509 (choice :tag "Special C-a"
1510 (const :tag "off" nil)
1511 (const :tag "on: after stars/bullet first" t)
1512 (const :tag "reversed: before stars/bullet first" reversed))
1513 (choice :tag "Special C-e"
1514 (const :tag "off" nil)
1515 (const :tag "on: before tags first" t)
1516 (const :tag "reversed: after tags first" reversed)))))
1517 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1519 (defcustom org-special-ctrl-k nil
1520 "Non-nil means `C-k' will behave specially in headlines.
1521 When nil, `C-k' will call the default `kill-line' command.
1522 When t, the following will happen while the cursor is in the headline:
1524 - When the cursor is at the beginning of a headline, kill the entire
1525 line and possible the folded subtree below the line.
1526 - When in the middle of the headline text, kill the headline up to the tags.
1527 - When after the headline text, kill the tags."
1528 :group 'org-edit-structure
1529 :type 'boolean)
1531 (defcustom org-ctrl-k-protect-subtree nil
1532 "Non-nil means, do not delete a hidden subtree with C-k.
1533 When set to the symbol `error', simply throw an error when C-k is
1534 used to kill (part-of) a headline that has hidden text behind it.
1535 Any other non-nil value will result in a query to the user, if it is
1536 OK to kill that hidden subtree. When nil, kill without remorse."
1537 :group 'org-edit-structure
1538 :version "24.1"
1539 :type '(choice
1540 (const :tag "Do not protect hidden subtrees" nil)
1541 (const :tag "Protect hidden subtrees with a security query" t)
1542 (const :tag "Never kill a hidden subtree with C-k" error)))
1544 (defcustom org-special-ctrl-o t
1545 "Non-nil means, make `C-o' insert a row in tables."
1546 :group 'org-edit-structure
1547 :type 'boolean)
1549 (defcustom org-catch-invisible-edits nil
1550 "Check if in invisible region before inserting or deleting a character.
1551 Valid values are:
1553 nil Do not check, so just do invisible edits.
1554 error Throw an error and do nothing.
1555 show Make point visible, and do the requested edit.
1556 show-and-error Make point visible, then throw an error and abort the edit.
1557 smart Make point visible, and do insertion/deletion if it is
1558 adjacent to visible text and the change feels predictable.
1559 Never delete a previously invisible character or add in the
1560 middle or right after an invisible region. Basically, this
1561 allows insertion and backward-delete right before ellipses.
1562 FIXME: maybe in this case we should not even show?"
1563 :group 'org-edit-structure
1564 :version "24.1"
1565 :type '(choice
1566 (const :tag "Do not check" nil)
1567 (const :tag "Throw error when trying to edit" error)
1568 (const :tag "Unhide, but do not do the edit" show-and-error)
1569 (const :tag "Show invisible part and do the edit" show)
1570 (const :tag "Be smart and do the right thing" smart)))
1572 (defcustom org-yank-folded-subtrees t
1573 "Non-nil means when yanking subtrees, fold them.
1574 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1575 it starts with a heading and all other headings in it are either children
1576 or siblings, then fold all the subtrees. However, do this only if no
1577 text after the yank would be swallowed into a folded tree by this action."
1578 :group 'org-edit-structure
1579 :type 'boolean)
1581 (defcustom org-yank-adjusted-subtrees nil
1582 "Non-nil means when yanking subtrees, adjust the level.
1583 With this setting, `org-paste-subtree' is used to insert the subtree, see
1584 this function for details."
1585 :group 'org-edit-structure
1586 :type 'boolean)
1588 (defcustom org-M-RET-may-split-line '((default . t))
1589 "Non-nil means M-RET will split the line at the cursor position.
1590 When nil, it will go to the end of the line before making a
1591 new line.
1592 You may also set this option in a different way for different
1593 contexts. Valid contexts are:
1595 headline when creating a new headline
1596 item when creating a new item
1597 table in a table field
1598 default the value to be used for all contexts not explicitly
1599 customized"
1600 :group 'org-structure
1601 :group 'org-table
1602 :type '(choice
1603 (const :tag "Always" t)
1604 (const :tag "Never" nil)
1605 (repeat :greedy t :tag "Individual contexts"
1606 (cons
1607 (choice :tag "Context"
1608 (const headline)
1609 (const item)
1610 (const table)
1611 (const default))
1612 (boolean)))))
1615 (defcustom org-insert-heading-respect-content nil
1616 "Non-nil means insert new headings after the current subtree.
1617 \\<org-mode-map>
1618 When nil, the new heading is created directly after the current line.
1619 The commands `\\[org-insert-heading-respect-content]' and \
1620 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1621 for the duration of the command."
1622 :group 'org-structure
1623 :type 'boolean)
1625 (defcustom org-blank-before-new-entry '((heading . auto)
1626 (plain-list-item . auto))
1627 "Should `org-insert-heading' leave a blank line before new heading/item?
1628 The value is an alist, with `heading' and `plain-list-item' as CAR,
1629 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1630 which case Org will look at the surrounding headings/items and try to
1631 make an intelligent decision whether to insert a blank line or not."
1632 :group 'org-edit-structure
1633 :type '(list
1634 (cons (const heading)
1635 (choice (const :tag "Never" nil)
1636 (const :tag "Always" t)
1637 (const :tag "Auto" auto)))
1638 (cons (const plain-list-item)
1639 (choice (const :tag "Never" nil)
1640 (const :tag "Always" t)
1641 (const :tag "Auto" auto)))))
1643 (defcustom org-insert-heading-hook nil
1644 "Hook being run after inserting a new heading."
1645 :group 'org-edit-structure
1646 :type 'hook)
1648 (defcustom org-enable-fixed-width-editor t
1649 "Non-nil means lines starting with \":\" are treated as fixed-width.
1650 This currently only means they are never auto-wrapped.
1651 When nil, such lines will be treated like ordinary lines."
1652 :group 'org-edit-structure
1653 :type 'boolean)
1655 (defgroup org-sparse-trees nil
1656 "Options concerning sparse trees in Org mode."
1657 :tag "Org Sparse Trees"
1658 :group 'org-structure)
1660 (defcustom org-highlight-sparse-tree-matches t
1661 "Non-nil means highlight all matches that define a sparse tree.
1662 The highlights will automatically disappear the next time the buffer is
1663 changed by an edit command."
1664 :group 'org-sparse-trees
1665 :type 'boolean)
1667 (defcustom org-remove-highlights-with-change t
1668 "Non-nil means any change to the buffer will remove temporary highlights.
1669 \\<org-mode-map>\
1670 Such highlights are created by `org-occur' and `org-clock-display'.
1671 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1672 to get rid of the highlights.
1673 The highlights created by `org-toggle-latex-fragment' always need
1674 `\\[org-toggle-latex-fragment]' to be removed."
1675 :group 'org-sparse-trees
1676 :group 'org-time
1677 :type 'boolean)
1679 (defcustom org-occur-case-fold-search t
1680 "Non-nil means `org-occur' should be case-insensitive.
1681 If set to `smart' the search will be case-insensitive only if it
1682 doesn't specify any upper case character."
1683 :group 'org-sparse-trees
1684 :version "26.1"
1685 :type '(choice
1686 (const :tag "Case-sensitive" nil)
1687 (const :tag "Case-insensitive" t)
1688 (const :tag "Case-insensitive for lower case searches only" smart)))
1690 (defcustom org-occur-hook '(org-first-headline-recenter)
1691 "Hook that is run after `org-occur' has constructed a sparse tree.
1692 This can be used to recenter the window to show as much of the structure
1693 as possible."
1694 :group 'org-sparse-trees
1695 :type 'hook)
1697 (defgroup org-table nil
1698 "Options concerning tables in Org mode."
1699 :tag "Org Table"
1700 :group 'org)
1702 (defcustom org-self-insert-cluster-for-undo nil
1703 "Non-nil means cluster self-insert commands for undo when possible.
1704 If this is set, then, like in the Emacs command loop, 20 consecutive
1705 characters will be undone together.
1706 This is configurable, because there is some impact on typing performance."
1707 :group 'org-table
1708 :type 'boolean)
1710 (defcustom org-table-tab-recognizes-table.el t
1711 "Non-nil means TAB will automatically notice a table.el table.
1712 When it sees such a table, it moves point into it and - if necessary -
1713 calls `table-recognize-table'."
1714 :group 'org-table-editing
1715 :type 'boolean)
1717 (defgroup org-link nil
1718 "Options concerning links in Org mode."
1719 :tag "Org Link"
1720 :group 'org)
1722 (defvar-local org-link-abbrev-alist-local nil
1723 "Buffer-local version of `org-link-abbrev-alist', which see.
1724 The value of this is taken from the #+LINK lines.")
1726 (defcustom org-link-parameters
1727 '(("doi" :follow org--open-doi-link)
1728 ("elisp" :follow org--open-elisp-link)
1729 ("file" :complete org-file-complete-link)
1730 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1731 ("help" :follow org--open-help-link)
1732 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1733 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1734 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1735 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1736 ("shell" :follow org--open-shell-link))
1737 "An alist of properties that defines all the links in Org mode.
1738 The key in each association is a string of the link type.
1739 Subsequent optional elements make up a p-list of link properties.
1741 :follow - A function that takes the link path as an argument.
1743 :export - A function that takes the link path, description and
1744 export-backend as arguments.
1746 :store - A function responsible for storing the link. See the
1747 function `org-store-link-functions'.
1749 :complete - A function that inserts a link with completion. The
1750 function takes one optional prefix arg.
1752 :face - A face for the link, or a function that returns a face.
1753 The function takes one argument which is the link path. The
1754 default face is `org-link'.
1756 :mouse-face - The mouse-face. The default is `highlight'.
1758 :display - `full' will not fold the link in descriptive
1759 display. Default is `org-link'.
1761 :help-echo - A string or function that takes (window object position)
1762 as arguments and returns a string.
1764 :keymap - A keymap that is active on the link. The default is
1765 `org-mouse-map'.
1767 :htmlize-link - A function for the htmlize-link. Defaults
1768 to (list :uri \"type:path\")
1770 :activate-func - A function to run at the end of font-lock
1771 activation. The function must accept (link-start link-end path bracketp)
1772 as arguments."
1773 :group 'org-link
1774 :type '(alist :tag "Link display parameters"
1775 :value-type plist)
1776 :version "26.1"
1777 :package-version '(Org . "9.1"))
1779 (defun org-link-get-parameter (type key)
1780 "Get TYPE link property for KEY.
1781 TYPE is a string and KEY is a plist keyword."
1782 (plist-get
1783 (cdr (assoc type org-link-parameters))
1784 key))
1786 (defun org-link-set-parameters (type &rest parameters)
1787 "Set link TYPE properties to PARAMETERS.
1788 PARAMETERS should be :key val pairs."
1789 (let ((data (assoc type org-link-parameters)))
1790 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1791 (push (cons type parameters) org-link-parameters)
1792 (org-make-link-regexps)
1793 (org-element-update-syntax))))
1795 (defun org-link-types ()
1796 "Return a list of known link types."
1797 (mapcar #'car org-link-parameters))
1799 (defcustom org-link-abbrev-alist nil
1800 "Alist of link abbreviations.
1801 The car of each element is a string, to be replaced at the start of a link.
1802 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1803 links in Org buffers can have an optional tag after a double colon, e.g.,
1805 [[linkkey:tag][description]]
1807 The `linkkey' must be a single word, starting with a letter, followed
1808 by letters, numbers, `-' or `_'.
1810 If REPLACE is a string, the tag will simply be appended to create the link.
1811 If the string contains \"%s\", the tag will be inserted there. If the string
1812 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1813 at that point (see the function `url-hexify-string'). If the string contains
1814 the specifier \"%(my-function)\", then the custom function `my-function' will
1815 be invoked: this function takes the tag as its only argument and must return
1816 a string.
1818 REPLACE may also be a function that will be called with the tag as the
1819 only argument to create the link, which should be returned as a string.
1821 See the manual for examples."
1822 :group 'org-link
1823 :type '(repeat
1824 (cons
1825 (string :tag "Protocol")
1826 (choice
1827 (string :tag "Format")
1828 (function)))))
1830 (defcustom org-descriptive-links t
1831 "Non-nil means Org will display descriptive links.
1832 E.g. [[https://orgmode.org][Org website]] will be displayed as
1833 \"Org Website\", hiding the link itself and just displaying its
1834 description. When set to nil, Org will display the full links
1835 literally.
1837 You can interactively set the value of this variable by calling
1838 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1839 :group 'org-link
1840 :type 'boolean)
1842 (defcustom org-link-file-path-type 'adaptive
1843 "How the path name in file links should be stored.
1844 Valid values are:
1846 relative Relative to the current directory, i.e. the directory of the file
1847 into which the link is being inserted.
1848 absolute Absolute path, if possible with ~ for home directory.
1849 noabbrev Absolute path, no abbreviation of home directory.
1850 adaptive Use relative path for files in the current directory and sub-
1851 directories of it. For other files, use an absolute path."
1852 :group 'org-link
1853 :type '(choice
1854 (const relative)
1855 (const absolute)
1856 (const noabbrev)
1857 (const adaptive)))
1859 (defvaralias 'org-activate-links 'org-highlight-links)
1860 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1861 "Types of links that should be highlighted in Org files.
1863 This is a list of symbols, each one of them leading to the
1864 highlighting of a certain link type.
1866 You can still open links that are not highlighted.
1868 In principle, it does not hurt to turn on highlighting for all
1869 link types. There may be a small gain when turning off unused
1870 link types. The types are:
1872 bracket The recommended [[link][description]] or [[link]] links with hiding.
1873 angle Links in angular brackets that may contain whitespace like
1874 <bbdb:Carsten Dominik>.
1875 plain Plain links in normal text, no whitespace, like http://google.com.
1876 radio Text that is matched by a radio target, see manual for details.
1877 tag Tag settings in a headline (link to tag search).
1878 date Time stamps (link to calendar).
1879 footnote Footnote labels.
1881 If you set this variable during an Emacs session, use `org-mode-restart'
1882 in the Org buffer so that the change takes effect."
1883 :group 'org-link
1884 :group 'org-appearance
1885 :type '(set :greedy t
1886 (const :tag "Double bracket links" bracket)
1887 (const :tag "Angular bracket links" angle)
1888 (const :tag "Plain text links" plain)
1889 (const :tag "Radio target matches" radio)
1890 (const :tag "Tags" tag)
1891 (const :tag "Timestamps" date)
1892 (const :tag "Footnotes" footnote)))
1894 (defcustom org-make-link-description-function nil
1895 "Function to use for generating link descriptions from links.
1896 This function must take two parameters: the first one is the
1897 link, the second one is the description generated by
1898 `org-insert-link'. The function should return the description to
1899 use."
1900 :group 'org-link
1901 :type '(choice (const nil) (function)))
1903 (defgroup org-link-store nil
1904 "Options concerning storing links in Org mode."
1905 :tag "Org Store Link"
1906 :group 'org-link)
1908 (defcustom org-url-hexify-p t
1909 "When non-nil, hexify URL when creating a link."
1910 :type 'boolean
1911 :version "24.3"
1912 :group 'org-link-store)
1914 (defcustom org-email-link-description-format "Email %c: %.30s"
1915 "Format of the description part of a link to an email or usenet message.
1916 The following %-escapes will be replaced by corresponding information:
1918 %F full \"From\" field
1919 %f name, taken from \"From\" field, address if no name
1920 %T full \"To\" field
1921 %t first name in \"To\" field, address if no name
1922 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1923 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1924 %s subject
1925 %d date
1926 %m message-id.
1928 You may use normal field width specification between the % and the letter.
1929 This is for example useful to limit the length of the subject.
1931 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1932 :group 'org-link-store
1933 :type 'string)
1935 (defcustom org-from-is-user-regexp
1936 (let (r1 r2)
1937 (when (and user-mail-address (not (string= user-mail-address "")))
1938 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1939 (when (and user-full-name (not (string= user-full-name "")))
1940 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1941 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1942 "Regexp matched against the \"From:\" header of an email or usenet message.
1943 It should match if the message is from the user him/herself."
1944 :group 'org-link-store
1945 :type 'regexp)
1947 (defcustom org-context-in-file-links t
1948 "Non-nil means file links from `org-store-link' contain context.
1949 \\<org-mode-map>
1950 A search string will be added to the file name with :: as separator
1951 and used to find the context when the link is activated by the command
1952 `org-open-at-point'. When this option is t, the entire active region
1953 will be placed in the search string of the file link. If set to a
1954 positive integer, only the first n lines of context will be stored.
1956 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1957 \\[org-store-link]')
1958 negates this setting for the duration of the command."
1959 :group 'org-link-store
1960 :type '(choice boolean integer))
1962 (defcustom org-keep-stored-link-after-insertion nil
1963 "Non-nil means keep link in list for entire session.
1964 \\<org-mode-map>
1965 The command `org-store-link' adds a link pointing to the current
1966 location to an internal list. These links accumulate during a session.
1967 The command `org-insert-link' can be used to insert links into any
1968 Org file (offering completion for all stored links).
1970 When this option is nil, every link which has been inserted once using
1971 `\\[org-insert-link]' will be removed from the list, to make completing the \
1972 unused
1973 links more efficient."
1974 :group 'org-link-store
1975 :type 'boolean)
1977 (defgroup org-link-follow nil
1978 "Options concerning following links in Org mode."
1979 :tag "Org Follow Link"
1980 :group 'org-link)
1982 (defcustom org-link-translation-function nil
1983 "Function to translate links with different syntax to Org syntax.
1984 This can be used to translate links created for example by the Planner
1985 or emacs-wiki packages to Org syntax.
1986 The function must accept two parameters, a TYPE containing the link
1987 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1988 which is everything after the link protocol. It should return a cons
1989 with possibly modified values of type and path.
1990 Org contains a function for this, so if you set this variable to
1991 `org-translate-link-from-planner', you should be able follow many
1992 links created by planner."
1993 :group 'org-link-follow
1994 :type '(choice (const nil) (function)))
1996 (defcustom org-follow-link-hook nil
1997 "Hook that is run after a link has been followed."
1998 :group 'org-link-follow
1999 :type 'hook)
2001 (defcustom org-tab-follows-link nil
2002 "Non-nil means on links TAB will follow the link.
2003 Needs to be set before org.el is loaded.
2004 This really should not be used, it does not make sense, and the
2005 implementation is bad."
2006 :group 'org-link-follow
2007 :type 'boolean)
2009 (defcustom org-return-follows-link nil
2010 "Non-nil means on links RET will follow the link.
2011 In tables, the special behavior of RET has precedence."
2012 :group 'org-link-follow
2013 :type 'boolean)
2015 (defcustom org-mouse-1-follows-link
2016 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2017 "Non-nil means mouse-1 on a link will follow the link.
2018 A longer mouse click will still set point. Needs to be set
2019 before org.el is loaded."
2020 :group 'org-link-follow
2021 :version "26.1"
2022 :package-version '(Org . "8.3")
2023 :type '(choice
2024 (const :tag "A double click follows the link" double)
2025 (const :tag "Unconditionally follow the link with mouse-1" t)
2026 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2028 (defcustom org-mark-ring-length 4
2029 "Number of different positions to be recorded in the ring.
2030 Changing this requires a restart of Emacs to work correctly."
2031 :group 'org-link-follow
2032 :type 'integer)
2034 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2035 "Non-nil means internal fuzzy links can only match headlines.
2037 When nil, the a fuzzy link may point to a target or a named
2038 construct in the document. When set to the special value
2039 `query-to-create', offer to create a new headline when none
2040 matched.
2042 Spaces and statistics cookies are ignored during heading searches."
2043 :group 'org-link-follow
2044 :version "24.1"
2045 :type '(choice
2046 (const :tag "Use fuzzy text search" nil)
2047 (const :tag "Match only exact headline" t)
2048 (const :tag "Match exact headline or query to create it"
2049 query-to-create))
2050 :safe #'symbolp)
2052 (defcustom org-link-frame-setup
2053 '((vm . vm-visit-folder-other-frame)
2054 (vm-imap . vm-visit-imap-folder-other-frame)
2055 (gnus . org-gnus-no-new-news)
2056 (file . find-file-other-window)
2057 (wl . wl-other-frame))
2058 "Setup the frame configuration for following links.
2059 When following a link with Emacs, it may often be useful to display
2060 this link in another window or frame. This variable can be used to
2061 set this up for the different types of links.
2062 For VM, use any of
2063 `vm-visit-folder'
2064 `vm-visit-folder-other-window'
2065 `vm-visit-folder-other-frame'
2066 For Gnus, use any of
2067 `gnus'
2068 `gnus-other-frame'
2069 `org-gnus-no-new-news'
2070 For FILE, use any of
2071 `find-file'
2072 `find-file-other-window'
2073 `find-file-other-frame'
2074 For Wanderlust use any of
2075 `wl'
2076 `wl-other-frame'
2077 For the calendar, use the variable `calendar-setup'.
2078 For BBDB, it is currently only possible to display the matches in
2079 another window."
2080 :group 'org-link-follow
2081 :type '(list
2082 (cons (const vm)
2083 (choice
2084 (const vm-visit-folder)
2085 (const vm-visit-folder-other-window)
2086 (const vm-visit-folder-other-frame)))
2087 (cons (const vm-imap)
2088 (choice
2089 (const vm-visit-imap-folder)
2090 (const vm-visit-imap-folder-other-window)
2091 (const vm-visit-imap-folder-other-frame)))
2092 (cons (const gnus)
2093 (choice
2094 (const gnus)
2095 (const gnus-other-frame)
2096 (const org-gnus-no-new-news)))
2097 (cons (const file)
2098 (choice
2099 (const find-file)
2100 (const find-file-other-window)
2101 (const find-file-other-frame)))
2102 (cons (const wl)
2103 (choice
2104 (const wl)
2105 (const wl-other-frame)))))
2107 (defcustom org-display-internal-link-with-indirect-buffer nil
2108 "Non-nil means use indirect buffer to display infile links.
2109 Activating internal links (from one location in a file to another location
2110 in the same file) normally just jumps to the location. When the link is
2111 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2112 is displayed in
2113 another window. When this option is set, the other window actually displays
2114 an indirect buffer clone of the current buffer, to avoid any visibility
2115 changes to the current buffer."
2116 :group 'org-link-follow
2117 :type 'boolean)
2119 (defcustom org-open-non-existing-files nil
2120 "Non-nil means `org-open-file' will open non-existing files.
2121 When nil, an error will be generated.
2122 This variable applies only to external applications because they
2123 might choke on non-existing files. If the link is to a file that
2124 will be opened in Emacs, the variable is ignored."
2125 :group 'org-link-follow
2126 :type 'boolean)
2128 (defcustom org-open-directory-means-index-dot-org nil
2129 "Non-nil means a link to a directory really means to index.org.
2130 When nil, following a directory link will run dired or open a finder/explorer
2131 window on that directory."
2132 :group 'org-link-follow
2133 :type 'boolean)
2135 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2136 "Non-nil means ask for confirmation before executing shell links.
2137 Shell links can be dangerous: just think about a link
2139 [[shell:rm -rf ~/*][Google Search]]
2141 This link would show up in your Org document as \"Google Search\",
2142 but really it would remove your entire home directory.
2143 Therefore we advise against setting this variable to nil.
2144 Just change it to `y-or-n-p' if you want to confirm with a
2145 single keystroke rather than having to type \"yes\"."
2146 :group 'org-link-follow
2147 :type '(choice
2148 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2149 (const :tag "with y-or-n (faster)" y-or-n-p)
2150 (const :tag "no confirmation (dangerous)" nil)))
2151 (put 'org-confirm-shell-link-function
2152 'safe-local-variable
2153 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2155 (defcustom org-confirm-shell-link-not-regexp ""
2156 "A regexp to skip confirmation for shell links."
2157 :group 'org-link-follow
2158 :version "24.1"
2159 :type 'regexp)
2161 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2162 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2163 Elisp links can be dangerous: just think about a link
2165 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2167 This link would show up in your Org document as \"Google Search\",
2168 but really it would remove your entire home directory.
2169 Therefore we advise against setting this variable to nil.
2170 Just change it to `y-or-n-p' if you want to confirm with a
2171 single keystroke rather than having to type \"yes\"."
2172 :group 'org-link-follow
2173 :type '(choice
2174 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2175 (const :tag "with y-or-n (faster)" y-or-n-p)
2176 (const :tag "no confirmation (dangerous)" nil)))
2177 (put 'org-confirm-shell-link-function
2178 'safe-local-variable
2179 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2181 (defcustom org-confirm-elisp-link-not-regexp ""
2182 "A regexp to skip confirmation for Elisp links."
2183 :group 'org-link-follow
2184 :version "24.1"
2185 :type 'regexp)
2187 (defconst org-file-apps-defaults-gnu
2188 '((remote . emacs)
2189 (system . mailcap)
2190 (t . mailcap))
2191 "Default file applications on a UNIX or GNU/Linux system.
2192 See `org-file-apps'.")
2194 (defconst org-file-apps-defaults-macosx
2195 '((remote . emacs)
2196 (system . "open %s")
2197 ("ps.gz" . "gv %s")
2198 ("eps.gz" . "gv %s")
2199 ("dvi" . "xdvi %s")
2200 ("fig" . "xfig %s")
2201 (t . "open %s"))
2202 "Default file applications on a macOS system.
2203 The system \"open\" is known as a default, but we use X11 applications
2204 for some files for which the OS does not have a good default.
2205 See `org-file-apps'.")
2207 (defconst org-file-apps-defaults-windowsnt
2208 (list '(remote . emacs)
2209 (cons 'system (lambda (file _path)
2210 (with-no-warnings (w32-shell-execute "open" file))))
2211 (cons t (lambda (file _path)
2212 (with-no-warnings (w32-shell-execute "open" file)))))
2213 "Default file applications on a Windows NT system.
2214 The system \"open\" is used for most files.
2215 See `org-file-apps'.")
2217 (defcustom org-file-apps
2218 '((auto-mode . emacs)
2219 ("\\.mm\\'" . default)
2220 ("\\.x?html?\\'" . default)
2221 ("\\.pdf\\'" . default))
2222 "External applications for opening `file:path' items in a document.
2223 \\<org-mode-map>\
2225 Org mode uses system defaults for different file types, but
2226 you can use this variable to set the application for a given file
2227 extension. The entries in this list are cons cells where the car identifies
2228 files and the cdr the corresponding command.
2230 Possible values for the file identifier are:
2232 \"string\" A string as a file identifier can be interpreted in different
2233 ways, depending on its contents:
2235 - Alphanumeric characters only:
2236 Match links with this file extension.
2237 Example: (\"pdf\" . \"evince %s\")
2238 to open PDFs with evince.
2240 - Regular expression: Match links where the
2241 filename matches the regexp. If you want to
2242 use groups here, use shy groups.
2244 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2245 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2246 to open *.html and *.xhtml with firefox.
2248 - Regular expression which contains (non-shy) groups:
2249 Match links where the whole link, including \"::\", and
2250 anything after that, matches the regexp.
2251 In a custom command string, %1, %2, etc. are replaced with
2252 the parts of the link that were matched by the groups.
2253 For backwards compatibility, if a command string is given
2254 that does not use any of the group matches, this case is
2255 handled identically to the second one (i.e. match against
2256 file name only).
2257 In a custom function, you can access the group matches with
2258 (match-string n link).
2260 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2261 \"evince -p %1 %s\")
2262 to open [[file:document.pdf::5]] with evince at page 5.
2264 `directory' Matches a directory
2265 `remote' Matches a remote file, accessible through tramp or efs.
2266 Remote files most likely should be visited through Emacs
2267 because external applications cannot handle such paths.
2268 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2269 so all files Emacs knows how to handle. Using this with
2270 command `emacs' will open most files in Emacs. Beware that this
2271 will also open html files inside Emacs, unless you add
2272 (\"html\" . default) to the list as well.
2273 `system' The system command to open files, like `open' on Windows
2274 and macOS, and mailcap under GNU/Linux. This is the command
2275 that will be selected if you call `org-open-at-point' with a
2276 double prefix argument (`\\[universal-argument] \
2277 \\[universal-argument] \\[org-open-at-point]').
2278 t Default for files not matched by any of the other options.
2280 Possible values for the command are:
2282 `emacs' The file will be visited by the current Emacs process.
2283 `default' Use the default application for this file type, which is the
2284 association for t in the list, most likely in the system-specific
2285 part. This can be used to overrule an unwanted setting in the
2286 system-specific variable.
2287 `system' Use the system command for opening files, like \"open\".
2288 This command is specified by the entry whose car is `system'.
2289 Most likely, the system-specific version of this variable
2290 does define this command, but you can overrule/replace it
2291 here.
2292 `mailcap' Use command specified in the mailcaps.
2293 string A command to be executed by a shell; %s will be replaced
2294 by the path to the file.
2295 function A Lisp function, which will be called with two arguments:
2296 the file path and the original link string, without the
2297 \"file:\" prefix.
2299 For more examples, see the system specific constants
2300 `org-file-apps-defaults-macosx'
2301 `org-file-apps-defaults-windowsnt'
2302 `org-file-apps-defaults-gnu'."
2303 :group 'org-link-follow
2304 :type '(repeat
2305 (cons (choice :value ""
2306 (string :tag "Extension")
2307 (const :tag "System command to open files" system)
2308 (const :tag "Default for unrecognized files" t)
2309 (const :tag "Remote file" remote)
2310 (const :tag "Links to a directory" directory)
2311 (const :tag "Any files that have Emacs modes"
2312 auto-mode))
2313 (choice :value ""
2314 (const :tag "Visit with Emacs" emacs)
2315 (const :tag "Use default" default)
2316 (const :tag "Use the system command" system)
2317 (string :tag "Command")
2318 (function :tag "Function")))))
2320 (defcustom org-doi-server-url "http://dx.doi.org/"
2321 "The URL of the DOI server."
2322 :type 'string
2323 :version "24.3"
2324 :group 'org-link-follow)
2326 (defgroup org-refile nil
2327 "Options concerning refiling entries in Org mode."
2328 :tag "Org Refile"
2329 :group 'org)
2331 (defcustom org-directory "~/org"
2332 "Directory with Org files.
2333 This is just a default location to look for Org files. There is no need
2334 at all to put your files into this directory. It is used in the
2335 following situations:
2337 1. When a capture template specifies a target file that is not an
2338 absolute path. The path will then be interpreted relative to
2339 `org-directory'
2340 2. When the value of variable `org-agenda-files' is a single file, any
2341 relative paths in this file will be taken as relative to
2342 `org-directory'."
2343 :group 'org-refile
2344 :group 'org-capture
2345 :type 'directory)
2347 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2348 "Default target for storing notes.
2349 Used as a fall back file for org-capture.el, for templates that
2350 do not specify a target file."
2351 :group 'org-refile
2352 :group 'org-capture
2353 :type 'file)
2355 (defcustom org-reverse-note-order nil
2356 "Non-nil means store new notes at the beginning of a file or entry.
2357 When nil, new notes will be filed to the end of a file or entry.
2358 This can also be a list with cons cells of regular expressions that
2359 are matched against file names, and values."
2360 :group 'org-capture
2361 :group 'org-refile
2362 :type '(choice
2363 (const :tag "Reverse always" t)
2364 (const :tag "Reverse never" nil)
2365 (repeat :tag "By file name regexp"
2366 (cons regexp boolean))))
2368 (defcustom org-log-refile nil
2369 "Information to record when a task is refiled.
2371 Possible values are:
2373 nil Don't add anything
2374 time Add a time stamp to the task
2375 note Prompt for a note and add it with template `org-log-note-headings'
2377 This option can also be set with on a per-file-basis with
2379 #+STARTUP: nologrefile
2380 #+STARTUP: logrefile
2381 #+STARTUP: lognoterefile
2383 You can have local logging settings for a subtree by setting the LOGGING
2384 property to one or more of these keywords.
2386 When bulk-refiling from the agenda, the value `note' is forbidden and
2387 will temporarily be changed to `time'."
2388 :group 'org-refile
2389 :group 'org-progress
2390 :version "24.1"
2391 :type '(choice
2392 (const :tag "No logging" nil)
2393 (const :tag "Record timestamp" time)
2394 (const :tag "Record timestamp with note." note)))
2396 (defcustom org-refile-targets nil
2397 "Targets for refiling entries with `\\[org-refile]'.
2398 This is a list of cons cells. Each cell contains:
2399 - a specification of the files to be considered, either a list of files,
2400 or a symbol whose function or variable value will be used to retrieve
2401 a file name or a list of file names. If you use `org-agenda-files' for
2402 that, all agenda files will be scanned for targets. Nil means consider
2403 headings in the current buffer.
2404 - A specification of how to find candidate refile targets. This may be
2405 any of:
2406 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2407 This tag has to be present in all target headlines, inheritance will
2408 not be considered.
2409 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2410 todo keyword.
2411 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2412 headlines that are refiling targets.
2413 - a cons cell (:level . N). Any headline of level N is considered a target.
2414 Note that, when `org-odd-levels-only' is set, level corresponds to
2415 order in hierarchy, not to the number of stars.
2416 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2417 Note that, when `org-odd-levels-only' is set, level corresponds to
2418 order in hierarchy, not to the number of stars.
2420 Each element of this list generates a set of possible targets.
2421 The union of these sets is presented (with completion) to
2422 the user by `org-refile'.
2424 You can set the variable `org-refile-target-verify-function' to a function
2425 to verify each headline found by the simple criteria above.
2427 When this variable is nil, all top-level headlines in the current buffer
2428 are used, equivalent to the value `((nil . (:level . 1))'."
2429 :group 'org-refile
2430 :type '(repeat
2431 (cons
2432 (choice :value org-agenda-files
2433 (const :tag "All agenda files" org-agenda-files)
2434 (const :tag "Current buffer" nil)
2435 (function) (variable) (file))
2436 (choice :tag "Identify target headline by"
2437 (cons :tag "Specific tag" (const :value :tag) (string))
2438 (cons :tag "TODO keyword" (const :value :todo) (string))
2439 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2440 (cons :tag "Level number" (const :value :level) (integer))
2441 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2443 (defcustom org-refile-target-verify-function nil
2444 "Function to verify if the headline at point should be a refile target.
2445 The function will be called without arguments, with point at the
2446 beginning of the headline. It should return t and leave point
2447 where it is if the headline is a valid target for refiling.
2449 If the target should not be selected, the function must return nil.
2450 In addition to this, it may move point to a place from where the search
2451 should be continued. For example, the function may decide that the entire
2452 subtree of the current entry should be excluded and move point to the end
2453 of the subtree."
2454 :group 'org-refile
2455 :type '(choice
2456 (const nil)
2457 (function)))
2459 (defcustom org-refile-use-cache nil
2460 "Non-nil means cache refile targets to speed up the process.
2461 \\<org-mode-map>\
2462 The cache for a particular file will be updated automatically when
2463 the buffer has been killed, or when any of the marker used for flagging
2464 refile targets no longer points at a live buffer.
2465 If you have added new entries to a buffer that might themselves be targets,
2466 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2467 if you find that easier, \
2468 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2469 \\[org-refile]'."
2470 :group 'org-refile
2471 :version "24.1"
2472 :type 'boolean)
2474 (defcustom org-refile-use-outline-path nil
2475 "Non-nil means provide refile targets as paths.
2476 So a level 3 headline will be available as level1/level2/level3.
2478 When the value is `file', also include the file name (without directory)
2479 into the path. In this case, you can also stop the completion after
2480 the file name, to get entries inserted as top level in the file.
2482 When `full-file-path', include the full file path.
2484 When `buffer-name', use the buffer name."
2485 :group 'org-refile
2486 :type '(choice
2487 (const :tag "Not" nil)
2488 (const :tag "Yes" t)
2489 (const :tag "Start with file name" file)
2490 (const :tag "Start with full file path" full-file-path)
2491 (const :tag "Start with buffer name" buffer-name)))
2493 (defcustom org-outline-path-complete-in-steps t
2494 "Non-nil means complete the outline path in hierarchical steps.
2495 When Org uses the refile interface to select an outline path (see
2496 `org-refile-use-outline-path'), the completion of the path can be
2497 done in a single go, or it can be done in steps down the headline
2498 hierarchy. Going in steps is probably the best if you do not use
2499 a special completion package like `ido' or `icicles'. However,
2500 when using these packages, going in one step can be very fast,
2501 while still showing the whole path to the entry."
2502 :group 'org-refile
2503 :type 'boolean)
2505 (defcustom org-refile-allow-creating-parent-nodes nil
2506 "Non-nil means allow the creation of new nodes as refile targets.
2507 New nodes are then created by adding \"/new node name\" to the completion
2508 of an existing node. When the value of this variable is `confirm',
2509 new node creation must be confirmed by the user (recommended).
2510 When nil, the completion must match an existing entry.
2512 Note that, if the new heading is not seen by the criteria
2513 listed in `org-refile-targets', multiple instances of the same
2514 heading would be created by trying again to file under the new
2515 heading."
2516 :group 'org-refile
2517 :type '(choice
2518 (const :tag "Never" nil)
2519 (const :tag "Always" t)
2520 (const :tag "Prompt for confirmation" confirm)))
2522 (defcustom org-refile-active-region-within-subtree nil
2523 "Non-nil means also refile active region within a subtree.
2525 By default `org-refile' doesn't allow refiling regions if they
2526 don't contain a set of subtrees, but it might be convenient to
2527 do so sometimes: in that case, the first line of the region is
2528 converted to a headline before refiling."
2529 :group 'org-refile
2530 :version "24.1"
2531 :type 'boolean)
2533 (defgroup org-todo nil
2534 "Options concerning TODO items in Org mode."
2535 :tag "Org TODO"
2536 :group 'org)
2538 (defgroup org-progress nil
2539 "Options concerning Progress logging in Org mode."
2540 :tag "Org Progress"
2541 :group 'org-time)
2543 (defvar org-todo-interpretation-widgets
2544 '((:tag "Sequence (cycling hits every state)" sequence)
2545 (:tag "Type (cycling directly to DONE)" type))
2546 "The available interpretation symbols for customizing `org-todo-keywords'.
2547 Interested libraries should add to this list.")
2549 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2550 "List of TODO entry keyword sequences and their interpretation.
2551 \\<org-mode-map>This is a list of sequences.
2553 Each sequence starts with a symbol, either `sequence' or `type',
2554 indicating if the keywords should be interpreted as a sequence of
2555 action steps, or as different types of TODO items. The first
2556 keywords are states requiring action - these states will select a headline
2557 for inclusion into the global TODO list Org produces. If one of the
2558 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2559 signify that no further action is necessary. If \"|\" is not found,
2560 the last keyword is treated as the only DONE state of the sequence.
2562 The command `\\[org-todo]' cycles an entry through these states, and one
2563 additional state where no keyword is present. For details about this
2564 cycling, see the manual.
2566 TODO keywords and interpretation can also be set on a per-file basis with
2567 the special #+SEQ_TODO and #+TYP_TODO lines.
2569 Each keyword can optionally specify a character for fast state selection
2570 \(in combination with the variable `org-use-fast-todo-selection')
2571 and specifiers for state change logging, using the same syntax that
2572 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2573 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2574 indicates to record a time stamp each time this state is selected.
2576 Each keyword may also specify if a timestamp or a note should be
2577 recorded when entering or leaving the state, by adding additional
2578 characters in the parenthesis after the keyword. This looks like this:
2579 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2580 record only the time of the state change. With X and Y being either
2581 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2582 Y when leaving the state if and only if the *target* state does not
2583 define X. You may omit any of the fast-selection key or X or /Y,
2584 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2586 For backward compatibility, this variable may also be just a list
2587 of keywords. In this case the interpretation (sequence or type) will be
2588 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2589 :group 'org-todo
2590 :group 'org-keywords
2591 :type '(choice
2592 (repeat :tag "Old syntax, just keywords"
2593 (string :tag "Keyword"))
2594 (repeat :tag "New syntax"
2595 (cons
2596 (choice
2597 :tag "Interpretation"
2598 ;;Quick and dirty way to see
2599 ;;`org-todo-interpretations'. This takes the
2600 ;;place of item arguments
2601 :convert-widget
2602 (lambda (widget)
2603 (widget-put widget
2604 :args (mapcar
2605 (lambda (x)
2606 (widget-convert
2607 (cons 'const x)))
2608 org-todo-interpretation-widgets))
2609 widget))
2610 (repeat
2611 (string :tag "Keyword"))))))
2613 (defvar-local org-todo-keywords-1 nil
2614 "All TODO and DONE keywords active in a buffer.")
2615 (defvar org-todo-keywords-for-agenda nil)
2616 (defvar org-done-keywords-for-agenda nil)
2617 (defvar org-todo-keyword-alist-for-agenda nil)
2618 (defvar org-tag-alist-for-agenda nil
2619 "Alist of all tags from all agenda files.")
2620 (defvar org-tag-groups-alist-for-agenda nil
2621 "Alist of all groups tags from all current agenda files.")
2622 (defvar-local org-tag-groups-alist nil)
2623 (defvar org-agenda-contributing-files nil)
2624 (defvar-local org-current-tag-alist nil
2625 "Alist of all tag groups in current buffer.
2626 This variable takes into consideration `org-tag-alist',
2627 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2628 (defvar-local org-not-done-keywords nil)
2629 (defvar-local org-done-keywords nil)
2630 (defvar-local org-todo-heads nil)
2631 (defvar-local org-todo-sets nil)
2632 (defvar-local org-todo-log-states nil)
2633 (defvar-local org-todo-kwd-alist nil)
2634 (defvar-local org-todo-key-alist nil)
2635 (defvar-local org-todo-key-trigger nil)
2637 (defcustom org-todo-interpretation 'sequence
2638 "Controls how TODO keywords are interpreted.
2639 This variable is in principle obsolete and is only used for
2640 backward compatibility, if the interpretation of todo keywords is
2641 not given already in `org-todo-keywords'. See that variable for
2642 more information."
2643 :group 'org-todo
2644 :group 'org-keywords
2645 :type '(choice (const sequence)
2646 (const type)))
2648 (defcustom org-use-fast-todo-selection t
2649 "\\<org-mode-map>\
2650 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2651 This variable describes if and under what circumstances the cycling
2652 mechanism for TODO keywords will be replaced by a single-key, direct
2653 selection scheme.
2655 When nil, fast selection is never used.
2657 When the symbol `prefix', it will be used when `org-todo' is called
2658 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2659 in an Org buffer, and
2660 `\\[universal-argument] t' in an agenda buffer.
2662 When t, fast selection is used by default. In this case, the prefix
2663 argument forces cycling instead.
2665 In all cases, the special interface is only used if access keys have
2666 actually been assigned by the user, i.e. if keywords in the configuration
2667 are followed by a letter in parenthesis, like TODO(t)."
2668 :group 'org-todo
2669 :type '(choice
2670 (const :tag "Never" nil)
2671 (const :tag "By default" t)
2672 (const :tag "Only with C-u C-c C-t" prefix)))
2674 (defcustom org-provide-todo-statistics t
2675 "Non-nil means update todo statistics after insert and toggle.
2676 ALL-HEADLINES means update todo statistics by including headlines
2677 with no TODO keyword as well, counting them as not done.
2678 A list of TODO keywords means the same, but skip keywords that are
2679 not in this list.
2680 When set to a list of two lists, the first list contains keywords
2681 to consider as TODO keywords, the second list contains keywords
2682 to consider as DONE keywords.
2684 When this is set, todo statistics is updated in the parent of the
2685 current entry each time a todo state is changed."
2686 :group 'org-todo
2687 :type '(choice
2688 (const :tag "Yes, only for TODO entries" t)
2689 (const :tag "Yes, including all entries" all-headlines)
2690 (repeat :tag "Yes, for TODOs in this list"
2691 (string :tag "TODO keyword"))
2692 (list :tag "Yes, for TODOs and DONEs in these lists"
2693 (repeat (string :tag "TODO keyword"))
2694 (repeat (string :tag "DONE keyword")))
2695 (other :tag "No TODO statistics" nil)))
2697 (defcustom org-hierarchical-todo-statistics t
2698 "Non-nil means TODO statistics covers just direct children.
2699 When nil, all entries in the subtree are considered.
2700 This has only an effect if `org-provide-todo-statistics' is set.
2701 To set this to nil for only a single subtree, use a COOKIE_DATA
2702 property and include the word \"recursive\" into the value."
2703 :group 'org-todo
2704 :type 'boolean)
2706 (defcustom org-after-todo-state-change-hook nil
2707 "Hook which is run after the state of a TODO item was changed.
2708 The new state (a string with a TODO keyword, or nil) is available in the
2709 Lisp variable `org-state'."
2710 :group 'org-todo
2711 :type 'hook)
2713 (defvar org-blocker-hook nil
2714 "Hook for functions that are allowed to block a state change.
2716 Functions in this hook should not modify the buffer.
2717 Each function gets as its single argument a property list,
2718 see `org-trigger-hook' for more information about this list.
2720 If any of the functions in this hook returns nil, the state change
2721 is blocked.")
2723 (defvar org-trigger-hook nil
2724 "Hook for functions that are triggered by a state change.
2726 Each function gets as its single argument a property list with at
2727 least the following elements:
2729 (:type type-of-change :position pos-at-entry-start
2730 :from old-state :to new-state)
2732 Depending on the type, more properties may be present.
2734 This mechanism is currently implemented for:
2736 TODO state changes
2737 ------------------
2738 :type todo-state-change
2739 :from previous state (keyword as a string), or nil, or a symbol
2740 `todo' or `done', to indicate the general type of state.
2741 :to new state, like in :from")
2743 (defcustom org-enforce-todo-dependencies nil
2744 "Non-nil means undone TODO entries will block switching the parent to DONE.
2745 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2746 be blocked if any prior sibling is not yet done.
2747 Finally, if the parent is blocked because of ordered siblings of its own,
2748 the child will also be blocked."
2749 :set (lambda (var val)
2750 (set var val)
2751 (if val
2752 (add-hook 'org-blocker-hook
2753 'org-block-todo-from-children-or-siblings-or-parent)
2754 (remove-hook 'org-blocker-hook
2755 'org-block-todo-from-children-or-siblings-or-parent)))
2756 :group 'org-todo
2757 :type 'boolean)
2759 (defcustom org-enforce-todo-checkbox-dependencies nil
2760 "Non-nil means unchecked boxes will block switching the parent to DONE.
2761 When this is nil, checkboxes have no influence on switching TODO states.
2762 When non-nil, you first need to check off all check boxes before the TODO
2763 entry can be switched to DONE.
2764 This variable needs to be set before org.el is loaded, and you need to
2765 restart Emacs after a change to make the change effective. The only way
2766 to change is while Emacs is running is through the customize interface."
2767 :set (lambda (var val)
2768 (set var val)
2769 (if val
2770 (add-hook 'org-blocker-hook
2771 'org-block-todo-from-checkboxes)
2772 (remove-hook 'org-blocker-hook
2773 'org-block-todo-from-checkboxes)))
2774 :group 'org-todo
2775 :type 'boolean)
2777 (defcustom org-treat-insert-todo-heading-as-state-change nil
2778 "Non-nil means inserting a TODO heading is treated as state change.
2779 So when the command `\\[org-insert-todo-heading]' is used, state change
2780 logging will apply if appropriate. When nil, the new TODO item will
2781 be inserted directly, and no logging will take place."
2782 :group 'org-todo
2783 :type 'boolean)
2785 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2786 "Non-nil means switching TODO states with S-cursor counts as state change.
2787 This is the default behavior. However, setting this to nil allows a
2788 convenient way to select a TODO state and bypass any logging associated
2789 with that."
2790 :group 'org-todo
2791 :type 'boolean)
2793 (defcustom org-todo-state-tags-triggers nil
2794 "Tag changes that should be triggered by TODO state changes.
2795 This is a list. Each entry is
2797 (state-change (tag . flag) .......)
2799 State-change can be a string with a state, and empty string to indicate the
2800 state that has no TODO keyword, or it can be one of the symbols `todo'
2801 or `done', meaning any not-done or done state, respectively."
2802 :group 'org-todo
2803 :group 'org-tags
2804 :type '(repeat
2805 (cons (choice :tag "When changing to"
2806 (const :tag "Not-done state" todo)
2807 (const :tag "Done state" done)
2808 (string :tag "State"))
2809 (repeat
2810 (cons :tag "Tag action"
2811 (string :tag "Tag")
2812 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2814 (defcustom org-log-done nil
2815 "Information to record when a task moves to the DONE state.
2817 Possible values are:
2819 nil Don't add anything, just change the keyword
2820 time Add a time stamp to the task
2821 note Prompt for a note and add it with template `org-log-note-headings'
2823 This option can also be set with on a per-file-basis with
2825 #+STARTUP: nologdone
2826 #+STARTUP: logdone
2827 #+STARTUP: lognotedone
2829 You can have local logging settings for a subtree by setting the LOGGING
2830 property to one or more of these keywords."
2831 :group 'org-todo
2832 :group 'org-progress
2833 :type '(choice
2834 (const :tag "No logging" nil)
2835 (const :tag "Record CLOSED timestamp" time)
2836 (const :tag "Record CLOSED timestamp with note." note)))
2838 ;; Normalize old uses of org-log-done.
2839 (cond
2840 ((eq org-log-done t) (setq org-log-done 'time))
2841 ((and (listp org-log-done) (memq 'done org-log-done))
2842 (setq org-log-done 'note)))
2844 (defcustom org-log-reschedule nil
2845 "Information to record when the scheduling date of a tasks is modified.
2847 Possible values are:
2849 nil Don't add anything, just change the date
2850 time Add a time stamp to the task
2851 note Prompt for a note and add it with template `org-log-note-headings'
2853 This option can also be set with on a per-file-basis with
2855 #+STARTUP: nologreschedule
2856 #+STARTUP: logreschedule
2857 #+STARTUP: lognotereschedule"
2858 :group 'org-todo
2859 :group 'org-progress
2860 :type '(choice
2861 (const :tag "No logging" nil)
2862 (const :tag "Record timestamp" time)
2863 (const :tag "Record timestamp with note." note)))
2865 (defcustom org-log-redeadline nil
2866 "Information to record when the deadline date of a tasks is modified.
2868 Possible values are:
2870 nil Don't add anything, just change the date
2871 time Add a time stamp to the task
2872 note Prompt for a note and add it with template `org-log-note-headings'
2874 This option can also be set with on a per-file-basis with
2876 #+STARTUP: nologredeadline
2877 #+STARTUP: logredeadline
2878 #+STARTUP: lognoteredeadline
2880 You can have local logging settings for a subtree by setting the LOGGING
2881 property to one or more of these keywords."
2882 :group 'org-todo
2883 :group 'org-progress
2884 :type '(choice
2885 (const :tag "No logging" nil)
2886 (const :tag "Record timestamp" time)
2887 (const :tag "Record timestamp with note." note)))
2889 (defcustom org-log-note-clock-out nil
2890 "Non-nil means record a note when clocking out of an item.
2891 This can also be configured on a per-file basis by adding one of
2892 the following lines anywhere in the buffer:
2894 #+STARTUP: lognoteclock-out
2895 #+STARTUP: nolognoteclock-out"
2896 :group 'org-todo
2897 :group 'org-progress
2898 :type 'boolean)
2900 (defcustom org-log-done-with-time t
2901 "Non-nil means the CLOSED time stamp will contain date and time.
2902 When nil, only the date will be recorded."
2903 :group 'org-progress
2904 :type 'boolean)
2906 (defcustom org-log-note-headings
2907 '((done . "CLOSING NOTE %t")
2908 (state . "State %-12s from %-12S %t")
2909 (note . "Note taken on %t")
2910 (reschedule . "Rescheduled from %S on %t")
2911 (delschedule . "Not scheduled, was %S on %t")
2912 (redeadline . "New deadline from %S on %t")
2913 (deldeadline . "Removed deadline, was %S on %t")
2914 (refile . "Refiled on %t")
2915 (clock-out . ""))
2916 "Headings for notes added to entries.
2918 The value is an alist, with the car being a symbol indicating the
2919 note context, and the cdr is the heading to be used. The heading
2920 may also be the empty string. The following placeholders can be
2921 used:
2923 %t a time stamp.
2924 %T an active time stamp instead the default inactive one
2925 %d a short-format time stamp.
2926 %D an active short-format time stamp.
2927 %s the new TODO state or time stamp (inactive), in double quotes.
2928 %S the old TODO state or time stamp (inactive), in double quotes.
2929 %u the user name.
2930 %U full user name.
2932 In fact, it is not a good idea to change the `state' entry,
2933 because Agenda Log mode depends on the format of these entries."
2934 :group 'org-todo
2935 :group 'org-progress
2936 :type '(list :greedy t
2937 (cons (const :tag "Heading when closing an item" done) string)
2938 (cons (const :tag
2939 "Heading when changing todo state (todo sequence only)"
2940 state) string)
2941 (cons (const :tag "Heading when just taking a note" note) string)
2942 (cons (const :tag "Heading when rescheduling" reschedule) string)
2943 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2944 (cons (const :tag "Heading when changing deadline" redeadline) string)
2945 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2946 (cons (const :tag "Heading when refiling" refile) string)
2947 (cons (const :tag "Heading when clocking out" clock-out) string)))
2949 (unless (assq 'note org-log-note-headings)
2950 (push '(note . "%t") org-log-note-headings))
2952 (defcustom org-log-into-drawer nil
2953 "Non-nil means insert state change notes and time stamps into a drawer.
2954 When nil, state changes notes will be inserted after the headline and
2955 any scheduling and clock lines, but not inside a drawer.
2957 The value of this variable should be the name of the drawer to use.
2958 LOGBOOK is proposed as the default drawer for this purpose, you can
2959 also set this to a string to define the drawer of your choice.
2961 A value of t is also allowed, representing \"LOGBOOK\".
2963 A value of t or nil can also be set with on a per-file-basis with
2965 #+STARTUP: logdrawer
2966 #+STARTUP: nologdrawer
2968 If this variable is set, `org-log-state-notes-insert-after-drawers'
2969 will be ignored.
2971 You can set the property LOG_INTO_DRAWER to overrule this setting for
2972 a subtree.
2974 Do not check directly this variable in a Lisp program. Call
2975 function `org-log-into-drawer' instead."
2976 :group 'org-todo
2977 :group 'org-progress
2978 :type '(choice
2979 (const :tag "Not into a drawer" nil)
2980 (const :tag "LOGBOOK" t)
2981 (string :tag "Other")))
2983 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2985 (defun org-log-into-drawer ()
2986 "Name of the log drawer, as a string, or nil.
2987 This is the value of `org-log-into-drawer'. However, if the
2988 current entry has or inherits a LOG_INTO_DRAWER property, it will
2989 be used instead of the default value."
2990 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2991 (cond ((equal p "nil") nil)
2992 ((equal p "t") "LOGBOOK")
2993 ((stringp p) p)
2994 (p "LOGBOOK")
2995 ((stringp org-log-into-drawer) org-log-into-drawer)
2996 (org-log-into-drawer "LOGBOOK"))))
2998 (defcustom org-log-state-notes-insert-after-drawers nil
2999 "Non-nil means insert state change notes after any drawers in entry.
3000 Only the drawers that *immediately* follow the headline and the
3001 deadline/scheduled line are skipped.
3002 When nil, insert notes right after the heading and perhaps the line
3003 with deadline/scheduling if present.
3005 This variable will have no effect if `org-log-into-drawer' is
3006 set."
3007 :group 'org-todo
3008 :group 'org-progress
3009 :type 'boolean)
3011 (defcustom org-log-states-order-reversed t
3012 "Non-nil means the latest state note will be directly after heading.
3013 When nil, the state change notes will be ordered according to time.
3015 This option can also be set with on a per-file-basis with
3017 #+STARTUP: logstatesreversed
3018 #+STARTUP: nologstatesreversed"
3019 :group 'org-todo
3020 :group 'org-progress
3021 :type 'boolean)
3023 (defcustom org-todo-repeat-to-state nil
3024 "The TODO state to which a repeater should return the repeating task.
3025 By default this is the first task of a TODO sequence or the
3026 previous state of a TYPE_TODO set. But you can specify to use
3027 the previous state in a TODO sequence or a string.
3029 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3030 entry, which has precedence over this option."
3031 :group 'org-todo
3032 :version "24.1"
3033 :type '(choice (const :tag "Use the previous TODO state" t)
3034 (const :tag "Use the head of the TODO sequence" nil)
3035 (string :tag "Use a specific TODO state")))
3037 (defcustom org-log-repeat 'time
3038 "Non-nil means record moving through the DONE state when triggering repeat.
3039 An auto-repeating task is immediately switched back to TODO when
3040 marked DONE. If you are not logging state changes (by adding \"@\"
3041 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3042 record a closing note, there will be no record of the task moving
3043 through DONE. This variable forces taking a note anyway.
3045 nil Don't force a record
3046 time Record a time stamp
3047 note Prompt for a note and add it with template `org-log-note-headings'
3049 This option can also be set with on a per-file-basis with
3051 #+STARTUP: nologrepeat
3052 #+STARTUP: logrepeat
3053 #+STARTUP: lognoterepeat
3055 You can have local logging settings for a subtree by setting the LOGGING
3056 property to one or more of these keywords."
3057 :group 'org-todo
3058 :group 'org-progress
3059 :type '(choice
3060 (const :tag "Don't force a record" nil)
3061 (const :tag "Force recording the DONE state" time)
3062 (const :tag "Force recording a note with the DONE state" note)))
3065 (defgroup org-priorities nil
3066 "Priorities in Org mode."
3067 :tag "Org Priorities"
3068 :group 'org-todo)
3070 (defcustom org-enable-priority-commands t
3071 "Non-nil means priority commands are active.
3072 When nil, these commands will be disabled, so that you never accidentally
3073 set a priority."
3074 :group 'org-priorities
3075 :type 'boolean)
3077 (defcustom org-highest-priority ?A
3078 "The highest priority of TODO items. A character like ?A, ?B etc.
3079 Must have a smaller ASCII number than `org-lowest-priority'."
3080 :group 'org-priorities
3081 :type 'character)
3083 (defcustom org-lowest-priority ?C
3084 "The lowest priority of TODO items. A character like ?A, ?B etc.
3085 Must have a larger ASCII number than `org-highest-priority'."
3086 :group 'org-priorities
3087 :type 'character)
3089 (defcustom org-default-priority ?B
3090 "The default priority of TODO items.
3091 This is the priority an item gets if no explicit priority is given.
3092 When starting to cycle on an empty priority the first step in the cycle
3093 depends on `org-priority-start-cycle-with-default'. The resulting first
3094 step priority must not exceed the range from `org-highest-priority' to
3095 `org-lowest-priority' which means that `org-default-priority' has to be
3096 in this range exclusive or inclusive the range boundaries. Else the
3097 first step refuses to set the default and the second will fall back
3098 to (depending on the command used) the highest or lowest priority."
3099 :group 'org-priorities
3100 :type 'character)
3102 (defcustom org-priority-start-cycle-with-default t
3103 "Non-nil means start with default priority when starting to cycle.
3104 When this is nil, the first step in the cycle will be (depending on the
3105 command used) one higher or lower than the default priority.
3106 See also `org-default-priority'."
3107 :group 'org-priorities
3108 :type 'boolean)
3110 (defcustom org-get-priority-function nil
3111 "Function to extract the priority from a string.
3112 The string is normally the headline. If this is nil Org computes the
3113 priority from the priority cookie like [#A] in the headline. It returns
3114 an integer, increasing by 1000 for each priority level.
3115 The user can set a different function here, which should take a string
3116 as an argument and return the numeric priority."
3117 :group 'org-priorities
3118 :version "24.1"
3119 :type '(choice
3120 (const nil)
3121 (function)))
3123 (defgroup org-time nil
3124 "Options concerning time stamps and deadlines in Org mode."
3125 :tag "Org Time"
3126 :group 'org)
3128 (defcustom org-time-stamp-rounding-minutes '(0 5)
3129 "Number of minutes to round time stamps to.
3130 \\<org-mode-map>\
3131 These are two values, the first applies when first creating a time stamp.
3132 The second applies when changing it with the commands `S-up' and `S-down'.
3133 When changing the time stamp, this means that it will change in steps
3134 of N minutes, as given by the second value.
3136 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3137 numbers should be factors of 60, so for example 5, 10, 15.
3139 When this is larger than 1, you can still force an exact time stamp by using
3140 a double prefix argument to a time stamp command like \
3141 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3142 and by using a prefix arg to `S-up/down' to specify the exact number
3143 of minutes to shift."
3144 :group 'org-time
3145 :get (lambda (var) ; Make sure both elements are there
3146 (if (integerp (default-value var))
3147 (list (default-value var) 5)
3148 (default-value var)))
3149 :type '(list
3150 (integer :tag "when inserting times")
3151 (integer :tag "when modifying times")))
3153 ;; Normalize old customizations of this variable.
3154 (when (integerp org-time-stamp-rounding-minutes)
3155 (setq org-time-stamp-rounding-minutes
3156 (list org-time-stamp-rounding-minutes
3157 org-time-stamp-rounding-minutes)))
3159 (defcustom org-display-custom-times nil
3160 "Non-nil means overlay custom formats over all time stamps.
3161 The formats are defined through the variable `org-time-stamp-custom-formats'.
3162 To turn this on on a per-file basis, insert anywhere in the file:
3163 #+STARTUP: customtime"
3164 :group 'org-time
3165 :set 'set-default
3166 :type 'sexp)
3167 (make-variable-buffer-local 'org-display-custom-times)
3169 (defcustom org-time-stamp-custom-formats
3170 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3171 "Custom formats for time stamps. See `format-time-string' for the syntax.
3172 These are overlaid over the default ISO format if the variable
3173 `org-display-custom-times' is set. Time like %H:%M should be at the
3174 end of the second format. The custom formats are also honored by export
3175 commands, if custom time display is turned on at the time of export."
3176 :group 'org-time
3177 :type 'sexp)
3179 (defun org-time-stamp-format (&optional long inactive)
3180 "Get the right format for a time string."
3181 (let ((f (if long (cdr org-time-stamp-formats)
3182 (car org-time-stamp-formats))))
3183 (if inactive
3184 (concat "[" (substring f 1 -1) "]")
3185 f)))
3187 (defcustom org-deadline-warning-days 14
3188 "Number of days before expiration during which a deadline becomes active.
3189 This variable governs the display in sparse trees and in the agenda.
3190 When 0 or negative, it means use this number (the absolute value of it)
3191 even if a deadline has a different individual lead time specified.
3193 Custom commands can set this variable in the options section."
3194 :group 'org-time
3195 :group 'org-agenda-daily/weekly
3196 :type 'integer)
3198 (defcustom org-scheduled-delay-days 0
3199 "Number of days before a scheduled item becomes active.
3200 This variable governs the display in sparse trees and in the agenda.
3201 The default value (i.e. 0) means: don't delay scheduled item.
3202 When negative, it means use this number (the absolute value of it)
3203 even if a scheduled item has a different individual delay time
3204 specified.
3206 Custom commands can set this variable in the options section."
3207 :group 'org-time
3208 :group 'org-agenda-daily/weekly
3209 :version "24.4"
3210 :package-version '(Org . "8.0")
3211 :type 'integer)
3213 (defcustom org-read-date-prefer-future t
3214 "Non-nil means assume future for incomplete date input from user.
3215 This affects the following situations:
3216 1. The user gives a month but not a year.
3217 For example, if it is April and you enter \"feb 2\", this will be read
3218 as Feb 2, *next* year. \"May 5\", however, will be this year.
3219 2. The user gives a day, but no month.
3220 For example, if today is the 15th, and you enter \"3\", Org will read
3221 this as the third of *next* month. However, if you enter \"17\",
3222 it will be considered as *this* month.
3224 If you set this variable to the symbol `time', then also the following
3225 will work:
3227 3. If the user gives a time.
3228 If the time is before now, it will be interpreted as tomorrow.
3230 Currently none of this works for ISO week specifications.
3232 When this option is nil, the current day, month and year will always be
3233 used as defaults.
3235 See also `org-agenda-jump-prefer-future'."
3236 :group 'org-time
3237 :type '(choice
3238 (const :tag "Never" nil)
3239 (const :tag "Check month and day" t)
3240 (const :tag "Check month, day, and time" time)))
3242 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3243 "Should the agenda jump command prefer the future for incomplete dates?
3244 The default is to do the same as configured in `org-read-date-prefer-future'.
3245 But you can also set a deviating value here.
3246 This may t or nil, or the symbol `org-read-date-prefer-future'."
3247 :group 'org-agenda
3248 :group 'org-time
3249 :version "24.1"
3250 :type '(choice
3251 (const :tag "Use org-read-date-prefer-future"
3252 org-read-date-prefer-future)
3253 (const :tag "Never" nil)
3254 (const :tag "Always" t)))
3256 (defcustom org-read-date-force-compatible-dates t
3257 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3259 Depending on the system Emacs is running on, certain dates cannot
3260 be represented with the type used internally to represent time.
3261 Dates between 1970-1-1 and 2038-1-1 can always be represented
3262 correctly. Some systems allow for earlier dates, some for later,
3263 some for both. One way to find out it to insert any date into an
3264 Org buffer, putting the cursor on the year and hitting S-up and
3265 S-down to test the range.
3267 When this variable is set to t, the date/time prompt will not let
3268 you specify dates outside the 1970-2037 range, so it is certain that
3269 these dates will work in whatever version of Emacs you are
3270 running, and also that you can move a file from one Emacs implementation
3271 to another. WHenever Org is forcing the year for you, it will display
3272 a message and beep.
3274 When this variable is nil, Org will check if the date is
3275 representable in the specific Emacs implementation you are using.
3276 If not, it will force a year, usually the current year, and beep
3277 to remind you. Currently this setting is not recommended because
3278 the likelihood that you will open your Org files in an Emacs that
3279 has limited date range is not negligible.
3281 A workaround for this problem is to use diary sexp dates for time
3282 stamps outside of this range."
3283 :group 'org-time
3284 :version "24.1"
3285 :type 'boolean)
3287 (defcustom org-read-date-display-live t
3288 "Non-nil means display current interpretation of date prompt live.
3289 This display will be in an overlay, in the minibuffer."
3290 :group 'org-time
3291 :type 'boolean)
3293 (defcustom org-read-date-popup-calendar t
3294 "Non-nil means pop up a calendar when prompting for a date.
3295 In the calendar, the date can be selected with mouse-1. However, the
3296 minibuffer will also be active, and you can simply enter the date as well.
3297 When nil, only the minibuffer will be available."
3298 :group 'org-time
3299 :type 'boolean)
3300 (defvaralias 'org-popup-calendar-for-date-prompt
3301 'org-read-date-popup-calendar)
3303 (defcustom org-extend-today-until 0
3304 "The hour when your day really ends. Must be an integer.
3305 This has influence for the following applications:
3306 - When switching the agenda to \"today\". It it is still earlier than
3307 the time given here, the day recognized as TODAY is actually yesterday.
3308 - When a date is read from the user and it is still before the time given
3309 here, the current date and time will be assumed to be yesterday, 23:59.
3310 Also, timestamps inserted in capture templates follow this rule.
3312 IMPORTANT: This is a feature whose implementation is and likely will
3313 remain incomplete. Really, it is only here because past midnight seems to
3314 be the favorite working time of John Wiegley :-)"
3315 :group 'org-time
3316 :type 'integer)
3318 (defcustom org-use-effective-time nil
3319 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3320 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3321 \"effective time\" of any timestamps between midnight and 8am will be
3322 23:59 of the previous day."
3323 :group 'org-time
3324 :version "24.1"
3325 :type 'boolean)
3327 (defcustom org-use-last-clock-out-time-as-effective-time nil
3328 "When non-nil, use the last clock out time for `org-todo'.
3329 Note that this option has precedence over the combined use of
3330 `org-use-effective-time' and `org-extend-today-until'."
3331 :group 'org-time
3332 :version "24.4"
3333 :package-version '(Org . "8.0")
3334 :type 'boolean)
3336 (defcustom org-edit-timestamp-down-means-later nil
3337 "Non-nil means S-down will increase the time in a time stamp.
3338 When nil, S-up will increase."
3339 :group 'org-time
3340 :type 'boolean)
3342 (defcustom org-calendar-follow-timestamp-change t
3343 "Non-nil means make the calendar window follow timestamp changes.
3344 When a timestamp is modified and the calendar window is visible, it will be
3345 moved to the new date."
3346 :group 'org-time
3347 :type 'boolean)
3349 (defgroup org-tags nil
3350 "Options concerning tags in Org mode."
3351 :tag "Org Tags"
3352 :group 'org)
3354 (defcustom org-tag-alist nil
3355 "Default tags available in Org files.
3357 The value of this variable is an alist. Associations either:
3359 (TAG)
3360 (TAG . SELECT)
3361 (SPECIAL)
3363 where TAG is a tag as a string, SELECT is character, used to
3364 select that tag through the fast tag selection interface, and
3365 SPECIAL is one of the following keywords: `:startgroup',
3366 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3367 `:newline'. These keywords are used to define a hierarchy of
3368 tags. See manual for details.
3370 When this variable is nil, Org mode bases tag input on what is
3371 already in the buffer. The value can be overridden locally by
3372 using a TAGS keyword, e.g.,
3374 #+TAGS: tag1 tag2
3376 See also `org-tag-persistent-alist' to sidestep this behavior."
3377 :group 'org-tags
3378 :type '(repeat
3379 (choice
3380 (cons :tag "Tag with key"
3381 (string :tag "Tag name")
3382 (character :tag "Access char"))
3383 (list :tag "Tag" (string :tag "Tag name"))
3384 (const :tag "Start radio group" (:startgroup))
3385 (const :tag "Start tag group, non distinct" (:startgrouptag))
3386 (const :tag "Group tags delimiter" (:grouptags))
3387 (const :tag "End radio group" (:endgroup))
3388 (const :tag "End tag group, non distinct" (:endgrouptag))
3389 (const :tag "New line" (:newline)))))
3391 (defcustom org-tag-persistent-alist nil
3392 "Tags always available in Org files.
3394 The value of this variable is an alist. Associations either:
3396 (TAG)
3397 (TAG . SELECT)
3398 (SPECIAL)
3400 where TAG is a tag as a string, SELECT is a character, used to
3401 select that tag through the fast tag selection interface, and
3402 SPECIAL is one of the following keywords: `:startgroup',
3403 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3404 `:newline'. These keywords are used to define a hierarchy of
3405 tags. See manual for details.
3407 Unlike to `org-tag-alist', tags defined in this variable do not
3408 depend on a local TAGS keyword. Instead, to disable these tags
3409 on a per-file basis, insert anywhere in the file:
3411 #+STARTUP: noptag"
3412 :group 'org-tags
3413 :type '(repeat
3414 (choice
3415 (cons :tag "Tag with key"
3416 (string :tag "Tag name")
3417 (character :tag "Access char"))
3418 (list :tag "Tag" (string :tag "Tag name"))
3419 (const :tag "Start radio group" (:startgroup))
3420 (const :tag "Start tag group, non distinct" (:startgrouptag))
3421 (const :tag "Group tags delimiter" (:grouptags))
3422 (const :tag "End radio group" (:endgroup))
3423 (const :tag "End tag group, non distinct" (:endgrouptag))
3424 (const :tag "New line" (:newline)))))
3426 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3427 "If non-nil, always offer completion for all tags of all agenda files.
3428 Instead of customizing this variable directly, you might want to
3429 set it locally for capture buffers, because there no list of
3430 tags in that file can be created dynamically (there are none).
3432 (add-hook \\='org-capture-mode-hook
3433 (lambda ()
3434 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3435 :group 'org-tags
3436 :version "24.1"
3437 :type 'boolean)
3439 (defvar org-file-tags nil
3440 "List of tags that can be inherited by all entries in the file.
3441 The tags will be inherited if the variable `org-use-tag-inheritance'
3442 says they should be.
3443 This variable is populated from #+FILETAGS lines.")
3445 (defcustom org-use-fast-tag-selection 'auto
3446 "Non-nil means use fast tag selection scheme.
3447 This is a special interface to select and deselect tags with single keys.
3448 When nil, fast selection is never used.
3449 When the symbol `auto', fast selection is used if and only if selection
3450 characters for tags have been configured, either through the variable
3451 `org-tag-alist' or through a #+TAGS line in the buffer.
3452 When t, fast selection is always used and selection keys are assigned
3453 automatically if necessary."
3454 :group 'org-tags
3455 :type '(choice
3456 (const :tag "Always" t)
3457 (const :tag "Never" nil)
3458 (const :tag "When selection characters are configured" auto)))
3460 (defcustom org-fast-tag-selection-single-key nil
3461 "Non-nil means fast tag selection exits after first change.
3462 When nil, you have to press RET to exit it.
3463 During fast tag selection, you can toggle this flag with `C-c'.
3464 This variable can also have the value `expert'. In this case, the window
3465 displaying the tags menu is not even shown, until you press C-c again."
3466 :group 'org-tags
3467 :type '(choice
3468 (const :tag "No" nil)
3469 (const :tag "Yes" t)
3470 (const :tag "Expert" expert)))
3472 (defvar org-fast-tag-selection-include-todo nil
3473 "Non-nil means fast tags selection interface will also offer TODO states.
3474 This is an undocumented feature, you should not rely on it.")
3476 (defcustom org-tags-column -77
3477 "The column to which tags should be indented in a headline.
3478 If this number is positive, it specifies the column. If it is negative,
3479 it means that the tags should be flushright to that column. For example,
3480 -80 works well for a normal 80 character screen.
3481 When 0, place tags directly after headline text, with only one space in
3482 between."
3483 :group 'org-tags
3484 :type 'integer)
3486 (defcustom org-auto-align-tags t
3487 "Non-nil keeps tags aligned when modifying headlines.
3488 Some operations (i.e. demoting) change the length of a headline and
3489 therefore shift the tags around. With this option turned on, after
3490 each such operation the tags are again aligned to `org-tags-column'."
3491 :group 'org-tags
3492 :type 'boolean)
3494 (defcustom org-use-tag-inheritance t
3495 "Non-nil means tags in levels apply also for sublevels.
3496 When nil, only the tags directly given in a specific line apply there.
3497 This may also be a list of tags that should be inherited, or a regexp that
3498 matches tags that should be inherited. Additional control is possible
3499 with the variable `org-tags-exclude-from-inheritance' which gives an
3500 explicit list of tags to be excluded from inheritance, even if the value of
3501 `org-use-tag-inheritance' would select it for inheritance.
3503 If this option is t, a match early-on in a tree can lead to a large
3504 number of matches in the subtree when constructing the agenda or creating
3505 a sparse tree. If you only want to see the first match in a tree during
3506 a search, check out the variable `org-tags-match-list-sublevels'."
3507 :group 'org-tags
3508 :type '(choice
3509 (const :tag "Not" nil)
3510 (const :tag "Always" t)
3511 (repeat :tag "Specific tags" (string :tag "Tag"))
3512 (regexp :tag "Tags matched by regexp")))
3514 (defcustom org-tags-exclude-from-inheritance nil
3515 "List of tags that should never be inherited.
3516 This is a way to exclude a few tags from inheritance. For way to do
3517 the opposite, to actively allow inheritance for selected tags,
3518 see the variable `org-use-tag-inheritance'."
3519 :group 'org-tags
3520 :type '(repeat (string :tag "Tag")))
3522 (defun org-tag-inherit-p (tag)
3523 "Check if TAG is one that should be inherited."
3524 (cond
3525 ((member tag org-tags-exclude-from-inheritance) nil)
3526 ((eq org-use-tag-inheritance t) t)
3527 ((not org-use-tag-inheritance) nil)
3528 ((stringp org-use-tag-inheritance)
3529 (string-match org-use-tag-inheritance tag))
3530 ((listp org-use-tag-inheritance)
3531 (member tag org-use-tag-inheritance))
3532 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3534 (defcustom org-tags-match-list-sublevels t
3535 "Non-nil means list also sublevels of headlines matching a search.
3536 This variable applies to tags/property searches, and also to stuck
3537 projects because this search is based on a tags match as well.
3539 When set to the symbol `indented', sublevels are indented with
3540 leading dots.
3542 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3543 the sublevels of a headline matching a tag search often also match
3544 the same search. Listing all of them can create very long lists.
3545 Setting this variable to nil causes subtrees of a match to be skipped.
3547 This variable is semi-obsolete and probably should always be true. It
3548 is better to limit inheritance to certain tags using the variables
3549 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3550 :group 'org-tags
3551 :type '(choice
3552 (const :tag "No, don't list them" nil)
3553 (const :tag "Yes, do list them" t)
3554 (const :tag "List them, indented with leading dots" indented)))
3556 (defcustom org-tags-sort-function nil
3557 "When set, tags are sorted using this function as a comparator."
3558 :group 'org-tags
3559 :type '(choice
3560 (const :tag "No sorting" nil)
3561 (const :tag "Alphabetical" org-string-collate-lessp)
3562 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3563 (function :tag "Custom function" nil)))
3565 (defvar org-tags-history nil
3566 "History of minibuffer reads for tags.")
3567 (defvar org-last-tags-completion-table nil
3568 "The last used completion table for tags.")
3569 (defvar org-after-tags-change-hook nil
3570 "Hook that is run after the tags in a line have changed.")
3572 (defgroup org-properties nil
3573 "Options concerning properties in Org mode."
3574 :tag "Org Properties"
3575 :group 'org)
3577 (defcustom org-property-format "%-10s %s"
3578 "How property key/value pairs should be formatted by `indent-line'.
3579 When `indent-line' hits a property definition, it will format the line
3580 according to this format, mainly to make sure that the values are
3581 lined-up with respect to each other."
3582 :group 'org-properties
3583 :type 'string)
3585 (defcustom org-properties-postprocess-alist nil
3586 "Alist of properties and functions to adjust inserted values.
3587 Elements of this alist must be of the form
3589 ([string] [function])
3591 where [string] must be a property name and [function] must be a
3592 lambda expression: this lambda expression must take one argument,
3593 the value to adjust, and return the new value as a string.
3595 For example, this element will allow the property \"Remaining\"
3596 to be updated wrt the relation between the \"Effort\" property
3597 and the clock summary:
3599 ((\"Remaining\" (lambda(value)
3600 (let ((clocksum (org-clock-sum-current-item))
3601 (effort (org-duration-to-minutes
3602 (org-entry-get (point) \"Effort\"))))
3603 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3604 :group 'org-properties
3605 :version "24.1"
3606 :type '(alist :key-type (string :tag "Property")
3607 :value-type (function :tag "Function")))
3609 (defcustom org-use-property-inheritance nil
3610 "Non-nil means properties apply also for sublevels.
3612 This setting is chiefly used during property searches. Turning it on can
3613 cause significant overhead when doing a search, which is why it is not
3614 on by default.
3616 When nil, only the properties directly given in the current entry count.
3617 When t, every property is inherited. The value may also be a list of
3618 properties that should have inheritance, or a regular expression matching
3619 properties that should be inherited.
3621 However, note that some special properties use inheritance under special
3622 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3623 and the properties ending in \"_ALL\" when they are used as descriptor
3624 for valid values of a property.
3626 Note for programmers:
3627 When querying an entry with `org-entry-get', you can control if inheritance
3628 should be used. By default, `org-entry-get' looks only at the local
3629 properties. You can request inheritance by setting the inherit argument
3630 to t (to force inheritance) or to `selective' (to respect the setting
3631 in this variable)."
3632 :group 'org-properties
3633 :type '(choice
3634 (const :tag "Not" nil)
3635 (const :tag "Always" t)
3636 (repeat :tag "Specific properties" (string :tag "Property"))
3637 (regexp :tag "Properties matched by regexp")))
3639 (defun org-property-inherit-p (property)
3640 "Return a non-nil value if PROPERTY should be inherited."
3641 (cond
3642 ((eq org-use-property-inheritance t) t)
3643 ((not org-use-property-inheritance) nil)
3644 ((stringp org-use-property-inheritance)
3645 (string-match org-use-property-inheritance property))
3646 ((listp org-use-property-inheritance)
3647 (member-ignore-case property org-use-property-inheritance))
3648 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3650 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3651 "The default column format, if no other format has been defined.
3652 This variable can be set on the per-file basis by inserting a line
3654 #+COLUMNS: %25ITEM ....."
3655 :group 'org-properties
3656 :type 'string)
3658 (defcustom org-columns-ellipses ".."
3659 "The ellipses to be used when a field in column view is truncated.
3660 When this is the empty string, as many characters as possible are shown,
3661 but then there will be no visual indication that the field has been truncated.
3662 When this is a string of length N, the last N characters of a truncated
3663 field are replaced by this string. If the column is narrower than the
3664 ellipses string, only part of the ellipses string will be shown."
3665 :group 'org-properties
3666 :type 'string)
3668 (defconst org-global-properties-fixed
3669 '(("VISIBILITY_ALL" . "folded children content all")
3670 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3671 "List of property/value pairs that can be inherited by any entry.
3673 These are fixed values, for the preset properties. The user variable
3674 that can be used to add to this list is `org-global-properties'.
3676 The entries in this list are cons cells where the car is a property
3677 name and cdr is a string with the value. If the value represents
3678 multiple items like an \"_ALL\" property, separate the items by
3679 spaces.")
3681 (defcustom org-global-properties nil
3682 "List of property/value pairs that can be inherited by any entry.
3684 This list will be combined with the constant `org-global-properties-fixed'.
3686 The entries in this list are cons cells where the car is a property
3687 name and cdr is a string with the value.
3689 You can set buffer-local values for the same purpose in the variable
3690 `org-file-properties' this by adding lines like
3692 #+PROPERTY: NAME VALUE"
3693 :group 'org-properties
3694 :type '(repeat
3695 (cons (string :tag "Property")
3696 (string :tag "Value"))))
3698 (defvar-local org-file-properties nil
3699 "List of property/value pairs that can be inherited by any entry.
3700 Valid for the current buffer.
3701 This variable is populated from #+PROPERTY lines.")
3703 (defgroup org-agenda nil
3704 "Options concerning agenda views in Org mode."
3705 :tag "Org Agenda"
3706 :group 'org)
3708 (defvar-local org-category nil
3709 "Variable used by Org files to set a category for agenda display.
3710 Such files should use a file variable to set it, for example
3712 # -*- mode: org; org-category: \"ELisp\"
3714 or contain a special line
3716 #+CATEGORY: ELisp
3718 If the file does not specify a category, then file's base name
3719 is used instead.")
3720 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3722 (defcustom org-agenda-files nil
3723 "The files to be used for agenda display.
3725 If an entry is a directory, all files in that directory that are matched
3726 by `org-agenda-file-regexp' will be part of the file list.
3728 If the value of the variable is not a list but a single file name, then
3729 the list of agenda files is actually stored and maintained in that file,
3730 one agenda file per line. In this file paths can be given relative to
3731 `org-directory'. Tilde expansion and environment variable substitution
3732 are also made.
3734 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3735 and removed with `\\[org-remove-file]'."
3736 :group 'org-agenda
3737 :type '(choice
3738 (repeat :tag "List of files and directories" file)
3739 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3741 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3742 "Regular expression to match files for `org-agenda-files'.
3743 If any element in the list in that variable contains a directory instead
3744 of a normal file, all files in that directory that are matched by this
3745 regular expression will be included."
3746 :group 'org-agenda
3747 :type 'regexp)
3749 (defcustom org-agenda-text-search-extra-files nil
3750 "List of extra files to be searched by text search commands.
3751 These files will be searched in addition to the agenda files by the
3752 commands `org-search-view' (`\\[org-agenda] s') \
3753 and `org-occur-in-agenda-files'.
3754 Note that these files will only be searched for text search commands,
3755 not for the other agenda views like todo lists, tag searches or the weekly
3756 agenda. This variable is intended to list notes and possibly archive files
3757 that should also be searched by these two commands.
3758 In fact, if the first element in the list is the symbol `agenda-archives',
3759 then all archive files of all agenda files will be added to the search
3760 scope."
3761 :group 'org-agenda
3762 :type '(set :greedy t
3763 (const :tag "Agenda Archives" agenda-archives)
3764 (repeat :inline t (file))))
3766 (defvaralias 'org-agenda-multi-occur-extra-files
3767 'org-agenda-text-search-extra-files)
3769 (defcustom org-agenda-skip-unavailable-files nil
3770 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3771 A nil value means to remove them, after a query, from the list."
3772 :group 'org-agenda
3773 :type 'boolean)
3775 (defcustom org-agenda-diary-file 'diary-file
3776 "File to which to add new entries with the `i' key in agenda and calendar.
3777 When this is the symbol `diary-file', the functionality in the Emacs
3778 calendar will be used to add entries to the `diary-file'. But when this
3779 points to a file, `org-agenda-diary-entry' will be used instead."
3780 :group 'org-agenda
3781 :type '(choice
3782 (const :tag "The standard Emacs diary file" diary-file)
3783 (file :tag "Special Org file diary entries")))
3785 (defgroup org-latex nil
3786 "Options for embedding LaTeX code into Org mode."
3787 :tag "Org LaTeX"
3788 :group 'org)
3790 (defcustom org-format-latex-options
3791 '(:foreground default :background default :scale 1.0
3792 :html-foreground "Black" :html-background "Transparent"
3793 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3794 "Options for creating images from LaTeX fragments.
3795 This is a property list with the following properties:
3796 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3797 `default' means use the foreground of the default face.
3798 `auto' means use the foreground from the text face.
3799 :background the background color, or \"Transparent\".
3800 `default' means use the background of the default face.
3801 `auto' means use the background from the text face.
3802 :scale a scaling factor for the size of the images, to get more pixels
3803 :html-foreground, :html-background, :html-scale
3804 the same numbers for HTML export.
3805 :matchers a list indicating which matchers should be used to
3806 find LaTeX fragments. Valid members of this list are:
3807 \"begin\" find environments
3808 \"$1\" find single characters surrounded by $.$
3809 \"$\" find math expressions surrounded by $...$
3810 \"$$\" find math expressions surrounded by $$....$$
3811 \"\\(\" find math expressions surrounded by \\(...\\)
3812 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3813 :group 'org-latex
3814 :type 'plist)
3816 (defcustom org-format-latex-signal-error t
3817 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3818 When nil, just push out a message."
3819 :group 'org-latex
3820 :version "24.1"
3821 :type 'boolean)
3823 (defcustom org-latex-to-mathml-jar-file nil
3824 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3825 Use this to specify additional executable file say a jar file.
3827 When using MathToWeb as the converter, specify the full-path to
3828 your mathtoweb.jar file."
3829 :group 'org-latex
3830 :version "24.1"
3831 :type '(choice
3832 (const :tag "None" nil)
3833 (file :tag "JAR file" :must-match t)))
3835 (defcustom org-latex-to-mathml-convert-command nil
3836 "Command to convert LaTeX fragments to MathML.
3837 Replace format-specifiers in the command as noted below and use
3838 `shell-command' to convert LaTeX to MathML.
3839 %j: Executable file in fully expanded form as specified by
3840 `org-latex-to-mathml-jar-file'.
3841 %I: Input LaTeX file in fully expanded form.
3842 %i: The latex fragment to be converted.
3843 %o: Output MathML file.
3845 This command is used by `org-create-math-formula'.
3847 When using MathToWeb as the converter, set this option to
3848 \"java -jar %j -unicode -force -df %o %I\".
3850 When using LaTeXML set this option to
3851 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3852 :group 'org-latex
3853 :version "24.1"
3854 :type '(choice
3855 (const :tag "None" nil)
3856 (string :tag "\nShell command")))
3858 (defcustom org-preview-latex-default-process 'dvipng
3859 "The default process to convert LaTeX fragments to image files.
3860 All available processes and theirs documents can be found in
3861 `org-preview-latex-process-alist', which see."
3862 :group 'org-latex
3863 :version "26.1"
3864 :package-version '(Org . "9.0")
3865 :type 'symbol)
3867 (defcustom org-preview-latex-process-alist
3868 '((dvipng
3869 :programs ("latex" "dvipng")
3870 :description "dvi > png"
3871 :message "you need to install the programs: latex and dvipng."
3872 :image-input-type "dvi"
3873 :image-output-type "png"
3874 :image-size-adjust (1.0 . 1.0)
3875 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3876 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3877 (dvisvgm
3878 :programs ("latex" "dvisvgm")
3879 :description "dvi > svg"
3880 :message "you need to install the programs: latex and dvisvgm."
3881 :use-xcolor t
3882 :image-input-type "dvi"
3883 :image-output-type "svg"
3884 :image-size-adjust (1.7 . 1.5)
3885 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3886 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3887 (imagemagick
3888 :programs ("latex" "convert")
3889 :description "pdf > png"
3890 :message "you need to install the programs: latex and imagemagick."
3891 :use-xcolor t
3892 :image-input-type "pdf"
3893 :image-output-type "png"
3894 :image-size-adjust (1.0 . 1.0)
3895 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3896 :image-converter
3897 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3898 "Definitions of external processes for LaTeX previewing.
3899 Org mode can use some external commands to generate TeX snippet's images for
3900 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3901 `org-create-formula-image' how to call them.
3903 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3904 PROPERTIES accepts the following attributes:
3906 :programs list of strings, required programs.
3907 :description string, describe the process.
3908 :message string, message it when required programs cannot be found.
3909 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3910 :image-output-type string, output file type of image converter (e.g., \"png\").
3911 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3912 deal with background and foreground color of image.
3913 Otherwise, dvipng style background and foreground color
3914 format are generated. You may then refer to them in
3915 command options with \"%F\" and \"%B\".
3916 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3917 image size showed in buffer and the cdr element is for
3918 HTML file. This option is only useful for process
3919 developers, users should use variable
3920 `org-format-latex-options' instead.
3921 :post-clean list of strings, files matched are to be cleaned up once
3922 the image is generated. When nil, the files with \".dvi\",
3923 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3924 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3925 be cleaned up.
3926 :latex-header list of strings, the LaTeX header of the snippet file.
3927 When nil, the fallback value is used instead, which is
3928 controlled by `org-format-latex-header',
3929 `org-latex-default-packages-alist' and
3930 `org-latex-packages-alist', which see.
3931 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3932 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3933 replaced with values defined below.
3934 :image-converter list of image converter commands strings. Each of them is
3935 given to the shell and supports any of the following
3936 place-holders defined below.
3938 Place-holders used by `:image-converter' and `:latex-compiler':
3940 %f input file name
3941 %b base name of input file
3942 %o base directory of input file
3943 %O absolute output file name
3945 Place-holders only used by `:image-converter':
3947 %F foreground of image
3948 %B background of image
3949 %D dpi, which is used to adjust image size by some processing commands.
3950 %S the image size scale ratio, which is used to adjust image size by some
3951 processing commands."
3952 :group 'org-latex
3953 :version "26.1"
3954 :package-version '(Org . "9.0")
3955 :type '(alist :tag "LaTeX to image backends"
3956 :value-type (plist)))
3958 (defcustom org-preview-latex-image-directory "ltximg/"
3959 "Path to store latex preview images.
3960 A relative path here creates many directories relative to the
3961 processed Org files paths. An absolute path puts all preview
3962 images at the same place."
3963 :group 'org-latex
3964 :version "26.1"
3965 :package-version '(Org . "9.0")
3966 :type 'string)
3968 (defun org-format-latex-mathml-available-p ()
3969 "Return t if `org-latex-to-mathml-convert-command' is usable."
3970 (save-match-data
3971 (when (and (boundp 'org-latex-to-mathml-convert-command)
3972 org-latex-to-mathml-convert-command)
3973 (let ((executable (car (split-string
3974 org-latex-to-mathml-convert-command))))
3975 (when (executable-find executable)
3976 (if (string-match
3977 "%j" org-latex-to-mathml-convert-command)
3978 (file-readable-p org-latex-to-mathml-jar-file)
3979 t))))))
3981 (defcustom org-format-latex-header "\\documentclass{article}
3982 \\usepackage[usenames]{color}
3983 \[PACKAGES]
3984 \[DEFAULT-PACKAGES]
3985 \\pagestyle{empty} % do not remove
3986 % The settings below are copied from fullpage.sty
3987 \\setlength{\\textwidth}{\\paperwidth}
3988 \\addtolength{\\textwidth}{-3cm}
3989 \\setlength{\\oddsidemargin}{1.5cm}
3990 \\addtolength{\\oddsidemargin}{-2.54cm}
3991 \\setlength{\\evensidemargin}{\\oddsidemargin}
3992 \\setlength{\\textheight}{\\paperheight}
3993 \\addtolength{\\textheight}{-\\headheight}
3994 \\addtolength{\\textheight}{-\\headsep}
3995 \\addtolength{\\textheight}{-\\footskip}
3996 \\addtolength{\\textheight}{-3cm}
3997 \\setlength{\\topmargin}{1.5cm}
3998 \\addtolength{\\topmargin}{-2.54cm}"
3999 "The document header used for processing LaTeX fragments.
4000 It is imperative that this header make sure that no page number
4001 appears on the page. The package defined in the variables
4002 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4003 will either replace the placeholder \"[PACKAGES]\" in this
4004 header, or they will be appended."
4005 :group 'org-latex
4006 :type 'string)
4008 (defun org-set-packages-alist (var val)
4009 "Set the packages alist and make sure it has 3 elements per entry."
4010 (set var (mapcar (lambda (x)
4011 (if (and (consp x) (= (length x) 2))
4012 (list (car x) (nth 1 x) t)
4014 val)))
4016 (defun org-get-packages-alist (var)
4017 "Get the packages alist and make sure it has 3 elements per entry."
4018 (mapcar (lambda (x)
4019 (if (and (consp x) (= (length x) 2))
4020 (list (car x) (nth 1 x) t)
4022 (default-value var)))
4024 (defcustom org-latex-default-packages-alist
4025 '(("AUTO" "inputenc" t ("pdflatex"))
4026 ("T1" "fontenc" t ("pdflatex"))
4027 ("" "graphicx" t)
4028 ("" "grffile" t)
4029 ("" "longtable" nil)
4030 ("" "wrapfig" nil)
4031 ("" "rotating" nil)
4032 ("normalem" "ulem" t)
4033 ("" "amsmath" t)
4034 ("" "textcomp" t)
4035 ("" "amssymb" t)
4036 ("" "capt-of" nil)
4037 ("" "hyperref" nil))
4038 "Alist of default packages to be inserted in the header.
4040 Change this only if one of the packages here causes an
4041 incompatibility with another package you are using.
4043 The packages in this list are needed by one part or another of
4044 Org mode to function properly:
4046 - inputenc, fontenc: for basic font and character selection
4047 - graphicx: for including images
4048 - grffile: allow periods and spaces in graphics file names
4049 - longtable: For multipage tables
4050 - wrapfig: for figure placement
4051 - rotating: for sideways figures and tables
4052 - ulem: for underline and strike-through
4053 - amsmath: for subscript and superscript and math environments
4054 - textcomp, amssymb: for various symbols used
4055 for interpreting the entities in `org-entities'. You can skip
4056 some of these packages if you don't use any of their symbols.
4057 - capt-of: for captions outside of floats
4058 - hyperref: for cross references
4060 Therefore you should not modify this variable unless you know
4061 what you are doing. The one reason to change it anyway is that
4062 you might be loading some other package that conflicts with one
4063 of the default packages. Each element is either a cell or
4064 a string.
4066 A cell is of the format
4068 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4070 If SNIPPET-FLAG is non-nil, the package also needs to be included
4071 when compiling LaTeX snippets into images for inclusion into
4072 non-LaTeX output. COMPILERS is a list of compilers that should
4073 include the package, see `org-latex-compiler'. If the document
4074 compiler is not in the list, and the list is non-nil, the package
4075 will not be inserted in the final document.
4077 A string will be inserted as-is in the header of the document."
4078 :group 'org-latex
4079 :group 'org-export-latex
4080 :set 'org-set-packages-alist
4081 :get 'org-get-packages-alist
4082 :version "26.1"
4083 :package-version '(Org . "8.3")
4084 :type '(repeat
4085 (choice
4086 (list :tag "options/package pair"
4087 (string :tag "options")
4088 (string :tag "package")
4089 (boolean :tag "Snippet")
4090 (choice
4091 (const :tag "For all compilers" nil)
4092 (repeat :tag "Allowed compiler" string)))
4093 (string :tag "A line of LaTeX"))))
4095 (defcustom org-latex-packages-alist nil
4096 "Alist of packages to be inserted in every LaTeX header.
4098 These will be inserted after `org-latex-default-packages-alist'.
4099 Each element is either a cell or a string.
4101 A cell is of the format:
4103 (\"options\" \"package\" SNIPPET-FLAG)
4105 SNIPPET-FLAG, when non-nil, indicates that this package is also
4106 needed when turning LaTeX snippets into images for inclusion into
4107 non-LaTeX output.
4109 A string will be inserted as-is in the header of the document.
4111 Make sure that you only list packages here which:
4113 - you want in every file;
4114 - do not conflict with the setup in `org-format-latex-header';
4115 - do not conflict with the default packages in
4116 `org-latex-default-packages-alist'."
4117 :group 'org-latex
4118 :group 'org-export-latex
4119 :set 'org-set-packages-alist
4120 :get 'org-get-packages-alist
4121 :type '(repeat
4122 (choice
4123 (list :tag "options/package pair"
4124 (string :tag "options")
4125 (string :tag "package")
4126 (boolean :tag "Snippet"))
4127 (string :tag "A line of LaTeX"))))
4129 (defgroup org-appearance nil
4130 "Settings for Org mode appearance."
4131 :tag "Org Appearance"
4132 :group 'org)
4134 (defcustom org-level-color-stars-only nil
4135 "Non-nil means fontify only the stars in each headline.
4136 When nil, the entire headline is fontified.
4137 Changing it requires restart of `font-lock-mode' to become effective
4138 also in regions already fontified."
4139 :group 'org-appearance
4140 :type 'boolean)
4142 (defcustom org-hide-leading-stars nil
4143 "Non-nil means hide the first N-1 stars in a headline.
4144 This works by using the face `org-hide' for these stars. This
4145 face is white for a light background, and black for a dark
4146 background. You may have to customize the face `org-hide' to
4147 make this work.
4148 Changing it requires restart of `font-lock-mode' to become effective
4149 also in regions already fontified.
4150 You may also set this on a per-file basis by adding one of the following
4151 lines to the buffer:
4153 #+STARTUP: hidestars
4154 #+STARTUP: showstars"
4155 :group 'org-appearance
4156 :type 'boolean)
4158 (defcustom org-hidden-keywords nil
4159 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4160 For example, a value \\='(title) for this list makes the document's title
4161 appear in the buffer without the initial \"#+TITLE:\" part."
4162 :group 'org-appearance
4163 :version "24.1"
4164 :type '(set (const :tag "#+AUTHOR" author)
4165 (const :tag "#+DATE" date)
4166 (const :tag "#+EMAIL" email)
4167 (const :tag "#+TITLE" title)))
4169 (defcustom org-custom-properties nil
4170 "List of properties (as strings) with a special meaning.
4171 The default use of these custom properties is to let the user
4172 hide them with `org-toggle-custom-properties-visibility'."
4173 :group 'org-properties
4174 :group 'org-appearance
4175 :version "24.3"
4176 :type '(repeat (string :tag "Property Name")))
4178 (defcustom org-fontify-done-headline nil
4179 "Non-nil means change the face of a headline if it is marked DONE.
4180 Normally, only the TODO/DONE keyword indicates the state of a headline.
4181 When this is non-nil, the headline after the keyword is set to the
4182 `org-headline-done' as an additional indication."
4183 :group 'org-appearance
4184 :type 'boolean)
4186 (defcustom org-fontify-emphasized-text t
4187 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4188 Changing this variable requires a restart of Emacs to take effect."
4189 :group 'org-appearance
4190 :type 'boolean)
4192 (defcustom org-fontify-whole-heading-line nil
4193 "Non-nil means fontify the whole line for headings.
4194 This is useful when setting a background color for the
4195 org-level-* faces."
4196 :group 'org-appearance
4197 :type 'boolean)
4199 (defcustom org-highlight-latex-and-related nil
4200 "Non-nil means highlight LaTeX related syntax in the buffer.
4201 When non nil, the value should be a list containing any of the
4202 following symbols:
4203 `latex' Highlight LaTeX snippets and environments.
4204 `script' Highlight subscript and superscript.
4205 `entities' Highlight entities."
4206 :group 'org-appearance
4207 :version "24.4"
4208 :package-version '(Org . "8.0")
4209 :type '(choice
4210 (const :tag "No highlighting" nil)
4211 (set :greedy t :tag "Highlight"
4212 (const :tag "LaTeX snippets and environments" latex)
4213 (const :tag "Subscript and superscript" script)
4214 (const :tag "Entities" entities))))
4216 (defcustom org-hide-emphasis-markers nil
4217 "Non-nil mean font-lock should hide the emphasis marker characters."
4218 :group 'org-appearance
4219 :type 'boolean)
4221 (defcustom org-hide-macro-markers nil
4222 "Non-nil mean font-lock should hide the brackets marking macro calls."
4223 :group 'org-appearance
4224 :type 'boolean)
4226 (defcustom org-pretty-entities nil
4227 "Non-nil means show entities as UTF8 characters.
4228 When nil, the \\name form remains in the buffer."
4229 :group 'org-appearance
4230 :version "24.1"
4231 :type 'boolean)
4233 (defcustom org-pretty-entities-include-sub-superscripts t
4234 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4235 :group 'org-appearance
4236 :version "24.1"
4237 :type 'boolean)
4239 (defvar org-emph-re nil
4240 "Regular expression for matching emphasis.
4241 After a match, the match groups contain these elements:
4242 0 The match of the full regular expression, including the characters
4243 before and after the proper match
4244 1 The character before the proper match, or empty at beginning of line
4245 2 The proper match, including the leading and trailing markers
4246 3 The leading marker like * or /, indicating the type of highlighting
4247 4 The text between the emphasis markers, not including the markers
4248 5 The character after the match, empty at the end of a line")
4250 (defvar org-verbatim-re nil
4251 "Regular expression for matching verbatim text.")
4253 (defvar org-emphasis-regexp-components) ; defined just below
4254 (defvar org-emphasis-alist) ; defined just below
4255 (defun org-set-emph-re (var val)
4256 "Set variable and compute the emphasis regular expression."
4257 (set var val)
4258 (when (and (boundp 'org-emphasis-alist)
4259 (boundp 'org-emphasis-regexp-components)
4260 org-emphasis-alist org-emphasis-regexp-components)
4261 (pcase-let*
4262 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4263 (body (if (<= nl 0) body
4264 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4265 (template
4266 (format (concat "\\([%s]\\|^\\)" ;before markers
4267 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4268 "\\([%s]\\|$\\)") ;after markers
4269 pre border border body border post)))
4270 (setq org-emph-re (format template "*/_+"))
4271 (setq org-verbatim-re (format template "=~")))))
4273 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4274 ;; set this option proved cumbersome. See this message/thread:
4275 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4276 (defvar org-emphasis-regexp-components
4277 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4278 "Components used to build the regular expression for emphasis.
4279 This is a list with five entries. Terminology: In an emphasis string
4280 like \" *strong word* \", we call the initial space PREMATCH, the final
4281 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4282 and \"trong wor\" is the body. The different components in this variable
4283 specify what is allowed/forbidden in each part:
4285 pre Chars allowed as prematch. Beginning of line will be allowed too.
4286 post Chars allowed as postmatch. End of line will be allowed too.
4287 border The chars *forbidden* as border characters.
4288 body-regexp A regexp like \".\" to match a body character. Don't use
4289 non-shy groups here, and don't allow newline here.
4290 newline The maximum number of newlines allowed in an emphasis exp.
4292 You need to reload Org or to restart Emacs after setting this.")
4294 (defcustom org-emphasis-alist
4295 '(("*" bold)
4296 ("/" italic)
4297 ("_" underline)
4298 ("=" org-verbatim verbatim)
4299 ("~" org-code verbatim)
4300 ("+" (:strike-through t)))
4301 "Alist of characters and faces to emphasize text.
4302 Text starting and ending with a special character will be emphasized,
4303 for example *bold*, _underlined_ and /italic/. This variable sets the
4304 marker characters and the face to be used by font-lock for highlighting
4305 in Org buffers.
4307 You need to reload Org or to restart Emacs after customizing this."
4308 :group 'org-appearance
4309 :set 'org-set-emph-re
4310 :version "24.4"
4311 :package-version '(Org . "8.0")
4312 :type '(repeat
4313 (list
4314 (string :tag "Marker character")
4315 (choice
4316 (face :tag "Font-lock-face")
4317 (plist :tag "Face property list"))
4318 (option (const verbatim)))))
4320 (defvar org-protecting-blocks '("src" "example" "export")
4321 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4322 This is needed for font-lock setup.")
4324 ;;; Functions and variables from their packages
4325 ;; Declared here to avoid compiler warnings
4326 (defvar mark-active)
4328 ;; Various packages
4329 (declare-function calc-eval "calc" (str &optional separator &rest args))
4330 (declare-function calendar-forward-day "cal-move" (arg))
4331 (declare-function calendar-goto-date "cal-move" (date))
4332 (declare-function calendar-goto-today "cal-move" ())
4333 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4334 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4335 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4336 (declare-function cdlatex-tab "ext:cdlatex" ())
4337 (declare-function dired-get-filename
4338 "dired"
4339 (&optional localp no-error-if-not-filep))
4340 (declare-function iswitchb-read-buffer
4341 "iswitchb"
4342 (prompt &optional
4343 default require-match _predicate start matches-set))
4344 (declare-function org-agenda-change-all-lines
4345 "org-agenda"
4346 (newhead hdmarker &optional fixface just-this))
4347 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4348 "org-agenda"
4349 (&optional end))
4350 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4351 (declare-function org-agenda-format-item
4352 "org-agenda"
4353 (extra txt &optional level category tags dotime
4354 remove-re habitp))
4355 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4356 (declare-function org-agenda-save-markers-for-cut-and-paste
4357 "org-agenda"
4358 (beg end))
4359 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4360 (declare-function org-agenda-skip "org-agenda" ())
4361 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4362 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4363 (declare-function org-indent-mode "org-indent" (&optional arg))
4364 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4365 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4366 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4367 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4368 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4369 (declare-function parse-time-string "parse-time" (string))
4371 (defvar align-mode-rules-list)
4372 (defvar calc-embedded-close-formula)
4373 (defvar calc-embedded-open-formula)
4374 (defvar calc-embedded-open-mode)
4375 (defvar font-lock-unfontify-region-function)
4376 (defvar iswitchb-temp-buflist)
4377 (defvar org-agenda-tags-todo-honor-ignore-options)
4378 (defvar remember-data-file)
4379 (defvar texmathp-why)
4381 ;;;###autoload
4382 (defun turn-on-orgtbl ()
4383 "Unconditionally turn on `orgtbl-mode'."
4384 (require 'org-table)
4385 (orgtbl-mode 1))
4387 (defun org-at-table-p (&optional table-type)
4388 "Non-nil if the cursor is inside an Org table.
4389 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4390 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4391 (or (not (derived-mode-p 'org-mode))
4392 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4393 (and e (or table-type
4394 (eq 'org (org-element-property :type e))))))))
4396 (defun org-at-table.el-p ()
4397 "Non-nil when point is at a table.el table."
4398 (and (org-match-line "[ \t]*[|+]")
4399 (let ((element (org-element-at-point)))
4400 (and (eq (org-element-type element) 'table)
4401 (eq (org-element-property :type element) 'table.el)))))
4403 (defun org-at-table-hline-p ()
4404 "Non-nil when point is inside a hline in a table.
4405 Assume point is already in a table."
4406 (org-match-line org-table-hline-regexp))
4408 (defun org-table-map-tables (function &optional quietly)
4409 "Apply FUNCTION to the start of all tables in the buffer."
4410 (org-with-wide-buffer
4411 (goto-char (point-min))
4412 (while (re-search-forward org-table-any-line-regexp nil t)
4413 (unless quietly
4414 (message "Mapping tables: %d%%"
4415 (floor (* 100.0 (point)) (buffer-size))))
4416 (beginning-of-line 1)
4417 (when (and (looking-at org-table-line-regexp)
4418 ;; Exclude tables in src/example/verbatim/clocktable blocks
4419 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4420 (save-excursion (funcall function))
4421 (or (looking-at org-table-line-regexp)
4422 (forward-char 1)))
4423 (re-search-forward org-table-any-border-regexp nil 1)))
4424 (unless quietly (message "Mapping tables: done")))
4426 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4427 (declare-function org-clock-update-mode-line "org-clock" ())
4428 (declare-function org-resolve-clocks "org-clock"
4429 (&optional also-non-dangling-p prompt last-valid))
4431 (defun org-at-TBLFM-p (&optional pos)
4432 "Non-nil when point (or POS) is in #+TBLFM line."
4433 (save-excursion
4434 (goto-char (or pos (point)))
4435 (beginning-of-line)
4436 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4437 (eq (org-element-type (org-element-at-point)) 'table))))
4439 (defvar org-clock-start-time)
4440 (defvar org-clock-marker (make-marker)
4441 "Marker recording the last clock-in.")
4442 (defvar org-clock-hd-marker (make-marker)
4443 "Marker recording the last clock-in, but the headline position.")
4444 (defvar org-clock-heading ""
4445 "The heading of the current clock entry.")
4446 (defun org-clock-is-active ()
4447 "Return the buffer where the clock is currently running.
4448 Return nil if no clock is running."
4449 (marker-buffer org-clock-marker))
4451 (defun org-check-running-clock ()
4452 "Check if the current buffer contains the running clock.
4453 If yes, offer to stop it and to save the buffer with the changes."
4454 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4455 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4456 (buffer-name))))
4457 (org-clock-out)
4458 (when (y-or-n-p "Save changed buffer?")
4459 (save-buffer))))
4461 (defun org-clocktable-try-shift (dir n)
4462 "Check if this line starts a clock table, if yes, shift the time block."
4463 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4464 (org-clocktable-shift dir n)))
4466 ;;;###autoload
4467 (defun org-clock-persistence-insinuate ()
4468 "Set up hooks for clock persistence."
4469 (require 'org-clock)
4470 (add-hook 'org-mode-hook 'org-clock-load)
4471 (add-hook 'kill-emacs-hook 'org-clock-save))
4473 (defgroup org-archive nil
4474 "Options concerning archiving in Org mode."
4475 :tag "Org Archive"
4476 :group 'org-structure)
4478 (defcustom org-archive-location "%s_archive::"
4479 "The location where subtrees should be archived.
4481 The value of this variable is a string, consisting of two parts,
4482 separated by a double-colon. The first part is a filename and
4483 the second part is a headline.
4485 When the filename is omitted, archiving happens in the same file.
4486 %s in the filename will be replaced by the current file
4487 name (without the directory part). Archiving to a different file
4488 is useful to keep archived entries from contributing to the
4489 Org Agenda.
4491 The archived entries will be filed as subtrees of the specified
4492 headline. When the headline is omitted, the subtrees are simply
4493 filed away at the end of the file, as top-level entries. Also in
4494 the heading you can use %s to represent the file name, this can be
4495 useful when using the same archive for a number of different files.
4497 Here are a few examples:
4498 \"%s_archive::\"
4499 If the current file is Projects.org, archive in file
4500 Projects.org_archive, as top-level trees. This is the default.
4502 \"::* Archived Tasks\"
4503 Archive in the current file, under the top-level headline
4504 \"* Archived Tasks\".
4506 \"~/org/archive.org::\"
4507 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4509 \"~/org/archive.org::* From %s\"
4510 Archive in file ~/org/archive.org (absolute path), under headlines
4511 \"From FILENAME\" where file name is the current file name.
4513 \"~/org/datetree.org::datetree/* Finished Tasks\"
4514 The \"datetree/\" string is special, signifying to archive
4515 items to the datetree. Items are placed in either the CLOSED
4516 date of the item, or the current date if there is no CLOSED date.
4517 The heading will be a subentry to the current date. There doesn't
4518 need to be a heading, but there always needs to be a slash after
4519 datetree. For example, to store archived items directly in the
4520 datetree, use \"~/org/datetree.org::datetree/\".
4522 \"basement::** Finished Tasks\"
4523 Archive in file ./basement (relative path), as level 3 trees
4524 below the level 2 heading \"** Finished Tasks\".
4526 You may set this option on a per-file basis by adding to the buffer a
4527 line like
4529 #+ARCHIVE: basement::** Finished Tasks
4531 You may also define it locally for a subtree by setting an ARCHIVE property
4532 in the entry. If such a property is found in an entry, or anywhere up
4533 the hierarchy, it will be used."
4534 :group 'org-archive
4535 :type 'string)
4537 (defcustom org-agenda-skip-archived-trees t
4538 "Non-nil means the agenda will skip any items located in archived trees.
4539 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4540 variable is no longer recommended, you should leave it at the value t.
4541 Instead, use the key `v' to cycle the archives-mode in the agenda."
4542 :group 'org-archive
4543 :group 'org-agenda-skip
4544 :type 'boolean)
4546 (defcustom org-columns-skip-archived-trees t
4547 "Non-nil means ignore archived trees when creating column view."
4548 :group 'org-archive
4549 :group 'org-properties
4550 :type 'boolean)
4552 (defcustom org-cycle-open-archived-trees nil
4553 "Non-nil means `org-cycle' will open archived trees.
4554 An archived tree is a tree marked with the tag ARCHIVE.
4555 When nil, archived trees will stay folded. You can still open them with
4556 normal outline commands like `show-all', but not with the cycling commands."
4557 :group 'org-archive
4558 :group 'org-cycle
4559 :type 'boolean)
4561 (defcustom org-sparse-tree-open-archived-trees nil
4562 "Non-nil means sparse tree construction shows matches in archived trees.
4563 When nil, matches in these trees are highlighted, but the trees are kept in
4564 collapsed state."
4565 :group 'org-archive
4566 :group 'org-sparse-trees
4567 :type 'boolean)
4569 (defcustom org-sparse-tree-default-date-type nil
4570 "The default date type when building a sparse tree.
4571 When this is nil, a date is a scheduled or a deadline timestamp.
4572 Otherwise, these types are allowed:
4574 all: all timestamps
4575 active: only active timestamps (<...>)
4576 inactive: only inactive timestamps ([...])
4577 scheduled: only scheduled timestamps
4578 deadline: only deadline timestamps"
4579 :type '(choice (const :tag "Scheduled or deadline" nil)
4580 (const :tag "All timestamps" all)
4581 (const :tag "Only active timestamps" active)
4582 (const :tag "Only inactive timestamps" inactive)
4583 (const :tag "Only scheduled timestamps" scheduled)
4584 (const :tag "Only deadline timestamps" deadline)
4585 (const :tag "Only closed timestamps" closed))
4586 :version "26.1"
4587 :package-version '(Org . "8.3")
4588 :group 'org-sparse-trees)
4590 (defun org-cycle-hide-archived-subtrees (state)
4591 "Re-hide all archived subtrees after a visibility state change.
4592 STATE should be one of the symbols listed in the docstring of
4593 `org-cycle-hook'."
4594 (when (and (not org-cycle-open-archived-trees)
4595 (not (memq state '(overview folded))))
4596 (save-excursion
4597 (let* ((globalp (memq state '(contents all)))
4598 (beg (if globalp (point-min) (point)))
4599 (end (if globalp (point-max) (org-end-of-subtree t))))
4600 (org-hide-archived-subtrees beg end)
4601 (goto-char beg)
4602 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4603 (message "%s" (substitute-command-keys
4604 "Subtree is archived and stays closed. Use \
4605 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4607 (defun org-force-cycle-archived ()
4608 "Cycle subtree even if it is archived."
4609 (interactive)
4610 (setq this-command 'org-cycle)
4611 (let ((org-cycle-open-archived-trees t))
4612 (call-interactively 'org-cycle)))
4614 (defun org-hide-archived-subtrees (beg end)
4615 "Re-hide all archived subtrees after a visibility state change."
4616 (org-with-wide-buffer
4617 (let ((case-fold-search nil)
4618 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4619 (goto-char beg)
4620 ;; Include headline point is currently on.
4621 (beginning-of-line)
4622 (while (and (< (point) end) (re-search-forward re end t))
4623 (when (member org-archive-tag (org-get-tags))
4624 (org-flag-subtree t)
4625 (org-end-of-subtree t))))))
4627 (defun org-flag-subtree (flag)
4628 (save-excursion
4629 (org-back-to-heading t)
4630 (org-flag-region (line-end-position)
4631 (progn (org-end-of-subtree t) (point))
4632 flag
4633 'outline)))
4635 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4637 ;; Declare Column View Code
4639 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4640 (declare-function org-columns-compute "org-colview" (property))
4642 ;; Declare ID code
4644 (declare-function org-id-store-link "org-id")
4645 (declare-function org-id-locations-load "org-id")
4646 (declare-function org-id-locations-save "org-id")
4647 (defvar org-id-track-globally)
4649 ;;; Variables for pre-computed regular expressions, all buffer local
4651 (defvar-local org-todo-regexp nil
4652 "Matches any of the TODO state keywords.
4653 Since TODO keywords are case-sensitive, `case-fold-search' is
4654 expected to be bound to nil when matching against this regexp.")
4656 (defvar-local org-not-done-regexp nil
4657 "Matches any of the TODO state keywords except the last one.
4658 Since TODO keywords are case-sensitive, `case-fold-search' is
4659 expected to be bound to nil when matching against this regexp.")
4661 (defvar-local org-not-done-heading-regexp nil
4662 "Matches a TODO headline that is not done.
4663 Since TODO keywords are case-sensitive, `case-fold-search' is
4664 expected to be bound to nil when matching against this regexp.")
4666 (defvar-local org-todo-line-regexp nil
4667 "Matches a headline and puts TODO state into group 2 if present.
4668 Since TODO keywords are case-sensitive, `case-fold-search' is
4669 expected to be bound to nil when matching against this regexp.")
4671 (defvar-local org-complex-heading-regexp nil
4672 "Matches a headline and puts everything into groups:
4674 group 1: Stars
4675 group 2: The TODO keyword, maybe
4676 group 3: Priority cookie
4677 group 4: True headline
4678 group 5: Tags
4680 Since TODO keywords are case-sensitive, `case-fold-search' is
4681 expected to be bound to nil when matching against this regexp.")
4683 (defvar-local org-complex-heading-regexp-format nil
4684 "Printf format to make regexp to match an exact headline.
4685 This regexp will match the headline of any node which has the
4686 exact headline text that is put into the format, but may have any
4687 TODO state, priority and tags.")
4689 (defvar-local org-todo-line-tags-regexp nil
4690 "Matches a headline and puts TODO state into group 2 if present.
4691 Also put tags into group 4 if tags are present.")
4693 (defconst org-plain-time-of-day-regexp
4694 (concat
4695 "\\(\\<[012]?[0-9]"
4696 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4697 "\\(--?"
4698 "\\(\\<[012]?[0-9]"
4699 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4700 "\\)?")
4701 "Regular expression to match a plain time or time range.
4702 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4703 groups carry important information:
4704 0 the full match
4705 1 the first time, range or not
4706 8 the second time, if it is a range.")
4708 (defconst org-plain-time-extension-regexp
4709 (concat
4710 "\\(\\<[012]?[0-9]"
4711 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4712 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4713 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4714 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4715 groups carry important information:
4716 0 the full match
4717 7 hours of duration
4718 9 minutes of duration")
4720 (defconst org-stamp-time-of-day-regexp
4721 (concat
4722 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4723 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4724 "\\(--?"
4725 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4726 "Regular expression to match a timestamp time or time range.
4727 After a match, the following groups carry important information:
4728 0 the full match
4729 1 date plus weekday, for back referencing to make sure both times are on the same day
4730 2 the first time, range or not
4731 4 the second time, if it is a range.")
4733 (defconst org-startup-options
4734 '(("fold" org-startup-folded t)
4735 ("overview" org-startup-folded t)
4736 ("nofold" org-startup-folded nil)
4737 ("showall" org-startup-folded nil)
4738 ("showeverything" org-startup-folded showeverything)
4739 ("content" org-startup-folded content)
4740 ("indent" org-startup-indented t)
4741 ("noindent" org-startup-indented nil)
4742 ("hidestars" org-hide-leading-stars t)
4743 ("showstars" org-hide-leading-stars nil)
4744 ("odd" org-odd-levels-only t)
4745 ("oddeven" org-odd-levels-only nil)
4746 ("align" org-startup-align-all-tables t)
4747 ("noalign" org-startup-align-all-tables nil)
4748 ("shrink" org-startup-shrink-all-tables t)
4749 ("inlineimages" org-startup-with-inline-images t)
4750 ("noinlineimages" org-startup-with-inline-images nil)
4751 ("latexpreview" org-startup-with-latex-preview t)
4752 ("nolatexpreview" org-startup-with-latex-preview nil)
4753 ("customtime" org-display-custom-times t)
4754 ("logdone" org-log-done time)
4755 ("lognotedone" org-log-done note)
4756 ("nologdone" org-log-done nil)
4757 ("lognoteclock-out" org-log-note-clock-out t)
4758 ("nolognoteclock-out" org-log-note-clock-out nil)
4759 ("logrepeat" org-log-repeat state)
4760 ("lognoterepeat" org-log-repeat note)
4761 ("logdrawer" org-log-into-drawer t)
4762 ("nologdrawer" org-log-into-drawer nil)
4763 ("logstatesreversed" org-log-states-order-reversed t)
4764 ("nologstatesreversed" org-log-states-order-reversed nil)
4765 ("nologrepeat" org-log-repeat nil)
4766 ("logreschedule" org-log-reschedule time)
4767 ("lognotereschedule" org-log-reschedule note)
4768 ("nologreschedule" org-log-reschedule nil)
4769 ("logredeadline" org-log-redeadline time)
4770 ("lognoteredeadline" org-log-redeadline note)
4771 ("nologredeadline" org-log-redeadline nil)
4772 ("logrefile" org-log-refile time)
4773 ("lognoterefile" org-log-refile note)
4774 ("nologrefile" org-log-refile nil)
4775 ("fninline" org-footnote-define-inline t)
4776 ("nofninline" org-footnote-define-inline nil)
4777 ("fnlocal" org-footnote-section nil)
4778 ("fnauto" org-footnote-auto-label t)
4779 ("fnprompt" org-footnote-auto-label nil)
4780 ("fnconfirm" org-footnote-auto-label confirm)
4781 ("fnplain" org-footnote-auto-label plain)
4782 ("fnadjust" org-footnote-auto-adjust t)
4783 ("nofnadjust" org-footnote-auto-adjust nil)
4784 ("constcgs" constants-unit-system cgs)
4785 ("constSI" constants-unit-system SI)
4786 ("noptag" org-tag-persistent-alist nil)
4787 ("hideblocks" org-hide-block-startup t)
4788 ("nohideblocks" org-hide-block-startup nil)
4789 ("beamer" org-startup-with-beamer-mode t)
4790 ("entitiespretty" org-pretty-entities t)
4791 ("entitiesplain" org-pretty-entities nil))
4792 "Variable associated with STARTUP options for Org.
4793 Each element is a list of three items: the startup options (as written
4794 in the #+STARTUP line), the corresponding variable, and the value to set
4795 this variable to if the option is found. An optional forth element PUSH
4796 means to push this value onto the list in the variable.")
4798 (defcustom org-group-tags t
4799 "When non-nil (the default), use group tags.
4800 This can be turned on/off through `org-toggle-tags-groups'."
4801 :group 'org-tags
4802 :group 'org-startup
4803 :type 'boolean)
4805 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4807 (defun org-toggle-tags-groups ()
4808 "Toggle support for group tags.
4809 Support for group tags is controlled by the option
4810 `org-group-tags', which is non-nil by default."
4811 (interactive)
4812 (setq org-group-tags (not org-group-tags))
4813 (cond ((and (derived-mode-p 'org-agenda-mode)
4814 org-group-tags)
4815 (org-agenda-redo))
4816 ((derived-mode-p 'org-mode)
4817 (let ((org-inhibit-startup t)) (org-mode))))
4818 (message "Groups tags support has been turned %s"
4819 (if org-group-tags "on" "off")))
4821 (defun org-set-regexps-and-options (&optional tags-only)
4822 "Precompute regular expressions used in the current buffer.
4823 When optional argument TAGS-ONLY is non-nil, only compute tags
4824 related expressions."
4825 (when (derived-mode-p 'org-mode)
4826 (let ((alist (org--setup-collect-keywords
4827 (org-make-options-regexp
4828 (append '("FILETAGS" "TAGS" "SETUPFILE")
4829 (and (not tags-only)
4830 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4831 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4832 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4833 ;; Startup options. Get this early since it does change
4834 ;; behavior for other options (e.g., tags).
4835 (let ((startup (cdr (assq 'startup alist))))
4836 (dolist (option startup)
4837 (let ((entry (assoc-string option org-startup-options t)))
4838 (when entry
4839 (let ((var (nth 1 entry))
4840 (val (nth 2 entry)))
4841 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4842 (unless (listp (symbol-value var))
4843 (set (make-local-variable var) nil))
4844 (add-to-list var val)))))))
4845 (setq-local org-file-tags
4846 (mapcar #'org-add-prop-inherited
4847 (cdr (assq 'filetags alist))))
4848 (setq org-current-tag-alist
4849 (append org-tag-persistent-alist
4850 (let ((tags (cdr (assq 'tags alist))))
4851 (if tags (org-tag-string-to-alist tags)
4852 org-tag-alist))))
4853 (setq org-tag-groups-alist
4854 (org-tag-alist-to-groups org-current-tag-alist))
4855 (unless tags-only
4856 ;; File properties.
4857 (setq-local org-file-properties (cdr (assq 'property alist)))
4858 ;; Archive location.
4859 (let ((archive (cdr (assq 'archive alist))))
4860 (when archive (setq-local org-archive-location archive)))
4861 ;; Category.
4862 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4863 (when cat
4864 (setq-local org-category (intern cat))
4865 (setq-local org-file-properties
4866 (org--update-property-plist
4867 "CATEGORY" cat org-file-properties))))
4868 ;; Columns.
4869 (let ((column (cdr (assq 'columns alist))))
4870 (when column (setq-local org-columns-default-format column)))
4871 ;; Constants.
4872 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4873 ;; Link abbreviations.
4874 (let ((links (cdr (assq 'link alist))))
4875 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4876 ;; Priorities.
4877 (let ((priorities (cdr (assq 'priorities alist))))
4878 (when priorities
4879 (setq-local org-highest-priority (nth 0 priorities))
4880 (setq-local org-lowest-priority (nth 1 priorities))
4881 (setq-local org-default-priority (nth 2 priorities))))
4882 ;; Scripts.
4883 (let ((scripts (assq 'scripts alist)))
4884 (when scripts
4885 (setq-local org-use-sub-superscripts (cdr scripts))))
4886 ;; TODO keywords.
4887 (setq-local org-todo-kwd-alist nil)
4888 (setq-local org-todo-key-alist nil)
4889 (setq-local org-todo-key-trigger nil)
4890 (setq-local org-todo-keywords-1 nil)
4891 (setq-local org-done-keywords nil)
4892 (setq-local org-todo-heads nil)
4893 (setq-local org-todo-sets nil)
4894 (setq-local org-todo-log-states nil)
4895 (let ((todo-sequences
4896 (or (nreverse (cdr (assq 'todo alist)))
4897 (let ((d (default-value 'org-todo-keywords)))
4898 (if (not (stringp (car d))) d
4899 ;; XXX: Backward compatibility code.
4900 (list (cons org-todo-interpretation d)))))))
4901 (dolist (sequence todo-sequences)
4902 (let* ((sequence (or (run-hook-with-args-until-success
4903 'org-todo-setup-filter-hook sequence)
4904 sequence))
4905 (sequence-type (car sequence))
4906 (keywords (cdr sequence))
4907 (sep (member "|" keywords))
4908 names alist)
4909 (dolist (k (remove "|" keywords))
4910 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4912 (error "Invalid TODO keyword %s" k))
4913 (let ((name (match-string 1 k))
4914 (key (match-string 2 k))
4915 (log (org-extract-log-state-settings k)))
4916 (push name names)
4917 (push (cons name (and key (string-to-char key))) alist)
4918 (when log (push log org-todo-log-states))))
4919 (let* ((names (nreverse names))
4920 (done (if sep (org-remove-keyword-keys (cdr sep))
4921 (last names)))
4922 (head (car names))
4923 (tail (list sequence-type head (car done) (org-last done))))
4924 (add-to-list 'org-todo-heads head 'append)
4925 (push names org-todo-sets)
4926 (setq org-done-keywords (append org-done-keywords done nil))
4927 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4928 (setq org-todo-key-alist
4929 (append org-todo-key-alist
4930 (and alist
4931 (append '((:startgroup))
4932 (nreverse alist)
4933 '((:endgroup))))))
4934 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4935 (setq org-todo-sets (nreverse org-todo-sets)
4936 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4937 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4938 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4939 ;; Compute the regular expressions and other local variables.
4940 ;; Using `org-outline-regexp-bol' would complicate them much,
4941 ;; because of the fixed white space at the end of that string.
4942 (unless org-done-keywords
4943 (setq org-done-keywords
4944 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4945 (setq org-not-done-keywords
4946 (org-delete-all org-done-keywords
4947 (copy-sequence org-todo-keywords-1))
4948 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4949 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4950 org-not-done-heading-regexp
4951 (format org-heading-keyword-regexp-format org-not-done-regexp)
4952 org-todo-line-regexp
4953 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4954 org-complex-heading-regexp
4955 (concat "^\\(\\*+\\)"
4956 "\\(?: +" org-todo-regexp "\\)?"
4957 "\\(?: +\\(\\[#.\\]\\)\\)?"
4958 "\\(?: +\\(.*?\\)\\)??"
4959 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4960 "[ \t]*$")
4961 org-complex-heading-regexp-format
4962 (concat "^\\(\\*+\\)"
4963 "\\(?: +" org-todo-regexp "\\)?"
4964 "\\(?: +\\(\\[#.\\]\\)\\)?"
4965 "\\(?: +"
4966 ;; Stats cookies can be stuck to body.
4967 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4968 "\\(%s\\)"
4969 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4970 "\\)"
4971 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
4972 "[ \t]*$")
4973 org-todo-line-tags-regexp
4974 (concat "^\\(\\*+\\)"
4975 "\\(?: +" org-todo-regexp "\\)?"
4976 "\\(?: +\\(.*?\\)\\)??"
4977 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
4978 "[ \t]*$"))
4979 (org-compute-latex-and-related-regexp)))))
4981 (defun org--setup-collect-keywords (regexp &optional files alist)
4982 "Return setup keywords values as an alist.
4984 REGEXP matches a subset of setup keywords. FILES is a list of
4985 file names already visited. It is used to avoid circular setup
4986 files. ALIST, when non-nil, is the alist computed so far.
4988 Return value contains the following keys: `archive', `category',
4989 `columns', `constants', `filetags', `link', `priorities',
4990 `property', `scripts', `startup', `tags' and `todo'."
4991 (org-with-wide-buffer
4992 (goto-char (point-min))
4993 (let ((case-fold-search t))
4994 (while (re-search-forward regexp nil t)
4995 (let ((element (org-element-at-point)))
4996 (when (eq (org-element-type element) 'keyword)
4997 (let ((key (org-element-property :key element))
4998 (value (org-element-property :value element)))
4999 (cond
5000 ((equal key "ARCHIVE")
5001 (when (org-string-nw-p value)
5002 (push (cons 'archive value) alist)))
5003 ((equal key "CATEGORY") (push (cons 'category value) alist))
5004 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5005 ((equal key "CONSTANTS")
5006 (let* ((constants (assq 'constants alist))
5007 (store (cdr constants)))
5008 (dolist (pair (split-string value))
5009 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5010 pair)
5011 (let* ((name (match-string 1 pair))
5012 (value (match-string 2 pair))
5013 (old (assoc name store)))
5014 (if old (setcdr old value)
5015 (push (cons name value) store)))))
5016 (if constants (setcdr constants store)
5017 (push (cons 'constants store) alist))))
5018 ((equal key "FILETAGS")
5019 (when (org-string-nw-p value)
5020 (let ((old (assq 'filetags alist))
5021 (new (apply #'nconc
5022 (mapcar (lambda (x) (org-split-string x ":"))
5023 (split-string value)))))
5024 (if old (setcdr old (append new (cdr old)))
5025 (push (cons 'filetags new) alist)))))
5026 ((equal key "LINK")
5027 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5028 (let ((links (assq 'link alist))
5029 (pair (cons (match-string-no-properties 1 value)
5030 (match-string-no-properties 2 value))))
5031 (if links (push pair (cdr links))
5032 (push (list 'link pair) alist)))))
5033 ((equal key "OPTIONS")
5034 (when (and (org-string-nw-p value)
5035 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5036 (push (cons 'scripts (read (match-string 1 value))) alist)))
5037 ((equal key "PRIORITIES")
5038 (push (cons 'priorities
5039 (let ((prio (split-string value)))
5040 (if (< (length prio) 3) '(?A ?C ?B)
5041 (mapcar #'string-to-char prio))))
5042 alist))
5043 ((equal key "PROPERTY")
5044 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5045 (let* ((property (assq 'property alist))
5046 (value (org--update-property-plist
5047 (match-string-no-properties 1 value)
5048 (match-string-no-properties 2 value)
5049 (cdr property))))
5050 (if property (setcdr property value)
5051 (push (cons 'property value) alist)))))
5052 ((equal key "STARTUP")
5053 (let ((startup (assq 'startup alist)))
5054 (if startup
5055 (setcdr startup
5056 (append (cdr startup) (split-string value)))
5057 (push (cons 'startup (split-string value)) alist))))
5058 ((equal key "TAGS")
5059 (let ((tag-cell (assq 'tags alist)))
5060 (if tag-cell
5061 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5062 (push (cons 'tags value) alist))))
5063 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5064 (let ((todo (assq 'todo alist))
5065 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5066 (split-string value))))
5067 (if todo (push value (cdr todo))
5068 (push (list 'todo value) alist))))
5069 ((equal key "SETUPFILE")
5070 (unless buffer-read-only ; Do not check in Gnus messages.
5071 (let ((f (and (org-string-nw-p value)
5072 (expand-file-name
5073 (org-unbracket-string "\"" "\"" value)))))
5074 (when (and f (file-readable-p f) (not (member f files)))
5075 (with-temp-buffer
5076 (setq default-directory (file-name-directory f))
5077 (insert-file-contents f)
5078 (setq alist
5079 ;; Fake Org mode to benefit from cache
5080 ;; without recurring needlessly.
5081 (let ((major-mode 'org-mode))
5082 (org--setup-collect-keywords
5083 regexp (cons f files) alist)))))))))))))))
5084 alist)
5086 (defun org-tag-string-to-alist (s)
5087 "Return tag alist associated to string S.
5088 S is a value for TAGS keyword or produced with
5089 `org-tag-alist-to-string'. Return value is an alist suitable for
5090 `org-tag-alist' or `org-tag-persistent-alist'."
5091 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5092 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5093 "\\|{.+?}\\)" ; regular expression
5094 "\\(?:(\\(.\\))\\)?\\'"))
5095 alist group-flag)
5096 (dolist (tokens lines (cdr (nreverse alist)))
5097 (push '(:newline) alist)
5098 (while tokens
5099 (let ((token (pop tokens)))
5100 (pcase token
5101 ("{"
5102 (push '(:startgroup) alist)
5103 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5104 ("}"
5105 (push '(:endgroup) alist)
5106 (setq group-flag nil))
5107 ("["
5108 (push '(:startgrouptag) alist)
5109 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5110 ("]"
5111 (push '(:endgrouptag) alist)
5112 (setq group-flag nil))
5113 (":"
5114 (push '(:grouptags) alist))
5115 ((guard (string-match tag-re token))
5116 (let ((tag (match-string 1 token))
5117 (key (and (match-beginning 2)
5118 (string-to-char (match-string 2 token)))))
5119 ;; Push all tags in groups, no matter if they already
5120 ;; appear somewhere else in the list.
5121 (when (or group-flag (not (assoc tag alist)))
5122 (push (cons tag key) alist))))))))))
5124 (defun org-tag-alist-to-string (alist &optional skip-key)
5125 "Return tag string associated to ALIST.
5127 ALIST is an alist, as defined in `org-tag-alist' or
5128 `org-tag-persistent-alist', or produced with
5129 `org-tag-string-to-alist'.
5131 Return value is a string suitable as a value for \"TAGS\"
5132 keyword.
5134 When optional argument SKIP-KEY is non-nil, skip selection keys
5135 next to tags."
5136 (mapconcat (lambda (token)
5137 (pcase token
5138 (`(:startgroup) "{")
5139 (`(:endgroup) "}")
5140 (`(:startgrouptag) "[")
5141 (`(:endgrouptag) "]")
5142 (`(:grouptags) ":")
5143 (`(:newline) "\\n")
5144 ((and
5145 (guard (not skip-key))
5146 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5147 (format "%s(%c)" tag key))
5148 (`(,(and tag (pred stringp)) . ,_) tag)
5149 (_ (user-error "Invalid tag token: %S" token))))
5150 alist
5151 " "))
5153 (defun org-tag-alist-to-groups (alist)
5154 "Return group alist from tag ALIST.
5155 ALIST is an alist, as defined in `org-tag-alist' or
5156 `org-tag-persistent-alist', or produced with
5157 `org-tag-string-to-alist'. Return value is an alist following
5158 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5159 a string, summarizing TAGS, as a list of strings."
5160 (let (groups group-status current-group)
5161 (dolist (token alist (nreverse groups))
5162 (pcase token
5163 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5164 (`(,(or :endgroup :endgrouptag))
5165 (when (eq group-status 'append)
5166 (push (nreverse current-group) groups))
5167 (setq group-status nil))
5168 (`(:grouptags) (setq group-status 'append))
5169 ((and `(,tag . ,_) (guard group-status))
5170 (if (eq group-status 'append) (push tag current-group)
5171 (setq current-group (list tag))))
5172 (_ nil)))))
5174 (defvar org--file-cache (make-hash-table :test #'equal)
5175 "Hash table to store contents of files referenced via a URL.
5176 This is the cache of file URLs read using `org-file-contents'.")
5178 (defun org-reset-file-cache ()
5179 "Reset the cache of files downloaded by `org-file-contents'."
5180 (clrhash org--file-cache))
5182 (defun org-file-url-p (file)
5183 "Non-nil if FILE is a URL."
5184 (require 'ffap)
5185 (string-match-p ffap-url-regexp file))
5187 (defun org-file-contents (file &optional noerror nocache)
5188 "Return the contents of FILE, as a string.
5190 FILE can be a file name or URL.
5192 If FILE is a URL, download the contents. If the URL contents are
5193 already cached in the `org--file-cache' hash table, the download step
5194 is skipped.
5196 If NOERROR is non-nil, ignore the error when unable to read the FILE
5197 from file or URL.
5199 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5200 is available. This option applies only if FILE is a URL."
5201 (let* ((is-url (org-file-url-p file))
5202 (cache (and is-url
5203 (not nocache)
5204 (gethash file org--file-cache))))
5205 (cond
5206 (cache)
5207 (is-url
5208 (with-current-buffer (url-retrieve-synchronously file)
5209 (goto-char (point-min))
5210 ;; Move point to after the url-retrieve header.
5211 (search-forward "\n\n" nil :move)
5212 ;; Search for the success code only in the url-retrieve header.
5213 (if (save-excursion
5214 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5215 ;; Update the cache `org--file-cache' and return contents.
5216 (puthash file
5217 (buffer-substring-no-properties (point) (point-max))
5218 org--file-cache)
5219 (funcall (if noerror #'message #'user-error)
5220 "Unable to fetch file from %S"
5221 file))))
5223 (with-temp-buffer
5224 (condition-case nil
5225 (progn
5226 (insert-file-contents file)
5227 (buffer-string))
5228 (file-error
5229 (funcall (if noerror #'message #'user-error)
5230 "Unable to read file %S"
5231 file))))))))
5233 (defun org-extract-log-state-settings (x)
5234 "Extract the log state setting from a TODO keyword string.
5235 This will extract info from a string like \"WAIT(w@/!)\"."
5236 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5237 (let ((kw (match-string 1 x))
5238 (log1 (and (match-end 3) (match-string 3 x)))
5239 (log2 (and (match-end 4) (match-string 4 x))))
5240 (and (or log1 log2)
5241 (list kw
5242 (and log1 (if (equal log1 "!") 'time 'note))
5243 (and log2 (if (equal log2 "!") 'time 'note)))))))
5245 (defun org-remove-keyword-keys (list)
5246 "Remove a pair of parenthesis at the end of each string in LIST."
5247 (mapcar (lambda (x)
5248 (if (string-match "(.*)$" x)
5249 (substring x 0 (match-beginning 0))
5251 list))
5253 (defun org-assign-fast-keys (alist)
5254 "Assign fast keys to a keyword-key alist.
5255 Respect keys that are already there."
5256 (let (new e (alt ?0))
5257 (while (setq e (pop alist))
5258 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5259 (cdr e)) ;; Key already assigned.
5260 (push e new)
5261 (let ((clist (string-to-list (downcase (car e))))
5262 (used (append new alist)))
5263 (when (= (car clist) ?@)
5264 (pop clist))
5265 (while (and clist (rassoc (car clist) used))
5266 (pop clist))
5267 (unless clist
5268 (while (rassoc alt used)
5269 (cl-incf alt)))
5270 (push (cons (car e) (or (car clist) alt)) new))))
5271 (nreverse new)))
5273 ;;; Some variables used in various places
5275 (defvar org-window-configuration nil
5276 "Used in various places to store a window configuration.")
5277 (defvar org-selected-window nil
5278 "Used in various places to store a window configuration.")
5279 (defvar org-finish-function nil
5280 "Function to be called when `C-c C-c' is used.
5281 This is for getting out of special buffers like capture.")
5282 (defvar org-last-state)
5284 ;; Defined somewhere in this file, but used before definition.
5285 (defvar org-entities) ;; defined in org-entities.el
5286 (defvar org-struct-menu)
5287 (defvar org-org-menu)
5288 (defvar org-tbl-menu)
5290 ;;;; Define the Org mode
5292 ;; We use a before-change function to check if a table might need
5293 ;; an update.
5294 (defvar org-table-may-need-update t
5295 "Indicates that a table might need an update.
5296 This variable is set by `org-before-change-function'.
5297 `org-table-align' sets it back to nil.")
5298 (defun org-before-change-function (_beg _end)
5299 "Every change indicates that a table might need an update."
5300 (setq org-table-may-need-update t))
5301 (defvar org-mode-map)
5302 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5303 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5304 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5305 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5306 (defvar org-table-buffer-is-an nil)
5308 (defvar bidi-paragraph-direction)
5309 (defvar buffer-face-mode-face)
5311 (require 'outline)
5313 ;; Other stuff we need.
5314 (require 'time-date)
5315 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5316 (require 'easymenu)
5317 (autoload 'easy-menu-add "easymenu")
5318 (require 'overlay)
5320 ;; (require 'org-macs) moved higher up in the file before it is first used
5321 (require 'org-entities)
5322 ;; (require 'org-compat) moved higher up in the file before it is first used
5323 (require 'org-faces)
5324 (require 'org-list)
5325 (require 'org-pcomplete)
5326 (require 'org-src)
5327 (require 'org-footnote)
5328 (require 'org-macro)
5330 ;; babel
5331 (require 'ob)
5333 ;;;###autoload
5334 (define-derived-mode org-mode outline-mode "Org"
5335 "Outline-based notes management and organizer, alias
5336 \"Carsten's outline-mode for keeping track of everything.\"
5338 Org mode develops organizational tasks around a NOTES file which
5339 contains information about projects as plain text. Org mode is
5340 implemented on top of Outline mode, which is ideal to keep the content
5341 of large files well structured. It supports ToDo items, deadlines and
5342 time stamps, which magically appear in the diary listing of the Emacs
5343 calendar. Tables are easily created with a built-in table editor.
5344 Plain text URL-like links connect to websites, emails (VM), Usenet
5345 messages (Gnus), BBDB entries, and any files related to the project.
5346 For printing and sharing of notes, an Org file (or a part of it)
5347 can be exported as a structured ASCII or HTML file.
5349 The following commands are available:
5351 \\{org-mode-map}"
5353 ;; Get rid of Outline menus, they are not needed
5354 ;; Need to do this here because define-derived-mode sets up
5355 ;; the keymap so late. Still, it is a waste to call this each time
5356 ;; we switch another buffer into Org mode.
5357 (define-key org-mode-map [menu-bar headings] 'undefined)
5358 (define-key org-mode-map [menu-bar hide] 'undefined)
5359 (define-key org-mode-map [menu-bar show] 'undefined)
5361 (org-load-modules-maybe)
5362 (org-install-agenda-files-menu)
5363 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5364 (add-to-invisibility-spec '(org-hide-block . t))
5365 (add-to-invisibility-spec '(org-hide-drawer . t))
5366 (setq-local outline-regexp org-outline-regexp)
5367 (setq-local outline-level 'org-outline-level)
5368 (setq bidi-paragraph-direction 'left-to-right)
5369 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5370 (unless org-display-table
5371 (setq org-display-table (make-display-table)))
5372 (set-display-table-slot
5373 org-display-table 4
5374 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5375 org-ellipsis)))
5376 (setq buffer-display-table org-display-table))
5377 (org-set-regexps-and-options)
5378 (org-set-font-lock-defaults)
5379 (when (and org-tag-faces (not org-tags-special-faces-re))
5380 ;; tag faces set outside customize.... force initialization.
5381 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5382 ;; Calc embedded
5383 (setq-local calc-embedded-open-mode "# ")
5384 ;; Modify a few syntax entries
5385 (modify-syntax-entry ?@ "w")
5386 (modify-syntax-entry ?\" "\"")
5387 (modify-syntax-entry ?\\ "_")
5388 (modify-syntax-entry ?~ "_")
5389 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5390 ;; Activate before-change-function
5391 (setq-local org-table-may-need-update t)
5392 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5393 ;; Check for running clock before killing a buffer
5394 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5395 ;; Initialize macros templates.
5396 (org-macro-initialize-templates)
5397 ;; Initialize radio targets.
5398 (org-update-radio-target-regexp)
5399 ;; Indentation.
5400 (setq-local indent-line-function 'org-indent-line)
5401 (setq-local indent-region-function 'org-indent-region)
5402 ;; Filling and auto-filling.
5403 (org-setup-filling)
5404 ;; Comments.
5405 (org-setup-comments-handling)
5406 ;; Initialize cache.
5407 (org-element-cache-reset)
5408 ;; Beginning/end of defun
5409 (setq-local beginning-of-defun-function 'org-backward-element)
5410 (setq-local end-of-defun-function
5411 (lambda ()
5412 (if (not (org-at-heading-p))
5413 (org-forward-element)
5414 (org-forward-element)
5415 (forward-char -1))))
5416 ;; Next error for sparse trees
5417 (setq-local next-error-function 'org-occur-next-match)
5418 ;; Make sure dependence stuff works reliably, even for users who set it
5419 ;; too late :-(
5420 (if org-enforce-todo-dependencies
5421 (add-hook 'org-blocker-hook
5422 'org-block-todo-from-children-or-siblings-or-parent)
5423 (remove-hook 'org-blocker-hook
5424 'org-block-todo-from-children-or-siblings-or-parent))
5425 (if org-enforce-todo-checkbox-dependencies
5426 (add-hook 'org-blocker-hook
5427 'org-block-todo-from-checkboxes)
5428 (remove-hook 'org-blocker-hook
5429 'org-block-todo-from-checkboxes))
5431 ;; Align options lines
5432 (setq-local
5433 align-mode-rules-list
5434 '((org-in-buffer-settings
5435 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5436 (modes . '(org-mode)))))
5438 ;; Imenu
5439 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5441 ;; Make isearch reveal context
5442 (setq-local outline-isearch-open-invisible-function
5443 (lambda (&rest _) (org-show-context 'isearch)))
5445 ;; Setup the pcomplete hooks
5446 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5447 (setq-local pcomplete-command-name-function 'org-command-at-point)
5448 (setq-local pcomplete-default-completion-function 'ignore)
5449 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5450 (setq-local pcomplete-termination-string "")
5451 (setq-local buffer-face-mode-face 'org-default)
5453 ;; If empty file that did not turn on Org mode automatically, make
5454 ;; it to.
5455 (when (and org-insert-mode-line-in-empty-file
5456 (called-interactively-p 'any)
5457 (= (point-min) (point-max)))
5458 (insert "# -*- mode: org -*-\n\n"))
5459 (unless org-inhibit-startup
5460 (org-unmodified
5461 (when org-startup-with-beamer-mode (org-beamer-mode))
5462 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5463 (org-table-map-tables
5464 (cond ((and org-startup-align-all-tables
5465 org-startup-shrink-all-tables)
5466 (lambda () (org-table-align) (org-table-shrink)))
5467 (org-startup-align-all-tables #'org-table-align)
5468 (t #'org-table-shrink))
5470 (when org-startup-with-inline-images (org-display-inline-images))
5471 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5472 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5473 (when org-startup-truncated (setq truncate-lines t))
5474 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5475 (org-refresh-effort-properties)))
5476 ;; Try to set `org-hide' face correctly.
5477 (let ((foreground (org-find-invisible-foreground)))
5478 (when foreground
5479 (set-face-foreground 'org-hide foreground))))
5481 ;; Update `customize-package-emacs-version-alist'
5482 (add-to-list 'customize-package-emacs-version-alist
5483 '(Org ("8.0" . "24.4")
5484 ("8.1" . "24.4")
5485 ("8.2" . "24.4")
5486 ("8.2.7" . "24.4")
5487 ("8.3" . "26.1")
5488 ("9.0" . "26.1")
5489 ("9.1" . "26.1")
5490 ("9.2" . "27.1")))
5492 (defvar org-mode-transpose-word-syntax-table
5493 (let ((st (make-syntax-table text-mode-syntax-table)))
5494 (dolist (c org-emphasis-alist st)
5495 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5497 (when (fboundp 'abbrev-table-put)
5498 (abbrev-table-put org-mode-abbrev-table
5499 :parents (list text-mode-abbrev-table)))
5501 (defun org-find-invisible-foreground ()
5502 (let ((candidates (remove
5503 "unspecified-bg"
5504 (nconc
5505 (list (face-background 'default)
5506 (face-background 'org-default))
5507 (mapcar
5508 (lambda (alist)
5509 (when (boundp alist)
5510 (cdr (assq 'background-color (symbol-value alist)))))
5511 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5512 (list (face-foreground 'org-hide))))))
5513 (car (remove nil candidates))))
5515 (defun org-current-time (&optional rounding-minutes past)
5516 "Current time, possibly rounded to ROUNDING-MINUTES.
5517 When ROUNDING-MINUTES is not an integer, fall back on the car of
5518 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5519 the rounding returns a past time."
5520 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5521 (car org-time-stamp-rounding-minutes)))
5522 (time (decode-time)) res)
5523 (if (< r 1)
5524 (current-time)
5525 (setq res
5526 (apply 'encode-time
5527 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5528 (nthcdr 2 time))))
5529 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5530 (seconds-to-time (- (float-time res) (* r 60)))
5531 res))))
5533 (defun org-today ()
5534 "Return today date, considering `org-extend-today-until'."
5535 (time-to-days
5536 (time-subtract (current-time)
5537 (list 0 (* 3600 org-extend-today-until) 0))))
5539 ;;;; Font-Lock stuff, including the activators
5541 (defvar org-mouse-map (make-sparse-keymap))
5542 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5543 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5544 (when org-mouse-1-follows-link
5545 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5546 (when org-tab-follows-link
5547 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5548 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5550 (require 'font-lock)
5552 (defconst org-non-link-chars "]\t\n\r<>")
5553 (defvar org-link-types-re nil
5554 "Matches a link that has a url-like prefix like \"http:\"")
5555 (defvar org-link-re-with-space nil
5556 "Matches a link with spaces, optional angular brackets around it.")
5557 (defvar org-link-re-with-space2 nil
5558 "Matches a link with spaces, optional angular brackets around it.")
5559 (defvar org-link-re-with-space3 nil
5560 "Matches a link with spaces, only for internal part in bracket links.")
5561 (defvar org-angle-link-re nil
5562 "Matches link with angular brackets, spaces are allowed.")
5563 (defvar org-plain-link-re nil
5564 "Matches plain link, without spaces.")
5565 (defvar org-bracket-link-regexp nil
5566 "Matches a link in double brackets.")
5567 (defvar org-bracket-link-analytic-regexp nil
5568 "Regular expression used to analyze links.
5569 Here is what the match groups contain after a match:
5570 1: http:
5571 2: http
5572 3: path
5573 4: [desc]
5574 5: desc")
5575 (defvar org-bracket-link-analytic-regexp++ nil
5576 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5577 (defvar org-any-link-re nil
5578 "Regular expression matching any link.")
5580 (defconst org-match-sexp-depth 3
5581 "Number of stacked braces for sub/superscript matching.")
5583 (defun org-create-multibrace-regexp (left right n)
5584 "Create a regular expression which will match a balanced sexp.
5585 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5586 as single character strings.
5587 The regexp returned will match the entire expression including the
5588 delimiters. It will also define a single group which contains the
5589 match except for the outermost delimiters. The maximum depth of
5590 stacked delimiters is N. Escaping delimiters is not possible."
5591 (let* ((nothing (concat "[^" left right "]*?"))
5592 (or "\\|")
5593 (re nothing)
5594 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5595 (while (> n 1)
5596 (setq n (1- n)
5597 re (concat re or next)
5598 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5599 (concat left "\\(" re "\\)" right)))
5601 (defconst org-match-substring-regexp
5602 (concat
5603 "\\(\\S-\\)\\([_^]\\)\\("
5604 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5605 "\\|"
5606 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5607 "\\|"
5608 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5609 "The regular expression matching a sub- or superscript.")
5611 (defconst org-match-substring-with-braces-regexp
5612 (concat
5613 "\\(\\S-\\)\\([_^]\\)"
5614 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5615 "The regular expression matching a sub- or superscript, forcing braces.")
5617 (defun org-make-link-regexps ()
5618 "Update the link regular expressions.
5619 This should be called after the variable `org-link-parameters' has changed."
5620 (let ((types-re (regexp-opt (org-link-types) t)))
5621 (setq org-link-types-re
5622 (concat "\\`" types-re ":")
5623 org-link-re-with-space
5624 (concat "<?" types-re ":"
5625 "\\([^" org-non-link-chars " ]"
5626 "[^" org-non-link-chars "]*"
5627 "[^" org-non-link-chars " ]\\)>?")
5628 org-link-re-with-space2
5629 (concat "<?" types-re ":"
5630 "\\([^" org-non-link-chars " ]"
5631 "[^\t\n\r]*"
5632 "[^" org-non-link-chars " ]\\)>?")
5633 org-link-re-with-space3
5634 (concat "<?" types-re ":"
5635 "\\([^" org-non-link-chars " ]"
5636 "[^\t\n\r]*\\)")
5637 org-angle-link-re
5638 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5639 types-re)
5640 org-plain-link-re
5641 (concat
5642 "\\<" types-re ":"
5643 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5644 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5645 org-bracket-link-regexp
5646 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5647 org-bracket-link-analytic-regexp
5648 (concat
5649 "\\[\\["
5650 "\\(" types-re ":\\)?"
5651 "\\([^]]+\\)"
5652 "\\]"
5653 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5654 "\\]")
5655 org-bracket-link-analytic-regexp++
5656 (concat
5657 "\\[\\["
5658 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5659 "\\([^]]+\\)"
5660 "\\]"
5661 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5662 "\\]")
5663 org-any-link-re
5664 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5665 org-angle-link-re "\\)\\|\\("
5666 org-plain-link-re "\\)"))))
5668 (org-make-link-regexps)
5670 (defvar org-emph-face nil)
5672 (defun org-do-emphasis-faces (limit)
5673 "Run through the buffer and emphasize strings."
5674 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5675 (car org-emphasis-regexp-components))))
5676 (catch :exit
5677 (while (re-search-forward quick-re limit t)
5678 (let* ((marker (match-string 2))
5679 (verbatim? (member marker '("~" "="))))
5680 (when (save-excursion
5681 (goto-char (match-beginning 0))
5682 (and
5683 ;; Do not match table hlines.
5684 (not (and (equal marker "+")
5685 (org-match-line
5686 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5687 ;; Do not match headline stars. Do not consider
5688 ;; stars of a headline as closing marker for bold
5689 ;; markup either.
5690 (not (and (equal marker "*")
5691 (save-excursion
5692 (forward-char)
5693 (skip-chars-backward "*")
5694 (looking-at-p org-outline-regexp-bol))))
5695 ;; Match full emphasis markup regexp.
5696 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5697 ;; Do not span over paragraph boundaries.
5698 (not (string-match-p org-element-paragraph-separate
5699 (match-string 2)))
5700 ;; Do not span over cells in table rows.
5701 (not (and (save-match-data (org-match-line "[ \t]*|"))
5702 (string-match-p "|" (match-string 4))))))
5703 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5704 (font-lock-prepend-text-property
5705 (match-beginning 2) (match-end 2) 'face face)
5706 (when verbatim?
5707 (org-remove-flyspell-overlays-in
5708 (match-beginning 0) (match-end 0)))
5709 (add-text-properties (match-beginning 2) (match-end 2)
5710 '(font-lock-multiline t org-emphasis t))
5711 (when org-hide-emphasis-markers
5712 (add-text-properties (match-end 4) (match-beginning 5)
5713 '(invisible org-link))
5714 (add-text-properties (match-beginning 3) (match-end 3)
5715 '(invisible org-link)))
5716 (throw :exit t))))))))
5718 (defun org-emphasize (&optional char)
5719 "Insert or change an emphasis, i.e. a font like bold or italic.
5720 If there is an active region, change that region to a new emphasis.
5721 If there is no region, just insert the marker characters and position
5722 the cursor between them.
5723 CHAR should be the marker character. If it is a space, it means to
5724 remove the emphasis of the selected region.
5725 If CHAR is not given (for example in an interactive call) it will be
5726 prompted for."
5727 (interactive)
5728 (let ((erc org-emphasis-regexp-components)
5729 (string "") beg end move s)
5730 (if (org-region-active-p)
5731 (setq beg (region-beginning)
5732 end (region-end)
5733 string (buffer-substring beg end))
5734 (setq move t))
5736 (unless char
5737 (message "Emphasis marker or tag: [%s]"
5738 (mapconcat #'car org-emphasis-alist ""))
5739 (setq char (read-char-exclusive)))
5740 (if (equal char ?\s)
5741 (setq s ""
5742 move nil)
5743 (unless (assoc (char-to-string char) org-emphasis-alist)
5744 (user-error "No such emphasis marker: \"%c\"" char))
5745 (setq s (char-to-string char)))
5746 (while (and (> (length string) 1)
5747 (equal (substring string 0 1) (substring string -1))
5748 (assoc (substring string 0 1) org-emphasis-alist))
5749 (setq string (substring string 1 -1)))
5750 (setq string (concat s string s))
5751 (when beg (delete-region beg end))
5752 (unless (or (bolp)
5753 (string-match (concat "[" (nth 0 erc) "\n]")
5754 (char-to-string (char-before (point)))))
5755 (insert " "))
5756 (unless (or (eobp)
5757 (string-match (concat "[" (nth 1 erc) "\n]")
5758 (char-to-string (char-after (point)))))
5759 (insert " ") (backward-char 1))
5760 (insert string)
5761 (and move (backward-char 1))))
5763 (defconst org-nonsticky-props
5764 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5766 (defsubst org-rear-nonsticky-at (pos)
5767 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5769 (defun org-activate-links (limit)
5770 "Add link properties to links.
5771 This includes angle, plain, and bracket links."
5772 (catch :exit
5773 (while (re-search-forward org-any-link-re limit t)
5774 (let* ((start (match-beginning 0))
5775 (end (match-end 0))
5776 (style (cond ((eq ?< (char-after start)) 'angle)
5777 ((eq ?\[ (char-after (1+ start))) 'bracket)
5778 (t 'plain))))
5779 (when (and (memq style org-highlight-links)
5780 ;; Do not confuse plain links with tags.
5781 (not (and (eq style 'plain)
5782 (let ((face (get-text-property
5783 (max (1- start) (point-min)) 'face)))
5784 (if (consp face) (memq 'org-tag face)
5785 (eq 'org-tag face))))))
5786 (let* ((link-object (save-excursion
5787 (goto-char start)
5788 (save-match-data (org-element-link-parser))))
5789 (link (org-element-property :raw-link link-object))
5790 (type (org-element-property :type link-object))
5791 (path (org-element-property :path link-object))
5792 (properties ;for link's visible part
5793 (list
5794 'face (pcase (org-link-get-parameter type :face)
5795 ((and (pred functionp) face) (funcall face path))
5796 ((and (pred facep) face) face)
5797 ((and (pred consp) face) face) ;anonymous
5798 (_ 'org-link))
5799 'mouse-face (or (org-link-get-parameter type :mouse-face)
5800 'highlight)
5801 'keymap (or (org-link-get-parameter type :keymap)
5802 org-mouse-map)
5803 'help-echo (pcase (org-link-get-parameter type :help-echo)
5804 ((and (pred stringp) echo) echo)
5805 ((and (pred functionp) echo) echo)
5806 (_ (concat "LINK: " link)))
5807 'htmlize-link (pcase (org-link-get-parameter type
5808 :htmlize-link)
5809 ((and (pred functionp) f) (funcall f))
5810 (_ `(:uri ,link)))
5811 'font-lock-multiline t)))
5812 (org-remove-flyspell-overlays-in start end)
5813 (org-rear-nonsticky-at end)
5814 (if (not (eq 'bracket style))
5815 (add-text-properties start end properties)
5816 ;; Handle invisible parts in bracket links.
5817 (remove-text-properties start end '(invisible nil))
5818 (let ((hidden
5819 (append `(invisible
5820 ,(or (org-link-get-parameter type :display)
5821 'org-link))
5822 properties))
5823 (visible-start (or (match-beginning 4) (match-beginning 2)))
5824 (visible-end (or (match-end 4) (match-end 2))))
5825 (add-text-properties start visible-start hidden)
5826 (add-text-properties visible-start visible-end properties)
5827 (add-text-properties visible-end end hidden)
5828 (org-rear-nonsticky-at visible-start)
5829 (org-rear-nonsticky-at visible-end)))
5830 (let ((f (org-link-get-parameter type :activate-func)))
5831 (when (functionp f)
5832 (funcall f start end path (eq style 'bracket))))
5833 (throw :exit t))))) ;signal success
5834 nil))
5836 (defun org-activate-code (limit)
5837 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5838 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5839 (remove-text-properties (match-beginning 0) (match-end 0)
5840 '(display t invisible t intangible t))
5843 (defcustom org-src-fontify-natively t
5844 "When non-nil, fontify code in code blocks.
5845 See also the `org-block' face."
5846 :type 'boolean
5847 :version "26.1"
5848 :package-version '(Org . "8.3")
5849 :group 'org-appearance
5850 :group 'org-babel)
5852 (defcustom org-allow-promoting-top-level-subtree nil
5853 "When non-nil, allow promoting a top level subtree.
5854 The leading star of the top level headline will be replaced
5855 by a #."
5856 :type 'boolean
5857 :version "24.1"
5858 :group 'org-appearance)
5860 (defun org-fontify-meta-lines-and-blocks (limit)
5861 (condition-case nil
5862 (org-fontify-meta-lines-and-blocks-1 limit)
5863 (error (message "Org mode fontification error in %S at %d"
5864 (current-buffer)
5865 (line-number-at-pos)))))
5867 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5868 "Fontify #+ lines and blocks."
5869 (let ((case-fold-search t))
5870 (when (re-search-forward
5871 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5872 limit t)
5873 (let ((beg (match-beginning 0))
5874 (block-start (match-end 0))
5875 (block-end nil)
5876 (lang (match-string 7))
5877 (beg1 (line-beginning-position 2))
5878 (dc1 (downcase (match-string 2)))
5879 (dc3 (downcase (match-string 3)))
5880 end end1 quoting block-type)
5881 (cond
5882 ((and (match-end 4) (equal dc3 "+begin"))
5883 ;; Truly a block
5884 (setq block-type (downcase (match-string 5))
5885 quoting (member block-type org-protecting-blocks))
5886 (when (re-search-forward
5887 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5888 nil t) ;; on purpose, we look further than LIMIT
5889 (setq end (min (point-max) (match-end 0))
5890 end1 (min (point-max) (1- (match-beginning 0))))
5891 (setq block-end (match-beginning 0))
5892 (when quoting
5893 (org-remove-flyspell-overlays-in beg1 end1)
5894 (remove-text-properties beg end
5895 '(display t invisible t intangible t)))
5896 (add-text-properties
5897 beg end '(font-lock-fontified t font-lock-multiline t))
5898 (add-text-properties beg beg1 '(face org-meta-line))
5899 (org-remove-flyspell-overlays-in beg beg1)
5900 (add-text-properties ; For end_src
5901 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5902 (org-remove-flyspell-overlays-in end1 end)
5903 (cond
5904 ((and lang (not (string= lang "")) org-src-fontify-natively)
5905 (org-src-font-lock-fontify-block lang block-start block-end)
5906 (add-text-properties beg1 block-end '(src-block t)))
5907 (quoting
5908 (add-text-properties beg1 (min (point-max) (1+ end1))
5909 (list 'face
5910 (list :inherit
5911 (let ((face-name
5912 (intern (format "org-block-%s" lang))))
5913 (append (and (facep face-name) (list face-name))
5914 '(org-block))))))) ; end of source block
5915 ((not org-fontify-quote-and-verse-blocks))
5916 ((string= block-type "quote")
5917 (add-face-text-property
5918 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5919 ((string= block-type "verse")
5920 (add-face-text-property
5921 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5922 (add-text-properties beg beg1 '(face org-block-begin-line))
5923 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5924 '(face org-block-end-line))
5926 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5927 (org-remove-flyspell-overlays-in
5928 (match-beginning 0)
5929 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5930 (add-text-properties
5931 beg (match-end 3)
5932 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5933 '(font-lock-fontified t invisible t)
5934 '(font-lock-fontified t face org-document-info-keyword)))
5935 (add-text-properties
5936 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5937 (if (string-equal dc1 "+title:")
5938 '(font-lock-fontified t face org-document-title)
5939 '(font-lock-fontified t face org-document-info))))
5940 ((string-prefix-p "+caption" dc1)
5941 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5942 (remove-text-properties (match-beginning 0) (match-end 0)
5943 '(display t invisible t intangible t))
5944 ;; Handle short captions.
5945 (save-excursion
5946 (beginning-of-line)
5947 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5948 (add-text-properties (line-beginning-position) (match-end 1)
5949 '(font-lock-fontified t face org-meta-line))
5950 (add-text-properties (match-end 0) (line-end-position)
5951 '(font-lock-fontified t face org-block))
5953 ((member dc3 '(" " ""))
5954 (org-remove-flyspell-overlays-in beg (match-end 0))
5955 (add-text-properties
5956 beg (match-end 0)
5957 '(font-lock-fontified t face font-lock-comment-face)))
5958 (t ;; just any other in-buffer setting, but not indented
5959 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5960 (remove-text-properties (match-beginning 0) (match-end 0)
5961 '(display t invisible t intangible t))
5962 (add-text-properties beg (match-end 0)
5963 '(font-lock-fontified t face org-meta-line))
5964 t))))))
5966 (defun org-fontify-drawers (limit)
5967 "Fontify drawers."
5968 (when (re-search-forward org-drawer-regexp limit t)
5969 (add-text-properties
5970 (match-beginning 0) (match-end 0)
5971 '(font-lock-fontified t face org-special-keyword))
5972 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5975 (defun org-fontify-macros (limit)
5976 "Fontify macros."
5977 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
5978 (let ((begin (match-beginning 0))
5979 (opening-end (match-beginning 1)))
5980 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
5981 (match-string 1))
5982 (let ((end (match-end 1))
5983 (closing-start (match-beginning 1)))
5984 (add-text-properties
5985 begin end
5986 '(font-lock-multiline t font-lock-fontified t face org-macro))
5987 (org-remove-flyspell-overlays-in begin end)
5988 (when org-hide-macro-markers
5989 (add-text-properties begin opening-end '(invisible t))
5990 (add-text-properties closing-start end '(invisible t)))
5991 t)))))
5993 (defun org-activate-footnote-links (limit)
5994 "Add text properties for footnotes."
5995 (let ((fn (org-footnote-next-reference-or-definition limit)))
5996 (when fn
5997 (let* ((beg (nth 1 fn))
5998 (end (nth 2 fn))
5999 (label (car fn))
6000 (referencep (/= (line-beginning-position) beg)))
6001 (when (and referencep (nth 3 fn))
6002 (save-excursion
6003 (goto-char beg)
6004 (search-forward (or label "fn:"))
6005 (org-remove-flyspell-overlays-in beg (match-end 0))))
6006 (add-text-properties beg end
6007 (list 'mouse-face 'highlight
6008 'keymap org-mouse-map
6009 'help-echo
6010 (if referencep "Footnote reference"
6011 "Footnote definition")
6012 'font-lock-fontified t
6013 'font-lock-multiline t
6014 'face 'org-footnote))))))
6016 (defun org-activate-dates (limit)
6017 "Add text properties for dates."
6018 (when (and (re-search-forward org-tsr-regexp-both limit t)
6019 (not (equal (char-before (match-beginning 0)) 91)))
6020 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6021 (add-text-properties (match-beginning 0) (match-end 0)
6022 (list 'mouse-face 'highlight
6023 'keymap org-mouse-map))
6024 (org-rear-nonsticky-at (match-end 0))
6025 (when org-display-custom-times
6026 ;; If it's a date range, activate custom time for second date.
6027 (when (match-end 3)
6028 (org-display-custom-time (match-beginning 3) (match-end 3)))
6029 (org-display-custom-time (match-beginning 1) (match-end 1)))
6032 (defvar-local org-target-link-regexp nil
6033 "Regular expression matching radio targets in plain text.")
6035 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6036 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6037 border border border))
6038 "Regular expression matching a link target.")
6040 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6041 "Regular expression matching a radio target.")
6043 (defconst org-any-target-regexp
6044 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6045 "Regular expression matching any target.")
6047 (defun org-activate-target-links (limit)
6048 "Add text properties for target matches."
6049 (when org-target-link-regexp
6050 (let ((case-fold-search t))
6051 (when (re-search-forward org-target-link-regexp limit t)
6052 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6053 (add-text-properties (match-beginning 1) (match-end 1)
6054 (list 'mouse-face 'highlight
6055 'keymap org-mouse-map
6056 'help-echo "Radio target link"
6057 'org-linked-text t))
6058 (org-rear-nonsticky-at (match-end 1))
6059 t))))
6061 (defun org-update-radio-target-regexp ()
6062 "Find all radio targets in this file and update the regular expression.
6063 Also refresh fontification if needed."
6064 (interactive)
6065 (let ((old-regexp org-target-link-regexp)
6066 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6067 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6068 (targets
6069 (org-with-wide-buffer
6070 (goto-char (point-min))
6071 (let (rtn)
6072 (while (re-search-forward org-radio-target-regexp nil t)
6073 ;; Make sure point is really within the object.
6074 (backward-char)
6075 (let ((obj (org-element-context)))
6076 (when (eq (org-element-type obj) 'radio-target)
6077 (cl-pushnew (org-element-property :value obj) rtn
6078 :test #'equal))))
6079 rtn))))
6080 (setq org-target-link-regexp
6081 (and targets
6082 (concat before-re
6083 (mapconcat
6084 (lambda (x)
6085 (replace-regexp-in-string
6086 " +" "\\s-+" (regexp-quote x) t t))
6087 targets
6088 "\\|")
6089 after-re)))
6090 (unless (equal old-regexp org-target-link-regexp)
6091 ;; Clean-up cache.
6092 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6093 ((not org-target-link-regexp) old-regexp)
6095 (concat before-re
6096 (mapconcat
6097 (lambda (re)
6098 (substring re (length before-re)
6099 (- (length after-re))))
6100 (list old-regexp org-target-link-regexp)
6101 "\\|")
6102 after-re)))))
6103 (org-with-wide-buffer
6104 (goto-char (point-min))
6105 (while (re-search-forward regexp nil t)
6106 (org-element-cache-refresh (match-beginning 1)))))
6107 ;; Re fontify buffer.
6108 (when (memq 'radio org-highlight-links)
6109 (org-restart-font-lock)))))
6111 (defvar org-latex-and-related-regexp nil
6112 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6114 (defun org-compute-latex-and-related-regexp ()
6115 "Compute regular expression for LaTeX, entities and sub/superscript.
6116 Result depends on variable `org-highlight-latex-and-related'."
6117 (setq-local
6118 org-latex-and-related-regexp
6119 (let* ((re-sub
6120 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6121 ((eq org-use-sub-superscripts '{})
6122 (list org-match-substring-with-braces-regexp))
6123 (org-use-sub-superscripts (list org-match-substring-regexp))))
6124 (re-latex
6125 (when (memq 'latex org-highlight-latex-and-related)
6126 (let ((matchers (plist-get org-format-latex-options :matchers)))
6127 (delq nil
6128 (mapcar (lambda (x)
6129 (and (member (car x) matchers) (nth 1 x)))
6130 org-latex-regexps)))))
6131 (re-entities
6132 (when (memq 'entities org-highlight-latex-and-related)
6133 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6134 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6136 (defun org-do-latex-and-related (limit)
6137 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6138 LIMIT bounds the search for syntax to highlight. Stop at first
6139 highlighted object, if any. Return t if some highlighting was
6140 done, nil otherwise."
6141 (when (org-string-nw-p org-latex-and-related-regexp)
6142 (catch 'found
6143 (while (re-search-forward org-latex-and-related-regexp limit t)
6144 (unless
6145 (cl-some
6146 (lambda (f)
6147 (memq f '(org-code org-verbatim underline org-special-keyword)))
6148 (save-excursion
6149 (goto-char (1+ (match-beginning 0)))
6150 (face-at-point nil t)))
6151 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6152 '(?_ ?^))
6154 0)))
6155 (font-lock-prepend-text-property
6156 (+ offset (match-beginning 0)) (match-end 0)
6157 'face 'org-latex-and-related)
6158 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6159 '(font-lock-multiline t)))
6160 (throw 'found t)))
6161 nil)))
6163 (defun org-restart-font-lock ()
6164 "Restart `font-lock-mode', to force refontification."
6165 (when (and (boundp 'font-lock-mode) font-lock-mode)
6166 (font-lock-mode -1)
6167 (font-lock-mode 1)))
6169 (defun org-activate-tags (limit)
6170 (when (re-search-forward
6171 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6172 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6173 (add-text-properties (match-beginning 1) (match-end 1)
6174 (list 'mouse-face 'highlight
6175 'keymap org-mouse-map))
6176 (org-rear-nonsticky-at (match-end 1))
6179 (defun org-outline-level ()
6180 "Compute the outline level of the heading at point.
6182 If this is called at a normal headline, the level is the number
6183 of stars. Use `org-reduced-level' to remove the effect of
6184 `org-odd-levels'. Unlike to `org-current-level', this function
6185 takes into consideration inlinetasks."
6186 (org-with-wide-buffer
6187 (end-of-line)
6188 (if (re-search-backward org-outline-regexp-bol nil t)
6189 (1- (- (match-end 0) (match-beginning 0)))
6190 0)))
6192 (defvar org-font-lock-keywords nil)
6194 (defsubst org-re-property (property &optional literal allow-null value)
6195 "Return a regexp matching a PROPERTY line.
6197 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6198 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6199 non-nil, match properties even without a value.
6201 Match group 3 is set to the value when it exists. If there is no
6202 value and ALLOW-NULL is non-nil, it is set to the empty string.
6204 With optional argument VALUE, match only property lines with
6205 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6206 unless LITERAL is non-nil."
6207 (concat
6208 "^\\(?4:[ \t]*\\)"
6209 (format "\\(?1::\\(?2:%s\\):\\)"
6210 (if literal property (regexp-quote property)))
6211 (cond (value
6212 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6213 (if literal value (regexp-quote value))))
6214 (allow-null
6215 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6217 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6219 (defconst org-property-re
6220 (org-re-property "\\S-+" 'literal t)
6221 "Regular expression matching a property line.
6222 There are four matching groups:
6223 1: :PROPKEY: including the leading and trailing colon,
6224 2: PROPKEY without the leading and trailing colon,
6225 3: PROPVAL without leading or trailing spaces,
6226 4: the indentation of the current line,
6227 5: trailing whitespace.")
6229 (defvar org-font-lock-hook nil
6230 "Functions to be called for special font lock stuff.")
6232 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6234 (defvar org-font-lock-set-keywords-hook nil
6235 "Functions that can manipulate `org-font-lock-extra-keywords'.
6236 This is called after `org-font-lock-extra-keywords' is defined, but before
6237 it is installed to be used by font lock. This can be useful if something
6238 needs to be inserted at a specific position in the font-lock sequence.")
6240 (defun org-font-lock-hook (limit)
6241 "Run `org-font-lock-hook' within LIMIT."
6242 (run-hook-with-args 'org-font-lock-hook limit))
6244 (defun org-set-font-lock-defaults ()
6245 "Set font lock defaults for the current buffer."
6246 (let* ((em org-fontify-emphasized-text)
6247 (lk org-highlight-links)
6248 (org-font-lock-extra-keywords
6249 (list
6250 ;; Call the hook
6251 '(org-font-lock-hook)
6252 ;; Headlines
6253 `(,(if org-fontify-whole-heading-line
6254 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6255 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6256 (1 (org-get-level-face 1))
6257 (2 (org-get-level-face 2))
6258 (3 (org-get-level-face 3)))
6259 ;; Table lines
6260 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6261 (1 'org-table t))
6262 ;; Table internals
6263 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6264 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6265 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6266 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6267 ;; Drawers
6268 '(org-fontify-drawers)
6269 ;; Properties
6270 (list org-property-re
6271 '(1 'org-special-keyword t)
6272 '(3 'org-property-value t))
6273 ;; Link related fontification.
6274 '(org-activate-links)
6275 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6276 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6277 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6278 (when (memq 'footnote lk) '(org-activate-footnote-links))
6279 ;; Targets.
6280 (list org-any-target-regexp '(0 'org-target t))
6281 ;; Diary sexps.
6282 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6283 ;; Macro
6284 '(org-fontify-macros)
6285 ;; TODO keyword
6286 (list (format org-heading-keyword-regexp-format
6287 org-todo-regexp)
6288 '(2 (org-get-todo-face 2) t))
6289 ;; DONE
6290 (if org-fontify-done-headline
6291 (list (format org-heading-keyword-regexp-format
6292 (concat
6293 "\\(?:"
6294 (mapconcat 'regexp-quote org-done-keywords "\\|")
6295 "\\)"))
6296 '(2 'org-headline-done t))
6297 nil)
6298 ;; Priorities
6299 '(org-font-lock-add-priority-faces)
6300 ;; Tags
6301 '(org-font-lock-add-tag-faces)
6302 ;; Tags groups
6303 (when (and org-group-tags org-tag-groups-alist)
6304 (list (concat org-outline-regexp-bol ".+\\(:"
6305 (regexp-opt (mapcar 'car org-tag-groups-alist))
6306 ":\\).*$")
6307 '(1 'org-tag-group prepend)))
6308 ;; Special keywords
6309 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6310 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6311 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6312 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6313 ;; Emphasis
6314 (when em '(org-do-emphasis-faces))
6315 ;; Checkboxes
6316 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6317 1 'org-checkbox prepend)
6318 (when (cdr (assq 'checkbox org-list-automatic-rules))
6319 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6320 (0 (org-get-checkbox-statistics-face) t)))
6321 ;; Description list items
6322 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6323 1 'org-list-dt prepend)
6324 ;; ARCHIVEd headings
6325 (list (concat
6326 org-outline-regexp-bol
6327 "\\(.*:" org-archive-tag ":.*\\)")
6328 '(1 'org-archived prepend))
6329 ;; Specials
6330 '(org-do-latex-and-related)
6331 '(org-fontify-entities)
6332 '(org-raise-scripts)
6333 ;; Code
6334 '(org-activate-code (1 'org-code t))
6335 ;; COMMENT
6336 (list (format
6337 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6338 org-todo-regexp
6339 org-comment-string)
6340 '(9 'org-special-keyword t))
6341 ;; Blocks and meta lines
6342 '(org-fontify-meta-lines-and-blocks))))
6343 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6344 (run-hooks 'org-font-lock-set-keywords-hook)
6345 ;; Now set the full font-lock-keywords
6346 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6347 (setq-local font-lock-defaults
6348 '(org-font-lock-keywords t nil nil backward-paragraph))
6349 (kill-local-variable 'font-lock-keywords)
6350 nil))
6352 (defun org-toggle-pretty-entities ()
6353 "Toggle the composition display of entities as UTF8 characters."
6354 (interactive)
6355 (setq-local org-pretty-entities (not org-pretty-entities))
6356 (org-restart-font-lock)
6357 (if org-pretty-entities
6358 (message "Entities are now displayed as UTF8 characters")
6359 (save-restriction
6360 (widen)
6361 (decompose-region (point-min) (point-max))
6362 (message "Entities are now displayed as plain text"))))
6364 (defvar-local org-custom-properties-overlays nil
6365 "List of overlays used for custom properties.")
6367 (defun org-toggle-custom-properties-visibility ()
6368 "Display or hide properties in `org-custom-properties'."
6369 (interactive)
6370 (if org-custom-properties-overlays
6371 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6372 (setq org-custom-properties-overlays nil))
6373 (when org-custom-properties
6374 (org-with-wide-buffer
6375 (goto-char (point-min))
6376 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6377 (while (re-search-forward regexp nil t)
6378 (let ((end (cdr (save-match-data (org-get-property-block)))))
6379 (when (and end (< (point) end))
6380 ;; Hide first custom property in current drawer.
6381 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6382 (overlay-put o 'invisible t)
6383 (overlay-put o 'org-custom-property t)
6384 (push o org-custom-properties-overlays))
6385 ;; Hide additional custom properties in the same drawer.
6386 (while (re-search-forward regexp end t)
6387 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6388 (overlay-put o 'invisible t)
6389 (overlay-put o 'org-custom-property t)
6390 (push o org-custom-properties-overlays)))))
6391 ;; Each entry is limited to a single property drawer.
6392 (outline-next-heading)))))))
6394 (defun org-fontify-entities (limit)
6395 "Find an entity to fontify."
6396 (let (ee)
6397 (when org-pretty-entities
6398 (catch 'match
6399 ;; "\_ "-family is left out on purpose. Only the first one,
6400 ;; i.e., "\_ ", could be fontified anyway, and it would be
6401 ;; confusing when adding a second white space character.
6402 (while (re-search-forward
6403 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6404 limit t)
6405 (when (and (not (org-at-comment-p))
6406 (setq ee (org-entity-get (match-string 1)))
6407 (= (length (nth 6 ee)) 1))
6408 (let* ((end (if (equal (match-string 2) "{}")
6409 (match-end 2)
6410 (match-end 1))))
6411 (add-text-properties
6412 (match-beginning 0) end
6413 (list 'font-lock-fontified t))
6414 (compose-region (match-beginning 0) end
6415 (nth 6 ee) nil)
6416 (backward-char 1)
6417 (throw 'match t))))
6418 nil))))
6420 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6421 "Fontify string S like in Org mode."
6422 (with-temp-buffer
6423 (insert s)
6424 (let ((org-odd-levels-only odd-levels))
6425 (org-mode)
6426 (org-font-lock-ensure)
6427 (buffer-string))))
6429 (defvar org-m nil)
6430 (defvar org-l nil)
6431 (defvar org-f nil)
6432 (defun org-get-level-face (n)
6433 "Get the right face for match N in font-lock matching of headlines."
6434 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6435 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6436 (if org-cycle-level-faces
6437 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6438 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6439 (cond
6440 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6441 ((eq n 2) org-f)
6442 (t (unless org-level-color-stars-only org-f))))
6444 (defun org-face-from-face-or-color (context inherit face-or-color)
6445 "Create a face list that inherits INHERIT, but sets the foreground color.
6446 When FACE-OR-COLOR is not a string, just return it."
6447 (if (stringp face-or-color)
6448 (list :inherit inherit
6449 (cdr (assoc context org-faces-easy-properties))
6450 face-or-color)
6451 face-or-color))
6453 (defun org-get-todo-face (kwd)
6454 "Get the right face for a TODO keyword KWD.
6455 If KWD is a number, get the corresponding match group."
6456 (when (numberp kwd) (setq kwd (match-string kwd)))
6457 (or (org-face-from-face-or-color
6458 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6459 (and (member kwd org-done-keywords) 'org-done)
6460 'org-todo))
6462 (defun org-get-priority-face (priority)
6463 "Get the right face for PRIORITY.
6464 PRIORITY is a character."
6465 (or (org-face-from-face-or-color
6466 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6467 'org-priority))
6469 (defun org-get-tag-face (tag)
6470 "Get the right face for TAG.
6471 If TAG is a number, get the corresponding match group."
6472 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6473 (or (org-face-from-face-or-color
6474 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6475 'org-tag)))
6477 (defun org-font-lock-add-priority-faces (limit)
6478 "Add the special priority faces."
6479 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6480 (add-text-properties
6481 (match-beginning 1) (match-end 1)
6482 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6483 'font-lock-fontified t))))
6485 (defun org-font-lock-add-tag-faces (limit)
6486 "Add the special tag faces."
6487 (when (and org-tag-faces org-tags-special-faces-re)
6488 (while (re-search-forward org-tags-special-faces-re limit t)
6489 (add-text-properties (match-beginning 1) (match-end 1)
6490 (list 'face (org-get-tag-face 1)
6491 'font-lock-fontified t))
6492 (backward-char 1))))
6494 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6495 "Remove fontification and activation overlays from links."
6496 (font-lock-default-unfontify-region beg end)
6497 (let* ((buffer-undo-list t)
6498 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6499 (inhibit-modification-hooks t)
6500 deactivate-mark buffer-file-name buffer-file-truename)
6501 (decompose-region beg end)
6502 (remove-text-properties beg end
6503 '(mouse-face t keymap t org-linked-text t
6504 invisible t intangible t
6505 org-emphasis t))
6506 (org-remove-font-lock-display-properties beg end)))
6508 (defconst org-script-display '(((raise -0.3) (height 0.7))
6509 ((raise 0.3) (height 0.7))
6510 ((raise -0.5))
6511 ((raise 0.5)))
6512 "Display properties for showing superscripts and subscripts.")
6514 (defun org-remove-font-lock-display-properties (beg end)
6515 "Remove specific display properties that have been added by font lock.
6516 The will remove the raise properties that are used to show superscripts
6517 and subscripts."
6518 (let (next prop)
6519 (while (< beg end)
6520 (setq next (next-single-property-change beg 'display nil end)
6521 prop (get-text-property beg 'display))
6522 (when (member prop org-script-display)
6523 (put-text-property beg next 'display nil))
6524 (setq beg next))))
6526 (defun org-raise-scripts (limit)
6527 "Add raise properties to sub/superscripts."
6528 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6529 (re-search-forward
6530 (if (eq org-use-sub-superscripts t)
6531 org-match-substring-regexp
6532 org-match-substring-with-braces-regexp)
6533 limit t))
6534 (let* ((pos (point)) table-p comment-p
6535 (mpos (match-beginning 3))
6536 (emph-p (get-text-property mpos 'org-emphasis))
6537 (link-p (get-text-property mpos 'mouse-face))
6538 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6539 (goto-char (point-at-bol))
6540 (setq table-p (looking-at-p org-table-dataline-regexp)
6541 comment-p (looking-at-p "^[ \t]*#[ +]"))
6542 (goto-char pos)
6543 ;; Handle a_b^c
6544 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6545 (unless (or comment-p emph-p link-p keyw-p)
6546 (put-text-property (match-beginning 3) (match-end 0)
6547 'display
6548 (if (equal (char-after (match-beginning 2)) ?^)
6549 (nth (if table-p 3 1) org-script-display)
6550 (nth (if table-p 2 0) org-script-display)))
6551 (add-text-properties (match-beginning 2) (match-end 2)
6552 (list 'invisible t))
6553 (when (and (eq (char-after (match-beginning 3)) ?{)
6554 (eq (char-before (match-end 3)) ?}))
6555 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6556 (list 'invisible t))
6557 (add-text-properties (1- (match-end 3)) (match-end 3)
6558 (list 'invisible t))))
6559 t)))
6561 (defun org-remove-empty-overlays-at (pos)
6562 "Remove outline overlays that do not contain non-white stuff."
6563 (dolist (o (overlays-at pos))
6564 (and (eq 'outline (overlay-get o 'invisible))
6565 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6566 (overlay-end o))))
6567 (delete-overlay o))))
6569 (defun org-show-empty-lines-in-parent ()
6570 "Move to the parent and re-show empty lines before visible headlines."
6571 (save-excursion
6572 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6573 (org-cycle-show-empty-lines context))))
6575 (defun org-files-list ()
6576 "Return `org-agenda-files' list, plus all open Org files.
6577 This is useful for operations that need to scan all of a user's
6578 open and agenda-wise Org files."
6579 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6580 (dolist (buf (buffer-list))
6581 (with-current-buffer buf
6582 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6583 (cl-pushnew (expand-file-name (buffer-file-name)) files
6584 :test #'equal))))
6585 files))
6587 (defsubst org-entry-beginning-position ()
6588 "Return the beginning position of the current entry."
6589 (save-excursion (org-back-to-heading t) (point)))
6591 (defsubst org-entry-end-position ()
6592 "Return the end position of the current entry."
6593 (save-excursion (outline-next-heading) (point)))
6595 (defun org-subtree-end-visible-p ()
6596 "Is the end of the current subtree visible?"
6597 (pos-visible-in-window-p
6598 (save-excursion (org-end-of-subtree t) (point))))
6600 (defun org-first-headline-recenter ()
6601 "Move cursor to the first headline and recenter the headline."
6602 (let ((window (get-buffer-window)))
6603 (when window
6604 (goto-char (point-min))
6605 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6606 (set-window-start window (line-beginning-position))))))
6609 ;;; Visibility (headlines, blocks, drawers)
6611 ;;;; Headlines visibility
6613 (defun org-show-entry ()
6614 "Show the body directly following this heading.
6615 Show the heading too, if it is currently invisible."
6616 (interactive)
6617 (save-excursion
6618 (ignore-errors
6619 (org-back-to-heading t)
6620 (org-flag-region
6621 (line-end-position 0)
6622 (save-excursion
6623 (if (re-search-forward
6624 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6625 (match-beginning 1)
6626 (point-max)))
6628 'outline))))
6630 (defun org-show-children (&optional level)
6631 "Show all direct subheadings of this heading.
6632 Prefix arg LEVEL is how many levels below the current level
6633 should be shown. Default is enough to cause the following
6634 heading to appear."
6635 (interactive "p")
6636 (save-excursion
6637 (org-back-to-heading t)
6638 (let* ((current-level (funcall outline-level))
6639 (max-level (org-get-valid-level
6640 current-level
6641 (if level (prefix-numeric-value level) 1)))
6642 (end (save-excursion (org-end-of-subtree t t)))
6643 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6644 (past-first-child nil)
6645 ;; Make sure to skip inlinetasks.
6646 (re (format regexp-fmt
6647 current-level
6648 (cond
6649 ((not (featurep 'org-inlinetask)) "")
6650 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6652 (t (1- org-inlinetask-min-level))))))
6653 ;; Display parent heading.
6654 (org-flag-heading nil)
6655 (forward-line)
6656 ;; Display children. First child may be deeper than expected
6657 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6658 ;; MAX-LEVEL accordingly.
6659 (while (re-search-forward re end t)
6660 (unless past-first-child
6661 (setq re (format regexp-fmt
6662 current-level
6663 (max (funcall outline-level) max-level)))
6664 (setq past-first-child t))
6665 (org-flag-heading nil)))))
6667 (defun org-show-subtree ()
6668 "Show everything after this heading at deeper levels."
6669 (interactive)
6670 (org-flag-region
6671 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6673 ;;;; Blocks visibility
6675 (defun org-hide-block-toggle-maybe ()
6676 "Toggle visibility of block at point.
6677 Unlike to `org-hide-block-toggle', this function does not throw
6678 an error. Return a non-nil value when toggling is successful."
6679 (interactive)
6680 (ignore-errors (org-hide-block-toggle)))
6682 (defun org-hide-block-toggle (&optional force)
6683 "Toggle the visibility of the current block.
6684 When optional argument FORCE is `off', make block visible. If it
6685 is non-nil, hide it unconditionally. Throw an error when not at
6686 a block. Return a non-nil value when toggling is successful."
6687 (interactive)
6688 (let ((element (org-element-at-point)))
6689 (unless (memq (org-element-type element)
6690 '(center-block comment-block dynamic-block example-block
6691 export-block quote-block special-block
6692 src-block verse-block))
6693 (user-error "Not at a block"))
6694 (let* ((post (org-element-property :post-affiliated element))
6695 (start (save-excursion
6696 (goto-char post)
6697 (line-end-position)))
6698 (end (save-excursion
6699 (goto-char (org-element-property :end element))
6700 (skip-chars-backward " \t\n")
6701 (line-end-position))))
6702 ;; Do nothing when not before or at the block opening line or at
6703 ;; the block closing line.
6704 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6705 (cond ((eq force 'off)
6706 (org-flag-region start end nil 'org-hide-block))
6707 (force
6708 (org-flag-region start end t 'org-hide-block))
6709 ((eq (get-char-property start 'invisible) 'org-hide-block)
6710 (org-flag-region start end nil 'org-hide-block))
6712 (org-flag-region start end t 'org-hide-block)))
6713 ;; When the block is hidden away, make sure point is left in
6714 ;; a visible part of the buffer.
6715 (when (invisible-p (max (1- (point)) (point-min)))
6716 (goto-char post))
6717 ;; Signal success.
6718 t))))
6720 (defun org-hide-block-toggle-all ()
6721 "Toggle the visibility of all blocks in the current buffer."
6722 (org-block-map 'org-hide-block-toggle))
6724 (defun org-hide-block-all ()
6725 "Fold all blocks in the current buffer."
6726 (interactive)
6727 (org-show-all '(blocks))
6728 (org-block-map 'org-hide-block-toggle-maybe))
6730 ;;;; Drawers visibility
6732 (defun org-cycle-hide-drawers (state &optional exceptions)
6733 "Re-hide all drawers after a visibility state change.
6734 STATE should be one of the symbols listed in the docstring of
6735 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6736 a list of strings specifying which drawers should not be hidden."
6737 (when (and (derived-mode-p 'org-mode)
6738 (not (memq state '(overview folded contents))))
6739 (save-excursion
6740 (let* ((globalp (eq state 'all))
6741 (beg (if globalp (point-min) (point)))
6742 (end (if globalp (point-max)
6743 (if (eq state 'children)
6744 (save-excursion (outline-next-heading) (point))
6745 (org-end-of-subtree t)))))
6746 (goto-char beg)
6747 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6748 (unless (member-ignore-case (match-string 1) exceptions)
6749 (let ((drawer (org-element-at-point)))
6750 (when (memq (org-element-type drawer) '(drawer property-drawer))
6751 (org-flag-drawer t drawer)
6752 ;; Make sure to skip drawer entirely or we might flag
6753 ;; it another time when matching its ending line with
6754 ;; `org-drawer-regexp'.
6755 (goto-char (org-element-property :end drawer))))))))))
6757 (defun org-flag-drawer (flag &optional element)
6758 "When FLAG is non-nil, hide the drawer we are at.
6759 Otherwise make it visible. When optional argument ELEMENT is
6760 a parsed drawer, as returned by `org-element-at-point', hide or
6761 show that drawer instead."
6762 (let ((drawer (or element
6763 (and (save-excursion
6764 (beginning-of-line)
6765 (looking-at-p org-drawer-regexp))
6766 (org-element-at-point)))))
6767 (when (memq (org-element-type drawer) '(drawer property-drawer))
6768 (let ((post (org-element-property :post-affiliated drawer)))
6769 (org-flag-region
6770 (save-excursion (goto-char post) (line-end-position))
6771 (save-excursion (goto-char (org-element-property :end drawer))
6772 (skip-chars-backward " \t\n")
6773 (line-end-position))
6774 flag 'org-hide-drawer)
6775 ;; When the drawer is hidden away, make sure point lies in
6776 ;; a visible part of the buffer.
6777 (when (invisible-p (max (1- (point)) (point-min)))
6778 (goto-char post))))))
6780 ;;;; Visibility cycling
6782 (defvar-local org-cycle-global-status nil)
6783 (put 'org-cycle-global-status 'org-state t)
6784 (defvar-local org-cycle-subtree-status nil)
6785 (put 'org-cycle-subtree-status 'org-state t)
6787 (defun org-show-all (&optional types)
6788 "Show all contents in the visible part of the buffer.
6789 By default, the function expands headings, blocks and drawers.
6790 When optional argument TYPE is a list of symbols among `blocks',
6791 `drawers' and `headings', to only expand one specific type."
6792 (dolist (type (or types '(blocks drawers headings)))
6793 (org-flag-region (point-min) (point-max) nil
6794 (pcase type
6795 (`blocks 'org-hide-block)
6796 (`drawers 'org-hide-drawer)
6797 (`headings 'outline)
6798 (_ (error "Invalid type: %S" type))))))
6800 ;;;###autoload
6801 (defun org-cycle (&optional arg)
6802 "TAB-action and visibility cycling for Org mode.
6804 This is the command invoked in Org mode by the `TAB' key. Its main
6805 purpose is outline visibility cycling, but it also invokes other actions
6806 in special contexts.
6808 When this function is called with a `\\[universal-argument]' prefix, rotate \
6809 the entire
6810 buffer through 3 states (global cycling)
6811 1. OVERVIEW: Show only top-level headlines.
6812 2. CONTENTS: Show all headlines of all levels, but no body text.
6813 3. SHOW ALL: Show everything.
6815 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6816 switch to the startup visibility,
6817 determined by the variable `org-startup-folded', and by any VISIBILITY
6818 properties in the buffer.
6820 With a `\\[universal-argument] \\[universal-argument] \
6821 \\[universal-argument]' prefix argument, show the entire buffer, including
6822 any drawers.
6824 When inside a table, re-align the table and move to the next field.
6826 When point is at the beginning of a headline, rotate the subtree started
6827 by this line through 3 different states (local cycling)
6828 1. FOLDED: Only the main headline is shown.
6829 2. CHILDREN: The main headline and the direct children are shown.
6830 From this state, you can move to one of the children
6831 and zoom in further.
6832 3. SUBTREE: Show the entire subtree, including body text.
6833 If there is no subtree, switch directly from CHILDREN to FOLDED.
6835 When point is at the beginning of an empty headline and the variable
6836 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6837 of the headline by demoting and promoting it to likely levels. This
6838 speeds up creation document structure by pressing `TAB' once or several
6839 times right after creating a new headline.
6841 When there is a numeric prefix, go up to a heading with level ARG, do
6842 a `show-subtree' and return to the previous cursor position. If ARG
6843 is negative, go up that many levels.
6845 When point is not at the beginning of a headline, execute the global
6846 binding for `TAB', which is re-indenting the line. See the option
6847 `org-cycle-emulate-tab' for details.
6849 As a special case, if point is at the beginning of the buffer and there is
6850 no headline in line 1, this function will act as if called with prefix arg
6851 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6852 prefix arg, but only
6853 if the variable `org-cycle-global-at-bob' is t."
6854 (interactive "P")
6855 (org-load-modules-maybe)
6856 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6857 (and org-cycle-level-after-item/entry-creation
6858 (or (org-cycle-level)
6859 (org-cycle-item-indentation))))
6860 (let* ((limit-level
6861 (or org-cycle-max-level
6862 (and (boundp 'org-inlinetask-min-level)
6863 org-inlinetask-min-level
6864 (1- org-inlinetask-min-level))))
6865 (nstars (and limit-level
6866 (if org-odd-levels-only
6867 (and limit-level (1- (* limit-level 2)))
6868 limit-level)))
6869 (org-outline-regexp
6870 (if (not (derived-mode-p 'org-mode))
6871 outline-regexp
6872 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6873 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6874 (not (looking-at org-outline-regexp))))
6875 (org-cycle-hook
6876 (if bob-special
6877 (delq 'org-optimize-window-after-visibility-change
6878 (copy-sequence org-cycle-hook))
6879 org-cycle-hook))
6880 (pos (point)))
6882 (cond
6884 ((equal arg '(16))
6885 (setq last-command 'dummy)
6886 (org-set-startup-visibility)
6887 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6889 ((equal arg '(64))
6890 (org-show-all)
6891 (org-unlogged-message "Entire buffer visible, including drawers"))
6893 ((equal arg '(4)) (org-cycle-internal-global))
6895 ;; Try hiding block at point.
6896 ((org-hide-block-toggle-maybe))
6898 ;; Try cdlatex TAB completion
6899 ((org-try-cdlatex-tab))
6901 ;; Table: enter it or move to the next field.
6902 ((org-at-table-p 'any)
6903 (if (org-at-table.el-p)
6904 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6905 Use `\\[org-edit-special]' to edit table.el tables"))
6906 (if arg (org-table-edit-field t)
6907 (org-table-justify-field-maybe)
6908 (call-interactively 'org-table-next-field))))
6910 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6912 ;; Global cycling: delegate to `org-cycle-internal-global'.
6913 (bob-special (org-cycle-internal-global))
6915 ;; Drawers: delegate to `org-flag-drawer'.
6916 ((save-excursion
6917 (beginning-of-line 1)
6918 (looking-at org-drawer-regexp))
6919 (org-flag-drawer ; toggle block visibility
6920 (not (get-char-property (match-end 0) 'invisible))))
6922 ;; Show-subtree, ARG levels up from here.
6923 ((integerp arg)
6924 (save-excursion
6925 (org-back-to-heading)
6926 (outline-up-heading (if (< arg 0) (- arg)
6927 (- (funcall outline-level) arg)))
6928 (org-show-subtree)))
6930 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6931 ((and (featurep 'org-inlinetask)
6932 (org-inlinetask-at-task-p)
6933 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6934 (org-inlinetask-toggle-visibility))
6936 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6937 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6938 (save-excursion (move-beginning-of-line 1)
6939 (looking-at org-outline-regexp)))
6940 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6941 (org-cycle-internal-local))
6943 ;; From there: TAB emulation and template completion.
6944 (buffer-read-only (org-back-to-heading))
6946 ((run-hook-with-args-until-success
6947 'org-tab-after-check-for-cycling-hook))
6949 ((run-hook-with-args-until-success
6950 'org-tab-before-tab-emulation-hook))
6952 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6953 (or (not (bolp))
6954 (not (looking-at org-outline-regexp))))
6955 (call-interactively (global-key-binding "\t")))
6957 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6958 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6959 (or (and (eq org-cycle-emulate-tab 'white)
6960 (= (match-end 0) (point-at-eol)))
6961 (and (eq org-cycle-emulate-tab 'whitestart)
6962 (>= (match-end 0) pos))))
6964 (eq org-cycle-emulate-tab t))
6965 (call-interactively (global-key-binding "\t")))
6967 (t (save-excursion
6968 (org-back-to-heading)
6969 (org-cycle)))))))
6971 (defun org-cycle-internal-global ()
6972 "Do the global cycling action."
6973 ;; Hack to avoid display of messages for .org attachments in Gnus
6974 (let ((ga (string-match "\\*fontification" (buffer-name))))
6975 (cond
6976 ((and (eq last-command this-command)
6977 (eq org-cycle-global-status 'overview))
6978 ;; We just created the overview - now do table of contents
6979 ;; This can be slow in very large buffers, so indicate action
6980 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6981 (unless ga (org-unlogged-message "CONTENTS..."))
6982 (org-content)
6983 (unless ga (org-unlogged-message "CONTENTS...done"))
6984 (setq org-cycle-global-status 'contents)
6985 (run-hook-with-args 'org-cycle-hook 'contents))
6987 ((and (eq last-command this-command)
6988 (eq org-cycle-global-status 'contents))
6989 ;; We just showed the table of contents - now show everything
6990 (run-hook-with-args 'org-pre-cycle-hook 'all)
6991 (org-show-all '(headings blocks))
6992 (unless ga (org-unlogged-message "SHOW ALL"))
6993 (setq org-cycle-global-status 'all)
6994 (run-hook-with-args 'org-cycle-hook 'all))
6997 ;; Default action: go to overview
6998 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6999 (org-overview)
7000 (unless ga (org-unlogged-message "OVERVIEW"))
7001 (setq org-cycle-global-status 'overview)
7002 (run-hook-with-args 'org-cycle-hook 'overview)))))
7004 (defvar org-called-with-limited-levels nil
7005 "Non-nil when `org-with-limited-levels' is currently active.")
7007 (defun org-cycle-internal-local ()
7008 "Do the local cycling action."
7009 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7010 ;; First, determine end of headline (EOH), end of subtree or item
7011 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7012 (save-excursion
7013 (if (org-at-item-p)
7014 (progn
7015 (beginning-of-line)
7016 (setq struct (org-list-struct))
7017 (setq eoh (point-at-eol))
7018 (setq eos (org-list-get-item-end-before-blank (point) struct))
7019 (setq has-children (org-list-has-child-p (point) struct)))
7020 (org-back-to-heading)
7021 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7022 (setq eos (save-excursion (org-end-of-subtree t t)
7023 (when (bolp) (backward-char)) (point)))
7024 (setq has-children
7025 (or (save-excursion
7026 (let ((level (funcall outline-level)))
7027 (outline-next-heading)
7028 (and (org-at-heading-p t)
7029 (> (funcall outline-level) level))))
7030 (save-excursion
7031 (org-list-search-forward (org-item-beginning-re) eos t)))))
7032 ;; Determine end invisible part of buffer (EOL)
7033 (beginning-of-line 2)
7034 (while (and (not (eobp)) ;This is like `next-line'.
7035 (get-char-property (1- (point)) 'invisible))
7036 (goto-char (next-single-char-property-change (point) 'invisible))
7037 (and (eolp) (beginning-of-line 2)))
7038 (setq eol (point)))
7039 ;; Find out what to do next and set `this-command'
7040 (cond
7041 ((= eos eoh)
7042 ;; Nothing is hidden behind this heading
7043 (unless (org-before-first-heading-p)
7044 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7045 (org-unlogged-message "EMPTY ENTRY")
7046 (setq org-cycle-subtree-status nil)
7047 (save-excursion
7048 (goto-char eos)
7049 (outline-next-heading)
7050 (when (org-invisible-p) (org-flag-heading nil))))
7051 ((and (or (>= eol eos)
7052 (not (string-match "\\S-" (buffer-substring eol eos))))
7053 (or has-children
7054 (not (setq children-skipped
7055 org-cycle-skip-children-state-if-no-children))))
7056 ;; Entire subtree is hidden in one line: children view
7057 (unless (org-before-first-heading-p)
7058 (run-hook-with-args 'org-pre-cycle-hook 'children))
7059 (if (org-at-item-p)
7060 (org-list-set-item-visibility (point-at-bol) struct 'children)
7061 (org-show-entry)
7062 (org-with-limited-levels (org-show-children))
7063 (org-show-set-visibility 'canonical)
7064 ;; Fold every list in subtree to top-level items.
7065 (when (eq org-cycle-include-plain-lists 'integrate)
7066 (save-excursion
7067 (org-back-to-heading)
7068 (while (org-list-search-forward (org-item-beginning-re) eos t)
7069 (beginning-of-line 1)
7070 (let* ((struct (org-list-struct))
7071 (prevs (org-list-prevs-alist struct))
7072 (end (org-list-get-bottom-point struct)))
7073 (dolist (e (org-list-get-all-items (point) struct prevs))
7074 (org-list-set-item-visibility e struct 'folded))
7075 (goto-char (if (< end eos) end eos)))))))
7076 (org-unlogged-message "CHILDREN")
7077 (save-excursion
7078 (goto-char eos)
7079 (outline-next-heading)
7080 (when (org-invisible-p) (org-flag-heading nil)))
7081 (setq org-cycle-subtree-status 'children)
7082 (unless (org-before-first-heading-p)
7083 (run-hook-with-args 'org-cycle-hook 'children)))
7084 ((or children-skipped
7085 (and (eq last-command this-command)
7086 (eq org-cycle-subtree-status 'children)))
7087 ;; We just showed the children, or no children are there,
7088 ;; now show everything.
7089 (unless (org-before-first-heading-p)
7090 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7091 (org-flag-region eoh eos nil 'outline)
7092 (org-unlogged-message
7093 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7094 (setq org-cycle-subtree-status 'subtree)
7095 (unless (org-before-first-heading-p)
7096 (run-hook-with-args 'org-cycle-hook 'subtree)))
7098 ;; Default action: hide the subtree.
7099 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7100 (org-flag-region eoh eos t 'outline)
7101 (org-unlogged-message "FOLDED")
7102 (setq org-cycle-subtree-status 'folded)
7103 (unless (org-before-first-heading-p)
7104 (run-hook-with-args 'org-cycle-hook 'folded))))))
7106 ;;;###autoload
7107 (defun org-global-cycle (&optional arg)
7108 "Cycle the global visibility. For details see `org-cycle'.
7109 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7110 With a numeric prefix, show all headlines up to that level."
7111 (interactive "P")
7112 (let ((org-cycle-include-plain-lists
7113 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7114 (cond
7115 ((integerp arg)
7116 (org-show-all '(headings blocks))
7117 (outline-hide-sublevels arg)
7118 (setq org-cycle-global-status 'contents))
7119 ((equal arg '(4))
7120 (org-set-startup-visibility)
7121 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7123 (org-cycle '(4))))))
7125 (defun org-set-startup-visibility ()
7126 "Set the visibility required by startup options and properties."
7127 (cond
7128 ((eq org-startup-folded t)
7129 (org-overview))
7130 ((eq org-startup-folded 'content)
7131 (org-content))
7132 ((or (eq org-startup-folded 'showeverything)
7133 (eq org-startup-folded nil))
7134 (org-show-all)))
7135 (unless (eq org-startup-folded 'showeverything)
7136 (when org-hide-block-startup (org-hide-block-all))
7137 (org-set-visibility-according-to-property)
7138 (org-cycle-hide-archived-subtrees 'all)
7139 (org-cycle-hide-drawers 'all)
7140 (org-cycle-show-empty-lines t)))
7142 (defun org-set-visibility-according-to-property ()
7143 "Switch subtree visibilities according to :VISIBILITY: property."
7144 (interactive)
7145 (org-with-wide-buffer
7146 (goto-char (point-min))
7147 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7148 (if (not (org-at-property-p)) (outline-next-heading)
7149 (let ((state (match-string 3)))
7150 (save-excursion
7151 (org-back-to-heading t)
7152 (outline-hide-subtree)
7153 (org-reveal)
7154 (cond
7155 ((equal state "folded")
7156 (outline-hide-subtree))
7157 ((equal state "children")
7158 (org-show-hidden-entry)
7159 (org-show-children))
7160 ((equal state "content")
7161 (save-excursion
7162 (save-restriction
7163 (org-narrow-to-subtree)
7164 (org-content))))
7165 ((member state '("all" "showall"))
7166 (outline-show-subtree)))))))))
7168 (defun org-overview ()
7169 "Switch to overview mode, showing only top-level headlines.
7170 This shows all headlines with a level equal or greater than the level
7171 of the first headline in the buffer. This is important, because if the
7172 first headline is not level one, then (hide-sublevels 1) gives confusing
7173 results."
7174 (interactive)
7175 (save-excursion
7176 (let ((level
7177 (save-excursion
7178 (goto-char (point-min))
7179 (when (re-search-forward org-outline-regexp-bol nil t)
7180 (goto-char (match-beginning 0))
7181 (funcall outline-level)))))
7182 (and level (outline-hide-sublevels level)))))
7184 (defun org-content (&optional arg)
7185 "Show all headlines in the buffer, like a table of contents.
7186 With numerical argument N, show content up to level N."
7187 (interactive "P")
7188 (org-overview)
7189 (save-excursion
7190 ;; Visit all headings and show their offspring
7191 (and (integerp arg) (org-overview))
7192 (goto-char (point-max))
7193 (catch 'exit
7194 (while (and (progn (condition-case nil
7195 (outline-previous-visible-heading 1)
7196 (error (goto-char (point-min))))
7198 (looking-at org-outline-regexp))
7199 (if (integerp arg)
7200 (org-show-children (1- arg))
7201 (outline-show-branches))
7202 (when (bobp) (throw 'exit nil))))))
7204 (defun org-optimize-window-after-visibility-change (state)
7205 "Adjust the window after a change in outline visibility.
7206 This function is the default value of the hook `org-cycle-hook'."
7207 (when (get-buffer-window (current-buffer))
7208 (cond
7209 ((eq state 'content) nil)
7210 ((eq state 'all) nil)
7211 ((eq state 'folded) nil)
7212 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7213 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7215 (defun org-clean-visibility-after-subtree-move ()
7216 "Fix visibility issues after moving a subtree."
7217 ;; First, find a reasonable region to look at:
7218 ;; Start two siblings above, end three below
7219 (let* ((beg (save-excursion
7220 (and (org-get-last-sibling)
7221 (org-get-last-sibling))
7222 (point)))
7223 (end (save-excursion
7224 (and (org-get-next-sibling)
7225 (org-get-next-sibling)
7226 (org-get-next-sibling))
7227 (if (org-at-heading-p)
7228 (point-at-eol)
7229 (point))))
7230 (level (looking-at "\\*+"))
7231 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7232 (save-excursion
7233 (save-restriction
7234 (narrow-to-region beg end)
7235 (when re
7236 ;; Properly fold already folded siblings
7237 (goto-char (point-min))
7238 (while (re-search-forward re nil t)
7239 (when (and (not (org-invisible-p))
7240 (org-invisible-p (line-end-position)))
7241 (outline-hide-entry))))
7242 (org-cycle-hide-drawers 'all)
7243 (org-cycle-show-empty-lines 'overview)))))
7245 (defun org-cycle-show-empty-lines (state)
7246 "Show empty lines above all visible headlines.
7247 The region to be covered depends on STATE when called through
7248 `org-cycle-hook'. Lisp program can use t for STATE to get the
7249 entire buffer covered. Note that an empty line is only shown if there
7250 are at least `org-cycle-separator-lines' empty lines before the headline."
7251 (when (/= org-cycle-separator-lines 0)
7252 (save-excursion
7253 (let* ((n (abs org-cycle-separator-lines))
7254 (re (cond
7255 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7256 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7257 (t (let ((ns (number-to-string (- n 2))))
7258 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7259 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7260 beg end)
7261 (cond
7262 ((memq state '(overview contents t))
7263 (setq beg (point-min) end (point-max)))
7264 ((memq state '(children folded))
7265 (setq beg (point)
7266 end (progn (org-end-of-subtree t t)
7267 (line-beginning-position 2)))))
7268 (when beg
7269 (goto-char beg)
7270 (while (re-search-forward re end t)
7271 (unless (get-char-property (match-end 1) 'invisible)
7272 (let ((e (match-end 1))
7273 (b (if (>= org-cycle-separator-lines 0)
7274 (match-beginning 1)
7275 (save-excursion
7276 (goto-char (match-beginning 0))
7277 (skip-chars-backward " \t\n")
7278 (line-end-position)))))
7279 (org-flag-region b e nil 'outline))))))))
7280 ;; Never hide empty lines at the end of the file.
7281 (save-excursion
7282 (goto-char (point-max))
7283 (outline-previous-heading)
7284 (outline-end-of-heading)
7285 (when (and (looking-at "[ \t\n]+")
7286 (= (match-end 0) (point-max)))
7287 (org-flag-region (point) (match-end 0) nil 'outline))))
7289 ;;;; Reveal point location
7291 (defun org-show-context (&optional key)
7292 "Make sure point and context are visible.
7293 Optional argument KEY, when non-nil, is a symbol. See
7294 `org-show-context-detail' for allowed values and how much is to
7295 be shown."
7296 (org-show-set-visibility
7297 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7298 ((cdr (assq key org-show-context-detail)))
7299 (t (cdr (assq 'default org-show-context-detail))))))
7301 (defun org-show-set-visibility (detail)
7302 "Set visibility around point according to DETAIL.
7303 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7304 `tree', `canonical' or t. See `org-show-context-detail' for more
7305 information."
7306 ;; Show current heading and possibly its entry, following headline
7307 ;; or all children.
7308 (if (and (org-at-heading-p) (not (eq detail 'local)))
7309 (org-flag-heading nil)
7310 (org-show-entry)
7311 ;; If point is hidden within a drawer or a block, make sure to
7312 ;; expose it.
7313 (dolist (o (overlays-at (point)))
7314 (when (memq (overlay-get o 'invisible)
7315 '(org-hide-block org-hide-drawer outline))
7316 (delete-overlay o)))
7317 (unless (org-before-first-heading-p)
7318 (org-with-limited-levels
7319 (cl-case detail
7320 ((tree canonical t) (org-show-children))
7321 ((nil minimal ancestors))
7322 (t (save-excursion
7323 (outline-next-heading)
7324 (org-flag-heading nil)))))))
7325 ;; Show all siblings.
7326 (when (eq detail 'lineage) (org-show-siblings))
7327 ;; Show ancestors, possibly with their children.
7328 (when (memq detail '(ancestors lineage tree canonical t))
7329 (save-excursion
7330 (while (org-up-heading-safe)
7331 (org-flag-heading nil)
7332 (when (memq detail '(canonical t)) (org-show-entry))
7333 (when (memq detail '(tree canonical t)) (org-show-children))))))
7335 (defvar org-reveal-start-hook nil
7336 "Hook run before revealing a location.")
7338 (defun org-reveal (&optional siblings)
7339 "Show current entry, hierarchy above it, and the following headline.
7341 This can be used to show a consistent set of context around
7342 locations exposed with `org-show-context'.
7344 With optional argument SIBLINGS, on each level of the hierarchy all
7345 siblings are shown. This repairs the tree structure to what it would
7346 look like when opened with hierarchical calls to `org-cycle'.
7348 With a \\[universal-argument] \\[universal-argument] prefix, \
7349 go to the parent and show the entire tree."
7350 (interactive "P")
7351 (run-hooks 'org-reveal-start-hook)
7352 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7353 ((equal siblings '(16))
7354 (save-excursion
7355 (when (org-up-heading-safe)
7356 (org-show-subtree)
7357 (run-hook-with-args 'org-cycle-hook 'subtree))))
7358 (t (org-show-set-visibility 'lineage))))
7361 ;;; Indirect buffer display of subtrees
7363 (defvar org-indirect-dedicated-frame nil
7364 "This is the frame being used for indirect tree display.")
7365 (defvar org-last-indirect-buffer nil)
7367 (defun org-tree-to-indirect-buffer (&optional arg)
7368 "Create indirect buffer and narrow it to current subtree.
7370 With a numerical prefix ARG, go up to this level and then take that tree.
7371 If ARG is negative, go up that many levels.
7373 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7374 indirect buffer previously made with this command, to avoid proliferation of
7375 indirect buffers. However, when you call the command with a \
7376 `\\[universal-argument]' prefix, or
7377 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7378 so that you can work with several indirect buffers at the same time. If
7379 `org-indirect-buffer-display' is `dedicated-frame', the \
7380 `\\[universal-argument]' prefix also
7381 requests that a new frame be made for the new buffer, so that the dedicated
7382 frame is not changed."
7383 (interactive "P")
7384 (let ((cbuf (current-buffer))
7385 (cwin (selected-window))
7386 (pos (point))
7387 beg end level heading ibuf)
7388 (save-excursion
7389 (org-back-to-heading t)
7390 (when (numberp arg)
7391 (setq level (org-outline-level))
7392 (when (< arg 0) (setq arg (+ level arg)))
7393 (while (> (setq level (org-outline-level)) arg)
7394 (org-up-heading-safe)))
7395 (setq beg (point)
7396 heading (org-get-heading 'no-tags))
7397 (org-end-of-subtree t t)
7398 (when (org-at-heading-p) (backward-char 1))
7399 (setq end (point)))
7400 (when (and (buffer-live-p org-last-indirect-buffer)
7401 (not (eq org-indirect-buffer-display 'new-frame))
7402 (not arg))
7403 (kill-buffer org-last-indirect-buffer))
7404 (setq ibuf (org-get-indirect-buffer cbuf heading)
7405 org-last-indirect-buffer ibuf)
7406 (cond
7407 ((or (eq org-indirect-buffer-display 'new-frame)
7408 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7409 (select-frame (make-frame))
7410 (delete-other-windows)
7411 (pop-to-buffer-same-window ibuf)
7412 (org-set-frame-title heading))
7413 ((eq org-indirect-buffer-display 'dedicated-frame)
7414 (raise-frame
7415 (select-frame (or (and org-indirect-dedicated-frame
7416 (frame-live-p org-indirect-dedicated-frame)
7417 org-indirect-dedicated-frame)
7418 (setq org-indirect-dedicated-frame (make-frame)))))
7419 (delete-other-windows)
7420 (pop-to-buffer-same-window ibuf)
7421 (org-set-frame-title (concat "Indirect: " heading)))
7422 ((eq org-indirect-buffer-display 'current-window)
7423 (pop-to-buffer-same-window ibuf))
7424 ((eq org-indirect-buffer-display 'other-window)
7425 (pop-to-buffer ibuf))
7426 (t (error "Invalid value")))
7427 (narrow-to-region beg end)
7428 (org-show-all '(headings blocks))
7429 (goto-char pos)
7430 (run-hook-with-args 'org-cycle-hook 'all)
7431 (and (window-live-p cwin) (select-window cwin))))
7433 (defun org-get-indirect-buffer (&optional buffer heading)
7434 (setq buffer (or buffer (current-buffer)))
7435 (let ((n 1) (base (buffer-name buffer)) bname)
7436 (while (buffer-live-p
7437 (get-buffer
7438 (setq bname
7439 (concat base "-"
7440 (if heading (concat heading "-" (number-to-string n))
7441 (number-to-string n))))))
7442 (setq n (1+ n)))
7443 (condition-case nil
7444 (make-indirect-buffer buffer bname 'clone)
7445 (error (make-indirect-buffer buffer bname)))))
7447 (defun org-set-frame-title (title)
7448 "Set the title of the current frame to the string TITLE."
7449 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7451 ;;;; Structure editing
7453 ;;; Inserting headlines
7455 (defun org--line-empty-p (n)
7456 "Is the Nth next line empty?
7458 Counts the current line as N = 1 and the previous line as N = 0;
7459 see `beginning-of-line'."
7460 (save-excursion
7461 (and (not (bobp))
7462 (or (beginning-of-line n) t)
7463 (save-match-data
7464 (looking-at "[ \t]*$")))))
7466 (defun org-previous-line-empty-p ()
7467 "Is the previous line a blank line?
7468 When NEXT is non-nil, check the next line instead."
7469 (org--line-empty-p 0))
7471 (defun org-next-line-empty-p ()
7472 "Is the previous line a blank line?
7473 When NEXT is non-nil, check the next line instead."
7474 (org--line-empty-p 2))
7476 (defun org--blank-before-heading-p (&optional parent)
7477 "Non-nil when an empty line should precede a new heading here.
7478 When optional argument PARENT is non-nil, consider parent
7479 headline instead of current one."
7480 (pcase (assq 'heading org-blank-before-new-entry)
7481 (`(heading . auto)
7482 (save-excursion
7483 (org-with-limited-levels
7484 (unless (and (org-before-first-heading-p)
7485 (not (outline-next-heading)))
7486 (org-back-to-heading t)
7487 (when parent (org-up-heading-safe))
7488 (cond ((not (bobp))
7489 (org-previous-line-empty-p))
7490 ((outline-next-heading)
7491 (org-previous-line-empty-p))
7492 ;; Ignore trailing spaces on last buffer line.
7493 ((progn (skip-chars-backward " \t") (bolp))
7494 (org-previous-line-empty-p))
7495 (t nil))))))
7496 (`(heading . ,value) value)
7497 (_ nil)))
7499 (defun org-insert-heading (&optional arg invisible-ok top)
7500 "Insert a new heading or an item with the same depth at point.
7502 If point is at the beginning of a heading, insert a new heading
7503 or a new headline above the current one. When at the beginning
7504 of a regular line of text, turn it into a heading.
7506 If point is in the middle of a line, split it and create a new
7507 headline with the text in the current line after point (see
7508 `org-M-RET-may-split-line' on how to modify this behavior). As
7509 a special case, on a headline, splitting can only happen on the
7510 title itself. E.g., this excludes breaking stars or tags.
7512 With a `\\[universal-argument]' prefix, set \
7513 `org-insert-heading-respect-content' to
7514 a non-nil value for the duration of the command. This forces the
7515 insertion of a heading after the current subtree, independently
7516 on the location of point.
7518 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7519 insert the heading at the end of the tree
7520 above the current heading. For example, if point is within a
7521 2nd-level heading, then it will insert a 2nd-level heading at
7522 the end of the 1st-level parent subtree.
7524 When INVISIBLE-OK is set, stop at invisible headlines when going
7525 back. This is important for non-interactive uses of the
7526 command.
7528 When optional argument TOP is non-nil, insert a level 1 heading,
7529 unconditionally."
7530 (interactive "P")
7531 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7532 (level (org-current-level))
7533 (stars (make-string (if (and level (not top)) level 1) ?*)))
7534 (cond
7535 ((or org-insert-heading-respect-content
7536 (member arg '((4) (16)))
7537 (and (not invisible-ok)
7538 (invisible-p (max (1- (point)) (point-min)))))
7539 ;; Position point at the location of insertion.
7540 (if (not level) ;before first headline
7541 (org-with-limited-levels (outline-next-heading))
7542 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7543 ;; is nil.
7544 (org-with-limited-levels (org-back-to-heading invisible-ok))
7545 (cond ((equal arg '(16))
7546 (org-up-heading-safe)
7547 (org-end-of-subtree t t))
7549 (org-end-of-subtree t t))))
7550 (unless (bolp) (insert "\n")) ;ensure final newline
7551 (unless (and blank? (org-previous-line-empty-p))
7552 (org-N-empty-lines-before-current (if blank? 1 0)))
7553 (insert stars " \n")
7554 (forward-char -1))
7555 ;; At a headline...
7556 ((org-at-heading-p)
7557 (cond ((bolp)
7558 (when blank? (save-excursion (insert "\n")))
7559 (save-excursion (insert stars " \n"))
7560 (unless (and blank? (org-previous-line-empty-p))
7561 (org-N-empty-lines-before-current (if blank? 1 0)))
7562 (end-of-line))
7563 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7564 (org-match-line org-complex-heading-regexp)
7565 (org-pos-in-match-range (point) 4))
7566 ;; Grab the text that should moved to the new headline.
7567 ;; Preserve tags.
7568 (let ((split (delete-and-extract-region (point) (match-end 4))))
7569 (if (looking-at "[ \t]*$") (replace-match "")
7570 (org-set-tags nil t))
7571 (end-of-line)
7572 (when blank? (insert "\n"))
7573 (insert "\n" stars " ")
7574 (when (org-string-nw-p split) (insert split))
7575 (when (eobp) (save-excursion (insert "\n")))))
7577 (end-of-line)
7578 (when blank? (insert "\n"))
7579 (insert "\n" stars " ")
7580 (when (eobp) (save-excursion (insert "\n"))))))
7581 ;; On regular text, turn line into a headline or split, if
7582 ;; appropriate.
7583 ((bolp)
7584 (insert stars " ")
7585 (unless (and blank? (org-previous-line-empty-p))
7586 (org-N-empty-lines-before-current (if blank? 1 0))))
7588 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7589 (end-of-line))
7590 (insert "\n" stars " ")
7591 (unless (and blank? (org-previous-line-empty-p))
7592 (org-N-empty-lines-before-current (if blank? 1 0))))))
7593 (run-hooks 'org-insert-heading-hook))
7595 (defun org-N-empty-lines-before-current (n)
7596 "Make the number of empty lines before current exactly N.
7597 So this will delete or add empty lines."
7598 (let ((column (current-column)))
7599 (beginning-of-line)
7600 (unless (bobp)
7601 (let ((start (save-excursion
7602 (skip-chars-backward " \r\t\n")
7603 (line-end-position))))
7604 (delete-region start (line-end-position 0))))
7605 (insert (make-string n ?\n))
7606 (move-to-column column)))
7608 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7609 "Return the heading of the current entry, without the stars.
7610 When NO-TAGS is non-nil, don't include tags.
7611 When NO-TODO is non-nil, don't include TODO keywords.
7612 When NO-PRIORITY is non-nil, don't include priority cookie.
7613 When NO-COMMENT is non-nil, don't include COMMENT string."
7614 (save-excursion
7615 (org-back-to-heading t)
7616 (let ((case-fold-search nil))
7617 (looking-at org-complex-heading-regexp)
7618 (let ((todo (and (not no-todo) (match-string 2)))
7619 (priority (and (not no-priority) (match-string 3)))
7620 (headline (pcase (match-string 4)
7621 (`nil "")
7622 ((and (guard no-comment) h)
7623 (replace-regexp-in-string
7624 (eval-when-compile
7625 (format "\\`%s[ \t]+" org-comment-string))
7626 "" h))
7627 (h h)))
7628 (tags (and (not no-tags) (match-string 5))))
7629 (mapconcat #'identity
7630 (delq nil (list todo priority headline tags))
7631 " ")))))
7633 (defun org-heading-components ()
7634 "Return the components of the current heading.
7635 This is a list with the following elements:
7636 - the level as an integer
7637 - the reduced level, different if `org-odd-levels-only' is set.
7638 - the TODO keyword, or nil
7639 - the priority character, like ?A, or nil if no priority is given
7640 - the headline text itself, or the tags string if no headline text
7641 - the tags string, or nil."
7642 (save-excursion
7643 (org-back-to-heading t)
7644 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7645 (list (length (match-string 1))
7646 (org-reduced-level (length (match-string 1)))
7647 (match-string-no-properties 2)
7648 (and (match-end 3) (aref (match-string 3) 2))
7649 (match-string-no-properties 4)
7650 (match-string-no-properties 5)))))
7652 (defun org-get-entry ()
7653 "Get the entry text, after heading, entire subtree."
7654 (save-excursion
7655 (org-back-to-heading t)
7656 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7658 (defun org-edit-headline (&optional heading)
7659 "Edit the current headline.
7660 Set it to HEADING when provided."
7661 (interactive)
7662 (org-with-wide-buffer
7663 (org-back-to-heading t)
7664 (let ((case-fold-search nil))
7665 (when (looking-at org-complex-heading-regexp)
7666 (let* ((old (match-string-no-properties 4))
7667 (new (save-match-data
7668 (org-trim (or heading (read-string "Edit: " old))))))
7669 (unless (equal old new)
7670 (if old (replace-match new t t nil 4)
7671 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7672 (insert " " new))
7673 (org-set-tags nil t)
7674 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7676 (defun org-insert-heading-after-current ()
7677 "Insert a new heading with same level as current, after current subtree."
7678 (interactive)
7679 (org-back-to-heading)
7680 (org-insert-heading)
7681 (org-move-subtree-down)
7682 (end-of-line 1))
7684 (defun org-insert-heading-respect-content (&optional invisible-ok)
7685 "Insert heading with `org-insert-heading-respect-content' set to t."
7686 (interactive)
7687 (org-insert-heading '(4) invisible-ok))
7689 (defun org-insert-todo-heading-respect-content (&optional force-state)
7690 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7691 (interactive)
7692 (org-insert-todo-heading force-state '(4)))
7694 (defun org-insert-todo-heading (arg &optional force-heading)
7695 "Insert a new heading with the same level and TODO state as current heading.
7697 If the heading has no TODO state, or if the state is DONE, use
7698 the first state (TODO by default). Also with one prefix arg,
7699 force first state. With two prefix args, force inserting at the
7700 end of the parent subtree.
7702 When called at a plain list item, insert a new item with an
7703 unchecked check box."
7704 (interactive "P")
7705 (when (or force-heading (not (org-insert-item 'checkbox)))
7706 (org-insert-heading (or (and (equal arg '(16)) '(16))
7707 force-heading))
7708 (save-excursion
7709 (org-forward-heading-same-level -1)
7710 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7711 (let* ((new-mark-x
7712 (if (or (equal arg '(4))
7713 (not (match-beginning 2))
7714 (member (match-string 2) org-done-keywords))
7715 (car org-todo-keywords-1)
7716 (match-string 2)))
7717 (new-mark
7719 (run-hook-with-args-until-success
7720 'org-todo-get-default-hook new-mark-x nil)
7721 new-mark-x)))
7722 (beginning-of-line 1)
7723 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7724 (if org-treat-insert-todo-heading-as-state-change
7725 (org-todo new-mark)
7726 (insert new-mark " "))))
7727 (when org-provide-todo-statistics
7728 (org-update-parent-todo-statistics))))
7730 (defun org-insert-subheading (arg)
7731 "Insert a new subheading and demote it.
7732 Works for outline headings and for plain lists alike."
7733 (interactive "P")
7734 (org-insert-heading arg)
7735 (cond
7736 ((org-at-heading-p) (org-do-demote))
7737 ((org-at-item-p) (org-indent-item))))
7739 (defun org-insert-todo-subheading (arg)
7740 "Insert a new subheading with TODO keyword or checkbox and demote it.
7741 Works for outline headings and for plain lists alike."
7742 (interactive "P")
7743 (org-insert-todo-heading arg)
7744 (cond
7745 ((org-at-heading-p) (org-do-demote))
7746 ((org-at-item-p) (org-indent-item))))
7748 ;;; Promotion and Demotion
7750 (defvar org-after-demote-entry-hook nil
7751 "Hook run after an entry has been demoted.
7752 The cursor will be at the beginning of the entry.
7753 When a subtree is being demoted, the hook will be called for each node.")
7755 (defvar org-after-promote-entry-hook nil
7756 "Hook run after an entry has been promoted.
7757 The cursor will be at the beginning of the entry.
7758 When a subtree is being promoted, the hook will be called for each node.")
7760 (defun org-promote-subtree ()
7761 "Promote the entire subtree.
7762 See also `org-promote'."
7763 (interactive)
7764 (save-excursion
7765 (org-with-limited-levels (org-map-tree 'org-promote)))
7766 (org-fix-position-after-promote))
7768 (defun org-demote-subtree ()
7769 "Demote the entire subtree.
7770 See `org-demote' and `org-promote'."
7771 (interactive)
7772 (save-excursion
7773 (org-with-limited-levels (org-map-tree 'org-demote)))
7774 (org-fix-position-after-promote))
7776 (defun org-do-promote ()
7777 "Promote the current heading higher up the tree.
7778 If the region is active in `transient-mark-mode', promote all
7779 headings in the region."
7780 (interactive)
7781 (save-excursion
7782 (if (org-region-active-p)
7783 (org-map-region 'org-promote (region-beginning) (region-end))
7784 (org-promote)))
7785 (org-fix-position-after-promote))
7787 (defun org-do-demote ()
7788 "Demote the current heading lower down the tree.
7789 If the region is active in `transient-mark-mode', demote all
7790 headings in the region."
7791 (interactive)
7792 (save-excursion
7793 (if (org-region-active-p)
7794 (org-map-region 'org-demote (region-beginning) (region-end))
7795 (org-demote)))
7796 (org-fix-position-after-promote))
7798 (defun org-fix-position-after-promote ()
7799 "Fix cursor position and indentation after demoting/promoting."
7800 (let ((pos (point)))
7801 (when (save-excursion
7802 (beginning-of-line)
7803 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7804 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7805 (cond ((eobp) (insert " "))
7806 ((eolp) (insert " "))
7807 ((equal (char-after) ?\s) (forward-char 1))))))
7809 (defun org-current-level ()
7810 "Return the level of the current entry, or nil if before the first headline.
7811 The level is the number of stars at the beginning of the
7812 headline. Use `org-reduced-level' to remove the effect of
7813 `org-odd-levels'. Unlike to `org-outline-level', this function
7814 ignores inlinetasks."
7815 (let ((level (org-with-limited-levels (org-outline-level))))
7816 (and (> level 0) level)))
7818 (defun org-get-previous-line-level ()
7819 "Return the outline depth of the last headline before the current line.
7820 Returns 0 for the first headline in the buffer, and nil if before the
7821 first headline."
7822 (and (org-current-level)
7823 (or (and (/= (line-beginning-position) (point-min))
7824 (save-excursion (beginning-of-line 0) (org-current-level)))
7825 0)))
7827 (defun org-reduced-level (l)
7828 "Compute the effective level of a heading.
7829 This takes into account the setting of `org-odd-levels-only'."
7830 (cond
7831 ((zerop l) 0)
7832 (org-odd-levels-only (1+ (floor (/ l 2))))
7833 (t l)))
7835 (defun org-level-increment ()
7836 "Return the number of stars that will be added or removed at a
7837 time to headlines when structure editing, based on the value of
7838 `org-odd-levels-only'."
7839 (if org-odd-levels-only 2 1))
7841 (defun org-get-valid-level (level &optional change)
7842 "Rectify a level change under the influence of `org-odd-levels-only'.
7843 LEVEL is a current level, CHANGE is by how much the level should
7844 be modified. Even if CHANGE is nil, LEVEL may be returned
7845 modified because even level numbers will become the next higher
7846 odd number. Returns values greater than 0."
7847 (if org-odd-levels-only
7848 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7849 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7850 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7851 (max 1 (+ level (or change 0)))))
7853 (defun org-promote ()
7854 "Promote the current heading higher up the tree."
7855 (org-with-wide-buffer
7856 (org-back-to-heading t)
7857 (let* ((after-change-functions (remq 'flyspell-after-change-function
7858 after-change-functions))
7859 (level (save-match-data (funcall outline-level)))
7860 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7861 (diff (abs (- level (length up-head) -1))))
7862 (cond
7863 ((and (= level 1) org-allow-promoting-top-level-subtree)
7864 (replace-match "# " nil t))
7865 ((= level 1)
7866 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7867 (t (replace-match up-head nil t)))
7868 (unless (= level 1)
7869 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7870 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7871 (run-hooks 'org-after-promote-entry-hook))))
7873 (defun org-demote ()
7874 "Demote the current heading lower down the tree."
7875 (org-with-wide-buffer
7876 (org-back-to-heading t)
7877 (let* ((after-change-functions (remq 'flyspell-after-change-function
7878 after-change-functions))
7879 (level (save-match-data (funcall outline-level)))
7880 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7881 (diff (abs (- level (length down-head) -1))))
7882 (replace-match down-head nil t)
7883 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7884 (when org-adapt-indentation (org-fixup-indentation diff))
7885 (run-hooks 'org-after-demote-entry-hook))))
7887 (defun org-cycle-level ()
7888 "Cycle the level of an empty headline through possible states.
7889 This goes first to child, then to parent, level, then up the hierarchy.
7890 After top level, it switches back to sibling level."
7891 (interactive)
7892 (let ((org-adapt-indentation nil))
7893 (when (org-point-at-end-of-empty-headline)
7894 (setq this-command 'org-cycle-level) ; Only needed for caching
7895 (let ((cur-level (org-current-level))
7896 (prev-level (org-get-previous-line-level)))
7897 (cond
7898 ;; If first headline in file, promote to top-level.
7899 ((= prev-level 0)
7900 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7901 do (org-do-promote)))
7902 ;; If same level as prev, demote one.
7903 ((= prev-level cur-level)
7904 (org-do-demote))
7905 ;; If parent is top-level, promote to top level if not already.
7906 ((= prev-level 1)
7907 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7908 do (org-do-promote)))
7909 ;; If top-level, return to prev-level.
7910 ((= cur-level 1)
7911 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7912 do (org-do-demote)))
7913 ;; If less than prev-level, promote one.
7914 ((< cur-level prev-level)
7915 (org-do-promote))
7916 ;; If deeper than prev-level, promote until higher than
7917 ;; prev-level.
7918 ((> cur-level prev-level)
7919 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7920 do (org-do-promote))))
7921 t))))
7923 (defun org-map-tree (fun)
7924 "Call FUN for every heading underneath the current one."
7925 (org-back-to-heading t)
7926 (let ((level (funcall outline-level)))
7927 (save-excursion
7928 (funcall fun)
7929 (while (and (progn
7930 (outline-next-heading)
7931 (> (funcall outline-level) level))
7932 (not (eobp)))
7933 (funcall fun)))))
7935 (defun org-map-region (fun beg end)
7936 "Call FUN for every heading between BEG and END."
7937 (let ((org-ignore-region t))
7938 (save-excursion
7939 (setq end (copy-marker end))
7940 (goto-char beg)
7941 (when (and (re-search-forward org-outline-regexp-bol nil t)
7942 (< (point) end))
7943 (funcall fun))
7944 (while (and (progn
7945 (outline-next-heading)
7946 (< (point) end))
7947 (not (eobp)))
7948 (funcall fun)))))
7950 (defun org-fixup-indentation (diff)
7951 "Change the indentation in the current entry by DIFF.
7953 DIFF is an integer. Indentation is done according to the
7954 following rules:
7956 - Planning information and property drawers are always indented
7957 according to the new level of the headline;
7959 - Footnote definitions and their contents are ignored;
7961 - Inlinetasks' boundaries are not shifted;
7963 - Empty lines are ignored;
7965 - Other lines' indentation are shifted by DIFF columns, unless
7966 it would introduce a structural change in the document, in
7967 which case no shifting is done at all.
7969 Assume point is at a heading or an inlinetask beginning."
7970 (org-with-wide-buffer
7971 (narrow-to-region (line-beginning-position)
7972 (save-excursion
7973 (if (org-with-limited-levels (org-at-heading-p))
7974 (org-with-limited-levels (outline-next-heading))
7975 (org-inlinetask-goto-end))
7976 (point)))
7977 (forward-line)
7978 ;; Indent properly planning info and property drawer.
7979 (when (looking-at-p org-planning-line-re)
7980 (org-indent-line)
7981 (forward-line))
7982 (when (looking-at org-property-drawer-re)
7983 (goto-char (match-end 0))
7984 (forward-line)
7985 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7986 (catch 'no-shift
7987 (when (zerop diff) (throw 'no-shift nil))
7988 ;; If DIFF is negative, first check if a shift is possible at all
7989 ;; (e.g., it doesn't break structure). This can only happen if
7990 ;; some contents are not properly indented.
7991 (let ((case-fold-search t))
7992 (when (< diff 0)
7993 (let ((diff (- diff))
7994 (forbidden-re (concat org-outline-regexp
7995 "\\|"
7996 (substring org-footnote-definition-re 1))))
7997 (save-excursion
7998 (while (not (eobp))
7999 (cond
8000 ((looking-at-p "[ \t]*$") (forward-line))
8001 ((and (looking-at-p org-footnote-definition-re)
8002 (let ((e (org-element-at-point)))
8003 (and (eq (org-element-type e) 'footnote-definition)
8004 (goto-char (org-element-property :end e))))))
8005 ((looking-at-p org-outline-regexp) (forward-line))
8006 ;; Give up if shifting would move before column 0 or
8007 ;; if it would introduce a headline or a footnote
8008 ;; definition.
8010 (skip-chars-forward " \t")
8011 (let ((ind (current-column)))
8012 (when (or (< ind diff)
8013 (and (= ind diff) (looking-at-p forbidden-re)))
8014 (throw 'no-shift nil)))
8015 ;; Ignore contents of example blocks and source
8016 ;; blocks if their indentation is meant to be
8017 ;; preserved. Jump to block's closing line.
8018 (beginning-of-line)
8019 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8020 (let ((e (org-element-at-point)))
8021 (and (memq (org-element-type e)
8022 '(example-block src-block))
8023 (or org-src-preserve-indentation
8024 (org-element-property :preserve-indent e))
8025 (goto-char (org-element-property :end e))
8026 (progn (skip-chars-backward " \r\t\n")
8027 (beginning-of-line)
8028 t))))
8029 (forward-line))))))))
8030 ;; Shift lines but footnote definitions, inlinetasks boundaries
8031 ;; by DIFF. Also skip contents of source or example blocks
8032 ;; when indentation is meant to be preserved.
8033 (while (not (eobp))
8034 (cond
8035 ((and (looking-at-p org-footnote-definition-re)
8036 (let ((e (org-element-at-point)))
8037 (and (eq (org-element-type e) 'footnote-definition)
8038 (goto-char (org-element-property :end e))))))
8039 ((looking-at-p org-outline-regexp) (forward-line))
8040 ((looking-at-p "[ \t]*$") (forward-line))
8042 (indent-line-to (+ (org-get-indentation) diff))
8043 (beginning-of-line)
8044 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8045 (let ((e (org-element-at-point)))
8046 (and (memq (org-element-type e)
8047 '(example-block src-block))
8048 (or org-src-preserve-indentation
8049 (org-element-property :preserve-indent e))
8050 (goto-char (org-element-property :end e))
8051 (progn (skip-chars-backward " \r\t\n")
8052 (beginning-of-line)
8053 t))))
8054 (forward-line)))))))))
8056 (defun org-convert-to-odd-levels ()
8057 "Convert an Org file with all levels allowed to one with odd levels.
8058 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8059 level 5 etc."
8060 (interactive)
8061 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8062 (let ((outline-level 'org-outline-level)
8063 (org-odd-levels-only nil) n)
8064 (save-excursion
8065 (goto-char (point-min))
8066 (while (re-search-forward "^\\*\\*+ " nil t)
8067 (setq n (- (length (match-string 0)) 2))
8068 (while (>= (setq n (1- n)) 0)
8069 (org-demote))
8070 (end-of-line 1))))))
8072 (defun org-convert-to-oddeven-levels ()
8073 "Convert an Org file with only odd levels to one with odd/even levels.
8074 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8075 file contains a section with an even level, conversion would
8076 destroy the structure of the file. An error is signaled in this
8077 case."
8078 (interactive)
8079 (goto-char (point-min))
8080 ;; First check if there are no even levels
8081 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8082 (org-show-set-visibility 'canonical)
8083 (error "Not all levels are odd in this file. Conversion not possible"))
8084 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8085 (let ((outline-regexp org-outline-regexp)
8086 (outline-level 'org-outline-level)
8087 (org-odd-levels-only nil) n)
8088 (save-excursion
8089 (goto-char (point-min))
8090 (while (re-search-forward "^\\*\\*+ " nil t)
8091 (setq n (/ (1- (length (match-string 0))) 2))
8092 (while (>= (setq n (1- n)) 0)
8093 (org-promote))
8094 (end-of-line 1))))))
8096 (defun org-tr-level (n)
8097 "Make N odd if required."
8098 (if org-odd-levels-only (1+ (/ n 2)) n))
8100 ;;; Vertical tree motion, cutting and pasting of subtrees
8102 (defun org-move-subtree-up (&optional arg)
8103 "Move the current subtree up past ARG headlines of the same level."
8104 (interactive "p")
8105 (org-move-subtree-down (- (prefix-numeric-value arg))))
8107 (defun org-move-subtree-down (&optional arg)
8108 "Move the current subtree down past ARG headlines of the same level."
8109 (interactive "p")
8110 (setq arg (prefix-numeric-value arg))
8111 (org-preserve-local-variables
8112 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8113 'org-get-last-sibling))
8114 (ins-point (make-marker))
8115 (cnt (abs arg))
8116 (col (current-column))
8117 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8118 ;; Select the tree
8119 (org-back-to-heading)
8120 (setq beg0 (point))
8121 (save-excursion
8122 (setq ne-beg (org-back-over-empty-lines))
8123 (setq beg (point)))
8124 (save-match-data
8125 (save-excursion (outline-end-of-heading)
8126 (setq folded (org-invisible-p)))
8127 (progn (org-end-of-subtree nil t)
8128 (unless (eobp) (backward-char))))
8129 (outline-next-heading)
8130 (setq ne-end (org-back-over-empty-lines))
8131 (setq end (point))
8132 (goto-char beg0)
8133 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8134 ;; include less whitespace
8135 (save-excursion
8136 (goto-char beg)
8137 (forward-line (- ne-beg ne-end))
8138 (setq beg (point))))
8139 ;; Find insertion point, with error handling
8140 (while (> cnt 0)
8141 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8142 (goto-char beg0)
8143 (user-error "Cannot move past superior level or buffer limit"))
8144 (setq cnt (1- cnt)))
8145 (when (> arg 0)
8146 ;; Moving forward - still need to move over subtree
8147 (org-end-of-subtree t t)
8148 (save-excursion
8149 (org-back-over-empty-lines)
8150 (or (bolp) (newline))))
8151 (setq ne-ins (org-back-over-empty-lines))
8152 (move-marker ins-point (point))
8153 (setq txt (buffer-substring beg end))
8154 (org-save-markers-in-region beg end)
8155 (delete-region beg end)
8156 (org-remove-empty-overlays-at beg)
8157 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8158 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8159 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8160 (let ((bbb (point)))
8161 (insert-before-markers txt)
8162 (org-reinstall-markers-in-region bbb)
8163 (move-marker ins-point bbb))
8164 (or (bolp) (insert "\n"))
8165 (setq ins-end (point))
8166 (goto-char ins-point)
8167 (org-skip-whitespace)
8168 (when (and (< arg 0)
8169 (org-first-sibling-p)
8170 (> ne-ins ne-beg))
8171 ;; Move whitespace back to beginning
8172 (save-excursion
8173 (goto-char ins-end)
8174 (let ((kill-whole-line t))
8175 (kill-line (- ne-ins ne-beg)) (point)))
8176 (insert (make-string (- ne-ins ne-beg) ?\n)))
8177 (move-marker ins-point nil)
8178 (if folded
8179 (outline-hide-subtree)
8180 (org-show-entry)
8181 (org-show-children))
8182 (org-clean-visibility-after-subtree-move)
8183 ;; move back to the initial column we were at
8184 (move-to-column col))))
8186 (defvar org-subtree-clip ""
8187 "Clipboard for cut and paste of subtrees.
8188 This is actually only a copy of the kill, because we use the normal kill
8189 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8191 (defvar org-subtree-clip-folded nil
8192 "Was the last copied subtree folded?
8193 This is used to fold the tree back after pasting.")
8195 (defun org-cut-subtree (&optional n)
8196 "Cut the current subtree into the clipboard.
8197 With prefix arg N, cut this many sequential subtrees.
8198 This is a short-hand for marking the subtree and then cutting it."
8199 (interactive "p")
8200 (org-copy-subtree n 'cut))
8202 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8203 "Copy the current subtree into the clipboard.
8204 With prefix arg N, copy this many sequential subtrees.
8205 This is a short-hand for marking the subtree and then copying it.
8206 If CUT is non-nil, actually cut the subtree.
8207 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8208 of some markers in the region, even if CUT is non-nil. This is
8209 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8210 (interactive "p")
8211 (org-preserve-local-variables
8212 (let (beg end folded (beg0 (point)))
8213 (if (called-interactively-p 'any)
8214 (org-back-to-heading nil) ; take what looks like a subtree
8215 (org-back-to-heading t)) ; take what is really there
8216 (setq beg (point))
8217 (skip-chars-forward " \t\r\n")
8218 (save-match-data
8219 (if nosubtrees
8220 (outline-next-heading)
8221 (save-excursion (outline-end-of-heading)
8222 (setq folded (org-invisible-p)))
8223 (ignore-errors (org-forward-heading-same-level (1- n) t))
8224 (org-end-of-subtree t t)))
8225 ;; Include the end of an inlinetask
8226 (when (and (featurep 'org-inlinetask)
8227 (looking-at-p (concat (org-inlinetask-outline-regexp)
8228 "END[ \t]*$")))
8229 (end-of-line))
8230 (setq end (point))
8231 (goto-char beg0)
8232 (when (> end beg)
8233 (setq org-subtree-clip-folded folded)
8234 (when (or cut force-store-markers)
8235 (org-save-markers-in-region beg end))
8236 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8237 (setq org-subtree-clip (current-kill 0))
8238 (message "%s: Subtree(s) with %d characters"
8239 (if cut "Cut" "Copied")
8240 (length org-subtree-clip))))))
8242 (defun org-paste-subtree (&optional level tree for-yank remove)
8243 "Paste the clipboard as a subtree, with modification of headline level.
8244 The entire subtree is promoted or demoted in order to match a new headline
8245 level.
8247 If the cursor is at the beginning of a headline, the same level as
8248 that headline is used to paste the tree.
8250 If not, the new level is derived from the *visible* headings
8251 before and after the insertion point, and taken to be the inferior headline
8252 level of the two. So if the previous visible heading is level 3 and the
8253 next is level 4 (or vice versa), level 4 will be used for insertion.
8254 This makes sure that the subtree remains an independent subtree and does
8255 not swallow low level entries.
8257 You can also force a different level, either by using a numeric prefix
8258 argument, or by inserting the heading marker by hand. For example, if the
8259 cursor is after \"*****\", then the tree will be shifted to level 5.
8261 If optional TREE is given, use this text instead of the kill ring.
8263 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8264 move back over whitespace before inserting, and move point to the end of
8265 the inserted text when done.
8267 When REMOVE is non-nil, remove the subtree from the clipboard."
8268 (interactive "P")
8269 (setq tree (or tree (and kill-ring (current-kill 0))))
8270 (unless (org-kill-is-subtree-p tree)
8271 (user-error "%s"
8272 (substitute-command-keys
8273 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8274 (org-with-limited-levels
8275 (let* ((visp (not (org-invisible-p)))
8276 (txt tree)
8277 (^re_ "\\(\\*+\\)[ \t]*")
8278 (old-level (if (string-match org-outline-regexp-bol txt)
8279 (- (match-end 0) (match-beginning 0) 1)
8280 -1))
8281 (force-level (cond (level (prefix-numeric-value level))
8282 ((and (looking-at "[ \t]*$")
8283 (string-match
8284 "^\\*+$" (buffer-substring
8285 (point-at-bol) (point))))
8286 (- (match-end 0) (match-beginning 0)))
8287 ((and (bolp)
8288 (looking-at org-outline-regexp))
8289 (- (match-end 0) (point) 1))))
8290 (previous-level (save-excursion
8291 (condition-case nil
8292 (progn
8293 (outline-previous-visible-heading 1)
8294 (if (looking-at ^re_)
8295 (- (match-end 0) (match-beginning 0) 1)
8297 (error 1))))
8298 (next-level (save-excursion
8299 (condition-case nil
8300 (progn
8301 (or (looking-at org-outline-regexp)
8302 (outline-next-visible-heading 1))
8303 (if (looking-at ^re_)
8304 (- (match-end 0) (match-beginning 0) 1)
8306 (error 1))))
8307 (new-level (or force-level (max previous-level next-level)))
8308 (shift (if (or (= old-level -1)
8309 (= new-level -1)
8310 (= old-level new-level))
8312 (- new-level old-level)))
8313 (delta (if (> shift 0) -1 1))
8314 (func (if (> shift 0) 'org-demote 'org-promote))
8315 (org-odd-levels-only nil)
8316 beg end newend)
8317 ;; Remove the forced level indicator
8318 (when force-level
8319 (delete-region (point-at-bol) (point)))
8320 ;; Paste
8321 (beginning-of-line (if (bolp) 1 2))
8322 (setq beg (point))
8323 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8324 (insert-before-markers txt)
8325 (unless (string-suffix-p "\n" txt) (insert "\n"))
8326 (setq newend (point))
8327 (org-reinstall-markers-in-region beg)
8328 (setq end (point))
8329 (goto-char beg)
8330 (skip-chars-forward " \t\n\r")
8331 (setq beg (point))
8332 (when (and (org-invisible-p) visp)
8333 (save-excursion (outline-show-heading)))
8334 ;; Shift if necessary
8335 (unless (= shift 0)
8336 (save-restriction
8337 (narrow-to-region beg end)
8338 (while (not (= shift 0))
8339 (org-map-region func (point-min) (point-max))
8340 (setq shift (+ delta shift)))
8341 (goto-char (point-min))
8342 (setq newend (point-max))))
8343 (when (or (called-interactively-p 'interactive) for-yank)
8344 (message "Clipboard pasted as level %d subtree" new-level))
8345 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8346 kill-ring
8347 (eq org-subtree-clip (current-kill 0))
8348 org-subtree-clip-folded)
8349 ;; The tree was folded before it was killed/copied
8350 (outline-hide-subtree))
8351 (and for-yank (goto-char newend))
8352 (and remove (setq kill-ring (cdr kill-ring))))))
8354 (defun org-kill-is-subtree-p (&optional txt)
8355 "Check if the current kill is an outline subtree, or a set of trees.
8356 Returns nil if kill does not start with a headline, or if the first
8357 headline level is not the largest headline level in the tree.
8358 So this will actually accept several entries of equal levels as well,
8359 which is OK for `org-paste-subtree'.
8360 If optional TXT is given, check this string instead of the current kill."
8361 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8362 (re (org-get-limited-outline-regexp))
8363 (^re (concat "^" re))
8364 (start-level (and kill
8365 (string-match
8366 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8367 kill)
8368 (- (match-end 2) (match-beginning 2) 1)))
8369 (start (1+ (or (match-beginning 2) -1))))
8370 (if (not start-level)
8371 (progn
8372 nil) ;; does not even start with a heading
8373 (catch 'exit
8374 (while (setq start (string-match ^re kill (1+ start)))
8375 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8376 (throw 'exit nil)))
8377 t))))
8379 (defvar org-markers-to-move nil
8380 "Markers that should be moved with a cut-and-paste operation.
8381 Those markers are stored together with their positions relative to
8382 the start of the region.")
8384 (defun org-save-markers-in-region (beg end)
8385 "Check markers in region.
8386 If these markers are between BEG and END, record their position relative
8387 to BEG, so that after moving the block of text, we can put the markers back
8388 into place.
8389 This function gets called just before an entry or tree gets cut from the
8390 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8391 called immediately, to move the markers with the entries."
8392 (setq org-markers-to-move nil)
8393 (when (featurep 'org-clock)
8394 (org-clock-save-markers-for-cut-and-paste beg end))
8395 (when (featurep 'org-agenda)
8396 (org-agenda-save-markers-for-cut-and-paste beg end)))
8398 (defun org-check-and-save-marker (marker beg end)
8399 "Check if MARKER is between BEG and END.
8400 If yes, remember the marker and the distance to BEG."
8401 (when (and (marker-buffer marker)
8402 (equal (marker-buffer marker) (current-buffer))
8403 (>= marker beg) (< marker end))
8404 (push (cons marker (- marker beg)) org-markers-to-move)))
8406 (defun org-reinstall-markers-in-region (beg)
8407 "Move all remembered markers to their position relative to BEG."
8408 (dolist (x org-markers-to-move)
8409 (move-marker (car x) (+ beg (cdr x))))
8410 (setq org-markers-to-move nil))
8412 (defun org-narrow-to-subtree ()
8413 "Narrow buffer to the current subtree."
8414 (interactive)
8415 (save-excursion
8416 (save-match-data
8417 (org-with-limited-levels
8418 (narrow-to-region
8419 (progn (org-back-to-heading t) (point))
8420 (progn (org-end-of-subtree t t)
8421 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8422 (point)))))))
8424 (defun org-narrow-to-block ()
8425 "Narrow buffer to the current block."
8426 (interactive)
8427 (let* ((case-fold-search t)
8428 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8429 "^[ \t]*#\\+end_.*")))
8430 (if blockp
8431 (narrow-to-region (car blockp) (cdr blockp))
8432 (user-error "Not in a block"))))
8434 (defun org-clone-subtree-with-time-shift (n &optional shift)
8435 "Clone the task (subtree) at point N times.
8436 The clones will be inserted as siblings.
8438 In interactive use, the user will be prompted for the number of
8439 clones to be produced. If the entry has a timestamp, the user
8440 will also be prompted for a time shift, which may be a repeater
8441 as used in time stamps, for example `+3d'. To disable this,
8442 you can call the function with a universal prefix argument.
8444 When a valid repeater is given and the entry contains any time
8445 stamps, the clones will become a sequence in time, with time
8446 stamps in the subtree shifted for each clone produced. If SHIFT
8447 is nil or the empty string, time stamps will be left alone. The
8448 ID property of the original subtree is removed.
8450 In each clone, all the CLOCK entries will be removed. This
8451 prevents Org from considering that the clocked times overlap.
8453 If the original subtree did contain time stamps with a repeater,
8454 the following will happen:
8455 - the repeater will be removed in each clone
8456 - an additional clone will be produced, with the current, unshifted
8457 date(s) in the entry.
8458 - the original entry will be placed *after* all the clones, with
8459 repeater intact.
8460 - the start days in the repeater in the original entry will be shifted
8461 to past the last clone.
8462 In this way you can spell out a number of instances of a repeating task,
8463 and still retain the repeater to cover future instances of the task.
8465 As described above, N+1 clones are produced when the original
8466 subtree has a repeater. Setting N to 0, then, can be used to
8467 remove the repeater from a subtree and create a shifted clone
8468 with the original repeater."
8469 (interactive "nNumber of clones to produce: ")
8470 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8471 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8472 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8473 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8474 (shift
8475 (or shift
8476 (if (and (not (equal current-prefix-arg '(4)))
8477 (save-excursion
8478 (goto-char beg)
8479 (re-search-forward org-ts-regexp-both end-of-tree t)))
8480 (read-from-minibuffer
8481 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8482 ""))) ;No time shift
8483 (doshift
8484 (and (org-string-nw-p shift)
8485 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8486 shift)
8487 (user-error "Invalid shift specification %s" shift)))))
8488 (goto-char end-of-tree)
8489 (unless (bolp) (insert "\n"))
8490 (let* ((end (point))
8491 (template (buffer-substring beg end))
8492 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8493 (shift-what (pcase (and doshift (match-string 2 shift))
8494 (`nil nil)
8495 ("d" 'day)
8496 ("w" (setq shift-n (* 7 shift-n)) 'day)
8497 ("m" 'month)
8498 ("y" 'year)
8499 (_ (error "Unsupported time unit"))))
8500 (nmin 1)
8501 (nmax n)
8502 (n-no-remove -1)
8503 (idprop (org-entry-get nil "ID")))
8504 (when (and doshift
8505 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8506 template))
8507 (delete-region beg end)
8508 (setq end beg)
8509 (setq nmin 0)
8510 (setq nmax (1+ nmax))
8511 (setq n-no-remove nmax))
8512 (goto-char end)
8513 (cl-loop for n from nmin to nmax do
8514 (insert
8515 ;; Prepare clone.
8516 (with-temp-buffer
8517 (insert template)
8518 (org-mode)
8519 (goto-char (point-min))
8520 (org-show-subtree)
8521 (and idprop (if org-clone-delete-id
8522 (org-entry-delete nil "ID")
8523 (org-id-get-create t)))
8524 (unless (= n 0)
8525 (while (re-search-forward org-clock-line-re nil t)
8526 (delete-region (line-beginning-position)
8527 (line-beginning-position 2)))
8528 (goto-char (point-min))
8529 (while (re-search-forward org-drawer-regexp nil t)
8530 (org-remove-empty-drawer-at (point))))
8531 (goto-char (point-min))
8532 (when doshift
8533 (while (re-search-forward org-ts-regexp-both nil t)
8534 (org-timestamp-change (* n shift-n) shift-what))
8535 (unless (= n n-no-remove)
8536 (goto-char (point-min))
8537 (while (re-search-forward org-ts-regexp nil t)
8538 (save-excursion
8539 (goto-char (match-beginning 0))
8540 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8541 (delete-region (match-beginning 1) (match-end 1)))))))
8542 (buffer-string)))))
8543 (goto-char beg)))
8545 ;;; Outline Sorting
8547 (defun org-sort (&optional with-case)
8548 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8549 Optional argument WITH-CASE means sort case-sensitively."
8550 (interactive "P")
8551 (org-call-with-arg
8552 (cond ((org-at-table-p) #'org-table-sort-lines)
8553 ((org-at-item-p) #'org-sort-list)
8554 (t #'org-sort-entries))
8555 with-case))
8557 (defun org-sort-remove-invisible (s)
8558 "Remove invisible part of links and emphasis markers from string S."
8559 (remove-text-properties 0 (length s) org-rm-props s)
8560 (replace-regexp-in-string
8561 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8562 (replace-regexp-in-string
8563 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8564 (org-link-display-format s)
8565 t t) t t))
8567 (defvar org-priority-regexp) ; defined later in the file
8569 (defvar org-after-sorting-entries-or-items-hook nil
8570 "Hook that is run after a bunch of entries or items have been sorted.
8571 When children are sorted, the cursor is in the parent line when this
8572 hook gets called. When a region or a plain list is sorted, the cursor
8573 will be in the first entry of the sorted region/list.")
8575 (defun org-sort-entries
8576 (&optional with-case sorting-type getkey-func compare-func property
8577 interactive?)
8578 "Sort entries on a certain level of an outline tree.
8579 If there is an active region, the entries in the region are sorted.
8580 Else, if the cursor is before the first entry, sort the top-level items.
8581 Else, the children of the entry at point are sorted.
8583 Sorting can be alphabetically, numerically, by date/time as given by
8584 a time stamp, by a property, by priority order, or by a custom function.
8586 The command prompts for the sorting type unless it has been given to the
8587 function through the SORTING-TYPE argument, which needs to be a character,
8588 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8589 the precise meaning of each character:
8591 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8592 c By creation time, which is assumed to be the first inactive time stamp
8593 at the beginning of a line.
8594 d By deadline date/time.
8595 k By clocking time.
8596 n Numerically, by converting the beginning of the entry/item to a number.
8597 o By order of TODO keywords.
8598 p By priority according to the cookie.
8599 r By the value of a property.
8600 s By scheduled date/time.
8601 t By date/time, either the first active time stamp in the entry, or, if
8602 none exist, by the first inactive one.
8604 Capital letters will reverse the sort order.
8606 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8607 called with point at the beginning of the record. It must return a
8608 value that is compatible with COMPARE-FUNC, the function used to
8609 compare entries.
8611 Comparing entries ignores case by default. However, with an optional argument
8612 WITH-CASE, the sorting considers case as well.
8614 Sorting is done against the visible part of the headlines, it ignores hidden
8615 links.
8617 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8619 A non-nil value for INTERACTIVE? is used to signal that this
8620 function is being called interactively."
8621 (interactive (list current-prefix-arg nil nil nil nil t))
8622 (let ((case-func (if with-case 'identity 'downcase))
8623 start beg end stars re re2
8624 txt what tmp)
8625 ;; Find beginning and end of region to sort
8626 (cond
8627 ((org-region-active-p)
8628 ;; we will sort the region
8629 (setq end (region-end)
8630 what "region")
8631 (goto-char (region-beginning))
8632 (unless (org-at-heading-p) (outline-next-heading))
8633 (setq start (point)))
8634 ((or (org-at-heading-p)
8635 (ignore-errors (progn (org-back-to-heading) t)))
8636 ;; we will sort the children of the current headline
8637 (org-back-to-heading)
8638 (setq start (point)
8639 end (progn (org-end-of-subtree t t)
8640 (or (bolp) (insert "\n"))
8641 (when (>= (org-back-over-empty-lines) 1)
8642 (forward-line 1))
8643 (point))
8644 what "children")
8645 (goto-char start)
8646 (outline-show-subtree)
8647 (outline-next-heading))
8649 ;; we will sort the top-level entries in this file
8650 (goto-char (point-min))
8651 (or (org-at-heading-p) (outline-next-heading))
8652 (setq start (point))
8653 (goto-char (point-max))
8654 (beginning-of-line 1)
8655 (when (looking-at ".*?\\S-")
8656 ;; File ends in a non-white line
8657 (end-of-line 1)
8658 (insert "\n"))
8659 (setq end (point-max))
8660 (setq what "top-level")
8661 (goto-char start)
8662 (org-show-all '(headings blocks))))
8664 (setq beg (point))
8665 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8667 (looking-at "\\(\\*+\\)")
8668 (setq stars (match-string 1)
8669 re (concat "^" (regexp-quote stars) " +")
8670 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8671 txt (buffer-substring beg end))
8672 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8673 (when (and (not (equal stars "*")) (string-match re2 txt))
8674 (user-error "Region to sort contains a level above the first entry"))
8676 (unless sorting-type
8677 (message
8678 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8679 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8680 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8681 what)
8682 (setq sorting-type (read-char-exclusive)))
8684 (unless getkey-func
8685 (and (= (downcase sorting-type) ?f)
8686 (setq getkey-func
8687 (or (and interactive?
8688 (org-read-function
8689 "Function for extracting keys: "))
8690 (error "Missing key extractor")))))
8692 (and (= (downcase sorting-type) ?r)
8693 (not property)
8694 (setq property
8695 (completing-read "Property: "
8696 (mapcar #'list (org-buffer-property-keys t))
8697 nil t)))
8699 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8700 (message "Sorting entries...")
8702 (save-restriction
8703 (narrow-to-region start end)
8704 (let ((restore-clock?
8705 ;; The clock marker is lost when using `sort-subr'; mark
8706 ;; the clock with temporary `:org-clock-marker-backup'
8707 ;; text property.
8708 (when (and (eq (org-clock-is-active) (current-buffer))
8709 (<= start (marker-position org-clock-marker))
8710 (>= end (marker-position org-clock-marker)))
8711 (org-with-silent-modifications
8712 (put-text-property (1- org-clock-marker) org-clock-marker
8713 :org-clock-marker-backup t))
8715 (dcst (downcase sorting-type))
8716 (case-fold-search nil)
8717 (now (current-time)))
8718 (org-preserve-local-variables
8719 (sort-subr
8720 (/= dcst sorting-type)
8721 ;; This function moves to the beginning character of the
8722 ;; "record" to be sorted.
8723 (lambda nil
8724 (if (re-search-forward re nil t)
8725 (goto-char (match-beginning 0))
8726 (goto-char (point-max))))
8727 ;; This function moves to the last character of the "record" being
8728 ;; sorted.
8729 (lambda nil
8730 (save-match-data
8731 (condition-case nil
8732 (outline-forward-same-level 1)
8733 (error
8734 (goto-char (point-max))))))
8735 ;; This function returns the value that gets sorted against.
8736 (lambda ()
8737 (cond
8738 ((= dcst ?n)
8739 (if (looking-at org-complex-heading-regexp)
8740 (string-to-number
8741 (org-sort-remove-invisible (match-string 4)))
8742 nil))
8743 ((= dcst ?a)
8744 (if (looking-at org-complex-heading-regexp)
8745 (funcall case-func
8746 (org-sort-remove-invisible (match-string 4)))
8747 nil))
8748 ((= dcst ?k)
8749 (or (get-text-property (point) :org-clock-minutes) 0))
8750 ((= dcst ?t)
8751 (let ((end (save-excursion (outline-next-heading) (point))))
8752 (if (or (re-search-forward org-ts-regexp end t)
8753 (re-search-forward org-ts-regexp-both end t))
8754 (org-time-string-to-seconds (match-string 0))
8755 (float-time now))))
8756 ((= dcst ?c)
8757 (let ((end (save-excursion (outline-next-heading) (point))))
8758 (if (re-search-forward
8759 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8760 end t)
8761 (org-time-string-to-seconds (match-string 0))
8762 (float-time now))))
8763 ((= dcst ?s)
8764 (let ((end (save-excursion (outline-next-heading) (point))))
8765 (if (re-search-forward org-scheduled-time-regexp end t)
8766 (org-time-string-to-seconds (match-string 1))
8767 (float-time now))))
8768 ((= dcst ?d)
8769 (let ((end (save-excursion (outline-next-heading) (point))))
8770 (if (re-search-forward org-deadline-time-regexp end t)
8771 (org-time-string-to-seconds (match-string 1))
8772 (float-time now))))
8773 ((= dcst ?p)
8774 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8775 (string-to-char (match-string 2))
8776 org-default-priority))
8777 ((= dcst ?r)
8778 (or (org-entry-get nil property) ""))
8779 ((= dcst ?o)
8780 (when (looking-at org-complex-heading-regexp)
8781 (let* ((m (match-string 2))
8782 (s (if (member m org-done-keywords) '- '+)))
8783 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8784 ((= dcst ?f)
8785 (if getkey-func
8786 (progn
8787 (setq tmp (funcall getkey-func))
8788 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8789 tmp)
8790 (error "Invalid key function `%s'" getkey-func)))
8791 (t (error "Invalid sorting type `%c'" sorting-type))))
8793 (cond
8794 ((= dcst ?a) 'org-string-collate-lessp)
8795 ((= dcst ?f)
8796 (or compare-func
8797 (and interactive?
8798 (org-read-function
8799 (concat "Function for comparing keys "
8800 "(empty for default `sort-subr' predicate): ")
8801 'allow-empty))))
8802 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8803 (when restore-clock?
8804 (move-marker org-clock-marker
8805 (1+ (next-single-property-change
8806 start :org-clock-marker-backup)))
8807 (remove-text-properties (1- org-clock-marker) org-clock-marker
8808 '(:org-clock-marker-backup t)))))
8809 (run-hooks 'org-after-sorting-entries-or-items-hook)
8810 (message "Sorting entries...done")))
8812 (defun org-contextualize-keys (alist contexts)
8813 "Return valid elements in ALIST depending on CONTEXTS.
8815 `org-agenda-custom-commands' or `org-capture-templates' are the
8816 values used for ALIST, and `org-agenda-custom-commands-contexts'
8817 or `org-capture-templates-contexts' are the associated contexts
8818 definitions."
8819 (let ((contexts
8820 ;; normalize contexts
8821 (mapcar
8822 (lambda(c) (cond ((listp (cadr c))
8823 (list (car c) (car c) (nth 1 c)))
8824 ((string= "" (cadr c))
8825 (list (car c) (car c) (nth 2 c)))
8826 (t c)))
8827 contexts))
8828 (a alist) r s)
8829 ;; loop over all commands or templates
8830 (dolist (c a)
8831 (let (vrules repl)
8832 (cond
8833 ((not (assoc (car c) contexts))
8834 (push c r))
8835 ((and (assoc (car c) contexts)
8836 (setq vrules (org-contextualize-validate-key
8837 (car c) contexts)))
8838 (mapc (lambda (vr)
8839 (unless (equal (car vr) (cadr vr))
8840 (setq repl vr)))
8841 vrules)
8842 (if (not repl) (push c r)
8843 (push (cadr repl) s)
8844 (push
8845 (cons (car c)
8846 (cdr (or (assoc (cadr repl) alist)
8847 (error "Undefined key `%s' as contextual replacement for `%s'"
8848 (cadr repl) (car c)))))
8849 r))))))
8850 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8851 (delq
8853 (delete-dups
8854 (mapcar (lambda (x)
8855 (let ((tpl (car x)))
8856 (unless (delq
8858 (mapcar (lambda (y)
8859 (equal y tpl))
8861 x)))
8862 (reverse r))))))
8864 (defun org-contextualize-validate-key (key contexts)
8865 "Check CONTEXTS for agenda or capture KEY."
8866 (let (res)
8867 (dolist (r contexts)
8868 (dolist (rr (car (last r)))
8869 (when
8870 (and (equal key (car r))
8871 (if (functionp rr) (funcall rr)
8872 (or (and (eq (car rr) 'in-file)
8873 (buffer-file-name)
8874 (string-match (cdr rr) (buffer-file-name)))
8875 (and (eq (car rr) 'in-mode)
8876 (string-match (cdr rr) (symbol-name major-mode)))
8877 (and (eq (car rr) 'in-buffer)
8878 (string-match (cdr rr) (buffer-name)))
8879 (when (and (eq (car rr) 'not-in-file)
8880 (buffer-file-name))
8881 (not (string-match (cdr rr) (buffer-file-name))))
8882 (when (eq (car rr) 'not-in-mode)
8883 (not (string-match (cdr rr) (symbol-name major-mode))))
8884 (when (eq (car rr) 'not-in-buffer)
8885 (not (string-match (cdr rr) (buffer-name)))))))
8886 (push r res))))
8887 (delete-dups (delq nil res))))
8889 (defun org-context-p (&rest contexts)
8890 "Check if local context is any of CONTEXTS.
8891 Possible values in the list of contexts are `table', `headline', and `item'."
8892 (let ((pos (point)))
8893 (goto-char (point-at-bol))
8894 (prog1 (or (and (memq 'table contexts)
8895 (looking-at "[ \t]*|"))
8896 (and (memq 'headline contexts)
8897 (looking-at org-outline-regexp))
8898 (and (memq 'item contexts)
8899 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8900 (and (memq 'item-body contexts)
8901 (org-in-item-p)))
8902 (goto-char pos))))
8904 ;; Defined to provide a value for defcustom, since there is no
8905 ;; string-collate-greaterp in Emacs.
8906 (defun org-string-collate-greaterp (s1 s2)
8907 "Return non-nil if S1 is greater than S2 in collation order."
8908 (not (org-string-collate-lessp s1 s2)))
8910 ;;;###autoload
8911 (defun org-run-like-in-org-mode (cmd)
8912 "Run a command, pretending that the current buffer is in Org mode.
8913 This will temporarily bind local variables that are typically bound in
8914 Org mode to the values they have in Org mode, and then interactively
8915 call CMD."
8916 (org-load-modules-maybe)
8917 (let (binds)
8918 (dolist (var (org-get-local-variables))
8919 (when (or (not (boundp (car var)))
8920 (eq (symbol-value (car var))
8921 (default-value (car var))))
8922 (push (list (car var) `(quote ,(cadr var))) binds)))
8923 (eval `(let ,binds
8924 (call-interactively (quote ,cmd))))))
8926 (defun org-get-category (&optional pos force-refresh)
8927 "Get the category applying to position POS."
8928 (save-match-data
8929 (when force-refresh (org-refresh-category-properties))
8930 (let ((pos (or pos (point))))
8931 (or (get-text-property pos 'org-category)
8932 (progn (org-refresh-category-properties)
8933 (get-text-property pos 'org-category))))))
8935 ;;; Refresh properties
8937 (defun org-refresh-properties (dprop tprop)
8938 "Refresh buffer text properties.
8939 DPROP is the drawer property and TPROP is either the
8940 corresponding text property to set, or an alist with each element
8941 being a text property (as a symbol) and a function to apply to
8942 the value of the drawer property."
8943 (let* ((case-fold-search t)
8944 (inhibit-read-only t)
8945 (inherit? (org-property-inherit-p dprop))
8946 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8947 (global (and inherit? (org--property-global-value dprop nil))))
8948 (org-with-silent-modifications
8949 (org-with-point-at 1
8950 ;; Set global values (e.g., values defined through
8951 ;; "#+PROPERTY:" keywords) to the whole buffer.
8952 (when global (put-text-property (point-min) (point-max) tprop global))
8953 ;; Set local values.
8954 (while (re-search-forward property-re nil t)
8955 (when (org-at-property-p)
8956 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8957 (outline-next-heading))))))
8959 (defun org-refresh-property (tprop p &optional inherit)
8960 "Refresh the buffer text property TPROP from the drawer property P.
8961 The refresh happens only for the current headline, or the whole
8962 sub-tree if optional argument INHERIT is non-nil."
8963 (unless (org-before-first-heading-p)
8964 (save-excursion
8965 (org-back-to-heading t)
8966 (let ((start (point))
8967 (end (save-excursion
8968 (if inherit (org-end-of-subtree t t)
8969 (or (outline-next-heading) (point-max))))))
8970 (if (symbolp tprop)
8971 ;; TPROP is a text property symbol.
8972 (put-text-property start end tprop p)
8973 ;; TPROP is an alist with (property . function) elements.
8974 (pcase-dolist (`(,prop . ,f) tprop)
8975 (put-text-property start end prop (funcall f p))))))))
8977 (defun org-refresh-category-properties ()
8978 "Refresh category text properties in the buffer."
8979 (let ((case-fold-search t)
8980 (inhibit-read-only t)
8981 (default-category
8982 (cond ((null org-category)
8983 (if buffer-file-name
8984 (file-name-sans-extension
8985 (file-name-nondirectory buffer-file-name))
8986 "???"))
8987 ((symbolp org-category) (symbol-name org-category))
8988 (t org-category))))
8989 (org-with-silent-modifications
8990 (org-with-wide-buffer
8991 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8992 ;; This is the default category for the buffer. If none is
8993 ;; found, fall-back to `org-category' or buffer file name.
8994 (put-text-property
8995 (point-min) (point-max)
8996 'org-category
8997 (catch 'buffer-category
8998 (goto-char (point-max))
8999 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9000 (let ((element (org-element-at-point)))
9001 (when (eq (org-element-type element) 'keyword)
9002 (throw 'buffer-category
9003 (org-element-property :value element)))))
9004 default-category))
9005 ;; Set sub-tree specific categories.
9006 (goto-char (point-min))
9007 (let ((regexp (org-re-property "CATEGORY")))
9008 (while (re-search-forward regexp nil t)
9009 (let ((value (match-string-no-properties 3)))
9010 (when (org-at-property-p)
9011 (put-text-property
9012 (save-excursion (org-back-to-heading t) (point))
9013 (save-excursion (org-end-of-subtree t t) (point))
9014 'org-category
9015 value)))))))))
9017 (defun org-refresh-stats-properties ()
9018 "Refresh stats text properties in the buffer."
9019 (org-with-silent-modifications
9020 (org-with-point-at 1
9021 (let ((regexp (concat org-outline-regexp-bol
9022 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9023 (while (re-search-forward regexp nil t)
9024 (let* ((numerator (string-to-number (match-string 1)))
9025 (denominator (and (match-end 2)
9026 (string-to-number (match-string 2))))
9027 (stats (cond ((not denominator) numerator) ;percent
9028 ((= denominator 0) 0)
9029 (t (/ (* numerator 100) denominator)))))
9030 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9031 'org-stats stats)))))))
9033 (defun org-refresh-effort-properties ()
9034 "Refresh effort properties"
9035 (org-refresh-properties
9036 org-effort-property
9037 '((effort . identity)
9038 (effort-minutes . org-duration-to-minutes))))
9040 ;;;; Link Stuff
9042 ;;; Link abbreviations
9044 (defun org-link-expand-abbrev (link)
9045 "Apply replacements as defined in `org-link-abbrev-alist'."
9046 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9047 (let* ((key (match-string 1 link))
9048 (as (or (assoc key org-link-abbrev-alist-local)
9049 (assoc key org-link-abbrev-alist)))
9050 (tag (and (match-end 2) (match-string 3 link)))
9051 rpl)
9052 (if (not as)
9053 link
9054 (setq rpl (cdr as))
9055 (cond
9056 ((symbolp rpl) (funcall rpl tag))
9057 ((string-match "%(\\([^)]+\\))" rpl)
9058 (replace-match
9059 (save-match-data
9060 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9061 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9062 ((string-match "%h" rpl)
9063 (replace-match (url-hexify-string (or tag "")) t t rpl))
9064 (t (concat rpl tag)))))
9065 link))
9067 ;;; Storing and inserting links
9069 (defvar org-insert-link-history nil
9070 "Minibuffer history for links inserted with `org-insert-link'.")
9072 (defvar org-stored-links nil
9073 "Contains the links stored with `org-store-link'.")
9075 (defvar org-store-link-plist nil
9076 "Plist with info about the most recently link created with `org-store-link'.")
9078 (defun org-store-link-functions ()
9079 "Return a list of functions that are called to create and store a link.
9080 The functions defined in the :store property of
9081 `org-link-parameters'.
9083 Each function will be called in turn until one returns a non-nil
9084 value. Each function should check if it is responsible for
9085 creating this link (for example by looking at the major mode).
9086 If not, it must exit and return nil. If yes, it should return
9087 a non-nil value after calling `org-store-link-props' with a list
9088 of properties and values. Special properties are:
9090 :type The link prefix, like \"http\". This must be given.
9091 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9092 This is obligatory as well.
9093 :description Optional default description for the second pair
9094 of brackets in an Org mode link. The user can still change
9095 this when inserting this link into an Org mode buffer.
9097 In addition to these, any additional properties can be specified
9098 and then used in capture templates."
9099 (cl-loop for link in org-link-parameters
9100 with store-func
9101 do (setq store-func (org-link-get-parameter (car link) :store))
9102 if store-func
9103 collect store-func))
9105 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9106 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9108 ;;;###autoload
9109 (defun org-store-link (arg &optional interactive?)
9110 "Store an org-link to the current location.
9111 \\<org-mode-map>
9112 This link is added to `org-stored-links' and can later be inserted
9113 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9115 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9116 A single
9117 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9118 `org-gnus-prefer-web-links' for links to Usenet articles.
9120 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9121 skipping storing functions that are not
9122 part of Org core.
9124 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9125 prefix ARG forces storing a link for each line in the
9126 active region.
9128 Assume the function is called interactively if INTERACTIVE? is
9129 non-nil."
9130 (interactive "P\np")
9131 (org-load-modules-maybe)
9132 (if (and (equal arg '(64)) (org-region-active-p))
9133 (save-excursion
9134 (let ((end (region-end)))
9135 (goto-char (region-beginning))
9136 (set-mark (point))
9137 (while (< (point-at-eol) end)
9138 (move-end-of-line 1) (activate-mark)
9139 (let (current-prefix-arg)
9140 (call-interactively 'org-store-link))
9141 (move-beginning-of-line 2)
9142 (set-mark (point)))))
9143 (setq org-store-link-plist nil)
9144 (let (link cpltxt desc description search txt custom-id agenda-link)
9145 (cond
9146 ;; Store a link using an external link type, if any function is
9147 ;; available. If more than one can generate a link from current
9148 ;; location, ask which one to use.
9149 ((and (not (equal arg '(16)))
9150 (let ((results-alist nil))
9151 (dolist (f (org-store-link-functions))
9152 (when (funcall f)
9153 ;; XXX: return value is not link's plist, so we
9154 ;; store the new value before it is modified. It
9155 ;; would be cleaner to ask store link functions to
9156 ;; return the plist instead.
9157 (push (cons f (copy-sequence org-store-link-plist))
9158 results-alist)))
9159 (pcase results-alist
9160 (`nil nil)
9161 (`((,_ . ,_)) t) ;single choice: nothing to do
9162 (`((,name . ,_) . ,_)
9163 ;; Reinstate link plist associated to the chosen
9164 ;; function.
9165 (apply #'org-store-link-props
9166 (cdr (assoc-string
9167 (completing-read
9168 "Which function for creating the link? "
9169 (mapcar #'car results-alist)
9170 nil t (symbol-name name))
9171 results-alist)))
9172 t))))
9173 (setq link (plist-get org-store-link-plist :link))
9174 (setq desc (or (plist-get org-store-link-plist :description)
9175 link)))
9177 ;; Store a link from a source code buffer.
9178 ((org-src-edit-buffer-p)
9179 (let ((coderef-format (org-src-coderef-format)))
9180 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9181 (setq link (format "(%s)" (match-string-no-properties 3))))
9182 (interactive?
9183 (let ((label (read-string "Code line label: ")))
9184 (end-of-line)
9185 (setq link (format coderef-format label))
9186 (let ((gc (- 79 (length link))))
9187 (if (< (current-column) gc)
9188 (org-move-to-column gc t)
9189 (insert " ")))
9190 (insert link)
9191 (setq link (concat "(" label ")"))
9192 (setq desc nil)))
9193 (t (setq link nil)))))
9195 ;; We are in the agenda, link to referenced location
9196 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9197 (let ((m (or (get-text-property (point) 'org-hd-marker)
9198 (get-text-property (point) 'org-marker))))
9199 (when m
9200 (org-with-point-at m
9201 (setq agenda-link (org-store-link nil interactive?))))))
9203 ((eq major-mode 'calendar-mode)
9204 (let ((cd (calendar-cursor-to-date)))
9205 (setq link
9206 (format-time-string
9207 (car org-time-stamp-formats)
9208 (apply 'encode-time
9209 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9210 nil nil nil))))
9211 (org-store-link-props :type "calendar" :date cd)))
9213 ((eq major-mode 'help-mode)
9214 (setq link (concat "help:" (save-excursion
9215 (goto-char (point-min))
9216 (looking-at "^[^ ]+")
9217 (match-string 0))))
9218 (org-store-link-props :type "help"))
9220 ((eq major-mode 'w3-mode)
9221 (setq cpltxt (if (and (buffer-name)
9222 (not (string-match "Untitled" (buffer-name))))
9223 (buffer-name)
9224 (url-view-url t))
9225 link (url-view-url t))
9226 (org-store-link-props :type "w3" :url (url-view-url t)))
9228 ((eq major-mode 'image-mode)
9229 (setq cpltxt (concat "file:"
9230 (abbreviate-file-name buffer-file-name))
9231 link cpltxt)
9232 (org-store-link-props :type "image" :file buffer-file-name))
9234 ;; In dired, store a link to the file of the current line
9235 ((derived-mode-p 'dired-mode)
9236 (let ((file (dired-get-filename nil t)))
9237 (setq file (if file
9238 (abbreviate-file-name
9239 (expand-file-name (dired-get-filename nil t)))
9240 ;; otherwise, no file so use current directory.
9241 default-directory))
9242 (setq cpltxt (concat "file:" file)
9243 link cpltxt)))
9245 ((setq search (run-hook-with-args-until-success
9246 'org-create-file-search-functions))
9247 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9248 "::" search))
9249 (setq cpltxt (or description link)))
9251 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9252 (org-with-limited-levels
9253 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9254 (cond
9255 ;; Store a link using the target at point
9256 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9257 (setq cpltxt
9258 (concat "file:"
9259 (abbreviate-file-name
9260 (buffer-file-name (buffer-base-buffer)))
9261 "::" (match-string 1))
9262 link cpltxt))
9263 ((and (featurep 'org-id)
9264 (or (eq org-id-link-to-org-use-id t)
9265 (and interactive?
9266 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9267 (and (eq org-id-link-to-org-use-id
9268 'create-if-interactive-and-no-custom-id)
9269 (not custom-id))))
9270 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9271 ;; Store a link using the ID at point
9272 (setq link (condition-case nil
9273 (prog1 (org-id-store-link)
9274 (setq desc (or (plist-get org-store-link-plist
9275 :description)
9276 "")))
9277 (error
9278 ;; Probably before first headline, link only to file
9279 (concat "file:"
9280 (abbreviate-file-name
9281 (buffer-file-name (buffer-base-buffer))))))))
9283 ;; Just link to current headline
9284 (setq cpltxt (concat "file:"
9285 (abbreviate-file-name
9286 (buffer-file-name (buffer-base-buffer)))))
9287 ;; Add a context search string
9288 (when (org-xor org-context-in-file-links
9289 (equal arg '(4)))
9290 (let* ((element (org-element-at-point))
9291 (name (org-element-property :name element)))
9292 (setq txt (cond
9293 ((org-at-heading-p) nil)
9294 (name)
9295 ((org-region-active-p)
9296 (buffer-substring (region-beginning) (region-end)))))
9297 (when (or (null txt) (string-match "\\S-" txt))
9298 (setq cpltxt
9299 (concat cpltxt "::"
9300 (condition-case nil
9301 (org-make-org-heading-search-string txt)
9302 (error "")))
9303 desc (or name
9304 (nth 4 (ignore-errors (org-heading-components)))
9305 "NONE")))))
9306 (when (string-match "::\\'" cpltxt)
9307 (setq cpltxt (substring cpltxt 0 -2)))
9308 (setq link cpltxt)))))
9310 ((buffer-file-name (buffer-base-buffer))
9311 ;; Just link to this file here.
9312 (setq cpltxt (concat "file:"
9313 (abbreviate-file-name
9314 (buffer-file-name (buffer-base-buffer)))))
9315 ;; Add a context string.
9316 (when (org-xor org-context-in-file-links
9317 (equal arg '(4)))
9318 (setq txt (if (org-region-active-p)
9319 (buffer-substring (region-beginning) (region-end))
9320 (buffer-substring (point-at-bol) (point-at-eol))))
9321 ;; Only use search option if there is some text.
9322 (when (string-match "\\S-" txt)
9323 (setq cpltxt
9324 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9325 desc "NONE")))
9326 (setq link cpltxt))
9328 (interactive?
9329 (user-error "No method for storing a link from this buffer"))
9331 (t (setq link nil)))
9333 ;; We're done setting link and desc, clean up
9334 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9335 (setq link (or link cpltxt)
9336 desc (or desc cpltxt))
9337 (cond ((not desc))
9338 ((equal desc "NONE") (setq desc nil))
9339 (t (setq desc
9340 (replace-regexp-in-string
9341 org-bracket-link-analytic-regexp
9342 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9343 desc))))
9344 ;; Return the link
9345 (if (not (and interactive? link))
9346 (or agenda-link (and link (org-make-link-string link desc)))
9347 (push (list link desc) org-stored-links)
9348 (message "Stored: %s" (or desc link))
9349 (when custom-id
9350 (setq link (concat "file:" (abbreviate-file-name
9351 (buffer-file-name)) "::#" custom-id))
9352 (push (list link desc) org-stored-links))
9353 (car org-stored-links)))))
9355 (defun org-store-link-props (&rest plist)
9356 "Store link properties.
9357 The properties are pre-processed by extracting names, addresses
9358 and dates."
9359 (let ((x (plist-get plist :from)))
9360 (when x
9361 (let ((adr (mail-extract-address-components x)))
9362 (setq plist (plist-put plist :fromname (car adr)))
9363 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9364 (let ((x (plist-get plist :to)))
9365 (when x
9366 (let ((adr (mail-extract-address-components x)))
9367 (setq plist (plist-put plist :toname (car adr)))
9368 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9369 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9370 (when x
9371 (setq plist (plist-put plist :date-timestamp
9372 (format-time-string
9373 (org-time-stamp-format t) x)))
9374 (setq plist (plist-put plist :date-timestamp-inactive
9375 (format-time-string
9376 (org-time-stamp-format t t) x)))))
9377 (let ((from (plist-get plist :from))
9378 (to (plist-get plist :to)))
9379 (when (and from to org-from-is-user-regexp)
9380 (setq plist
9381 (plist-put plist :fromto
9382 (if (string-match org-from-is-user-regexp from)
9383 (concat "to %t")
9384 (concat "from %f"))))))
9385 (setq org-store-link-plist plist))
9387 (defun org-add-link-props (&rest plist)
9388 "Add these properties to the link property list."
9389 (let (key value)
9390 (while plist
9391 (setq key (pop plist) value (pop plist))
9392 (setq org-store-link-plist
9393 (plist-put org-store-link-plist key value)))))
9395 (defun org-email-link-description (&optional fmt)
9396 "Return the description part of an email link.
9397 This takes information from `org-store-link-plist' and formats it
9398 according to FMT (default from `org-email-link-description-format')."
9399 (setq fmt (or fmt org-email-link-description-format))
9400 (let* ((p org-store-link-plist)
9401 (to (plist-get p :toaddress))
9402 (from (plist-get p :fromaddress))
9403 (table
9404 (list
9405 (cons "%c" (plist-get p :fromto))
9406 (cons "%F" (plist-get p :from))
9407 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9408 (cons "%T" (plist-get p :to))
9409 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9410 (cons "%s" (plist-get p :subject))
9411 (cons "%d" (plist-get p :date))
9412 (cons "%m" (plist-get p :message-id)))))
9413 (when (string-match "%c" fmt)
9414 ;; Check if the user wrote this message
9415 (if (and org-from-is-user-regexp from to
9416 (save-match-data (string-match org-from-is-user-regexp from)))
9417 (setq fmt (replace-match "to %t" t t fmt))
9418 (setq fmt (replace-match "from %f" t t fmt))))
9419 (org-replace-escapes fmt table)))
9421 (defun org-make-org-heading-search-string (&optional string)
9422 "Make search string for the current headline or STRING."
9423 (let ((s (or string
9424 (and (derived-mode-p 'org-mode)
9425 (save-excursion
9426 (org-back-to-heading t)
9427 (org-element-property :raw-value (org-element-at-point))))))
9428 (lines org-context-in-file-links))
9429 (unless string (setq s (concat "*" s))) ;Add * for headlines
9430 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9431 (when (and string (integerp lines) (> lines 0))
9432 (let ((slines (org-split-string s "\n")))
9433 (when (< lines (length slines))
9434 (setq s (mapconcat
9435 'identity
9436 (reverse (nthcdr (- (length slines) lines)
9437 (reverse slines))) "\n")))))
9438 (mapconcat #'identity (split-string s) " ")))
9440 (defconst org-link-escape-chars
9441 ;;%20 %5B %5D %25
9442 '(?\s ?\[ ?\] ?%)
9443 "List of characters that should be escaped in a link when stored to Org.
9444 This is the list that is used for internal purposes.")
9446 (defun org-make-link-string (link &optional description)
9447 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9448 (unless (org-string-nw-p link) (error "Empty link"))
9449 (let ((uri (cond ((string-match org-link-types-re link)
9450 (concat (match-string 1 link)
9451 (org-link-escape (substring link (match-end 1)))))
9452 ((or (file-name-absolute-p link)
9453 (string-match-p "\\`\\.\\.?/" link))
9454 (org-link-escape link))
9455 ;; For readability, do not encode space characters
9456 ;; in fuzzy links.
9457 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9458 (description
9459 (and (org-string-nw-p description)
9460 ;; Remove brackets from description, as they are fatal.
9461 (replace-regexp-in-string
9462 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9463 (org-trim description)))))
9464 (format "[[%s]%s]"
9466 (if description (format "[%s]" description) ""))))
9468 (defun org-link-escape (text &optional table merge)
9469 "Return percent escaped representation of TEXT.
9470 TEXT is a string with the text to escape.
9471 Optional argument TABLE is a list with characters that should be
9472 escaped. When nil, `org-link-escape-chars' is used.
9473 If optional argument MERGE is set, merge TABLE into
9474 `org-link-escape-chars'."
9475 (let ((characters-to-encode
9476 (cond ((null table) org-link-escape-chars)
9477 (merge (append org-link-escape-chars table))
9478 (t table))))
9479 (mapconcat
9480 (lambda (c)
9481 (if (or (memq c characters-to-encode)
9482 (and org-url-hexify-p (or (< c 32) (> c 126))))
9483 (mapconcat (lambda (e) (format "%%%.2X" e))
9484 (or (encode-coding-char c 'utf-8)
9485 (error "Unable to percent escape character: %c" c))
9487 (char-to-string c)))
9488 text "")))
9490 (defun org-link-unescape (str)
9491 "Unhex hexified Unicode parts in string STR.
9492 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9493 reciprocal of `org-link-escape', which see."
9494 (if (org-string-nw-p str)
9495 (replace-regexp-in-string
9496 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9497 str))
9499 (defun org-link-unescape-compound (hex)
9500 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9501 Note: this function also decodes single byte encodings like
9502 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9503 (save-match-data
9504 (let* ((bytes (cdr (split-string hex "%")))
9505 (ret "")
9506 (eat 0)
9507 (sum 0))
9508 (while bytes
9509 (let* ((val (string-to-number (pop bytes) 16))
9510 (shift-xor
9511 (if (= 0 eat)
9512 (cond
9513 ((>= val 252) (cons 6 252))
9514 ((>= val 248) (cons 5 248))
9515 ((>= val 240) (cons 4 240))
9516 ((>= val 224) (cons 3 224))
9517 ((>= val 192) (cons 2 192))
9518 (t (cons 0 0)))
9519 (cons 6 128))))
9520 (when (>= val 192) (setq eat (car shift-xor)))
9521 (setq val (logxor val (cdr shift-xor)))
9522 (setq sum (+ (lsh sum (car shift-xor)) val))
9523 (when (> eat 0) (setq eat (- eat 1)))
9524 (cond
9525 ((= 0 eat) ;multi byte
9526 (setq ret (concat ret (char-to-string sum)))
9527 (setq sum 0))
9528 ((not bytes) ; single byte(s)
9529 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9530 ret)))
9532 (defun org-link-unescape-single-byte-sequence (hex)
9533 "Unhexify hex-encoded single byte character sequences."
9534 (mapconcat (lambda (byte)
9535 (char-to-string (string-to-number byte 16)))
9536 (cdr (split-string hex "%")) ""))
9538 (defun org-fixup-message-id-for-http (s)
9539 "Replace special characters in a message id, so it can be used in an http query."
9540 (when (string-match "%" s)
9541 (setq s (mapconcat (lambda (c)
9542 (if (eq c ?%)
9543 "%25"
9544 (char-to-string c)))
9545 s "")))
9546 (while (string-match "<" s)
9547 (setq s (replace-match "%3C" t t s)))
9548 (while (string-match ">" s)
9549 (setq s (replace-match "%3E" t t s)))
9550 (while (string-match "@" s)
9551 (setq s (replace-match "%40" t t s)))
9554 (defun org-link-prettify (link)
9555 "Return a human-readable representation of LINK.
9556 The car of LINK must be a raw link.
9557 The cdr of LINK must be either a link description or nil."
9558 (let ((desc (or (cadr link) "<no description>")))
9559 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9560 "<" (car link) ">")))
9562 ;;;###autoload
9563 (defun org-insert-link-global ()
9564 "Insert a link like Org mode does.
9565 This command can be called in any mode to insert a link in Org syntax."
9566 (interactive)
9567 (org-load-modules-maybe)
9568 (org-run-like-in-org-mode 'org-insert-link))
9570 (defun org-insert-all-links (arg &optional pre post)
9571 "Insert all links in `org-stored-links'.
9572 When a universal prefix, do not delete the links from `org-stored-links'.
9573 When `ARG' is a number, insert the last N link(s).
9574 `PRE' and `POST' are optional arguments to define a string to
9575 prepend or to append."
9576 (interactive "P")
9577 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9578 (links (copy-sequence org-stored-links))
9579 (pr (or pre "- "))
9580 (po (or post "\n"))
9581 (cnt 1) l)
9582 (if (null org-stored-links)
9583 (message "No link to insert")
9584 (while (and (or (listp arg) (>= arg cnt))
9585 (setq l (if (listp arg)
9586 (pop links)
9587 (pop org-stored-links))))
9588 (setq cnt (1+ cnt))
9589 (insert pr)
9590 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9591 (insert po)))))
9593 (defun org-insert-last-stored-link (arg)
9594 "Insert the last link stored in `org-stored-links'."
9595 (interactive "p")
9596 (org-insert-all-links arg "" "\n"))
9598 (defun org-link-fontify-links-to-this-file ()
9599 "Fontify links to the current file in `org-stored-links'."
9600 (let ((f (buffer-file-name)) a b)
9601 (setq a (mapcar (lambda(l)
9602 (let ((ll (car l)))
9603 (when (and (string-match "^file:\\(.+\\)::" ll)
9604 (equal f (expand-file-name (match-string 1 ll))))
9605 ll)))
9606 org-stored-links))
9607 (when (featurep 'org-id)
9608 (setq b (mapcar (lambda(l)
9609 (let ((ll (car l)))
9610 (when (and (string-match "^id:\\(.+\\)$" ll)
9611 (equal f (expand-file-name
9612 (or (org-id-find-id-file
9613 (match-string 1 ll)) ""))))
9614 ll)))
9615 org-stored-links)))
9616 (mapcar (lambda(l)
9617 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9618 (delq nil (append a b)))))
9620 (defvar org--links-history nil)
9621 (defun org-insert-link (&optional complete-file link-location default-description)
9622 "Insert a link. At the prompt, enter the link.
9624 Completion can be used to insert any of the link protocol prefixes in use.
9626 The history can be used to select a link previously stored with
9627 `org-store-link'. When the empty string is entered (i.e. if you just
9628 press `RET' at the prompt), the link defaults to the most recently
9629 stored link. As `SPC' triggers completion in the minibuffer, you need to
9630 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9632 You will also be prompted for a description, and if one is given, it will
9633 be displayed in the buffer instead of the link.
9635 If there is already a link at point, this command will allow you to edit
9636 link and description parts.
9638 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9639 file name can be
9640 selected using completion. The path to the file will be relative to the
9641 current directory if the file is in the current directory or a subdirectory.
9642 Otherwise, the link will be the absolute path as completed in the minibuffer
9643 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9644 option `org-link-file-path-type'.
9646 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9647 absolute path even if the file is in
9648 the current directory or below.
9650 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9651 prefix negates `org-keep-stored-link-after-insertion'.
9653 If the LINK-LOCATION parameter is non-nil, this value will be used as
9654 the link location instead of reading one interactively.
9656 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9657 be used as the default description. Otherwise, if
9658 `org-make-link-description-function' is non-nil, this function
9659 will be called with the link target, and the result will be the
9660 default link description. When called non-interactivily, don't
9661 allow to edit the default description."
9662 (interactive "P")
9663 (let* ((wcf (current-window-configuration))
9664 (origbuf (current-buffer))
9665 (region (when (org-region-active-p)
9666 (buffer-substring (region-beginning) (region-end))))
9667 (remove (and region (list (region-beginning) (region-end))))
9668 (desc region)
9669 (link link-location)
9670 (abbrevs org-link-abbrev-alist-local)
9671 entry all-prefixes auto-desc)
9672 (cond
9673 (link-location) ; specified by arg, just use it.
9674 ((org-in-regexp org-bracket-link-regexp 1)
9675 ;; We do have a link at point, and we are going to edit it.
9676 (setq remove (list (match-beginning 0) (match-end 0)))
9677 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9678 (setq link (read-string "Link: "
9679 (org-link-unescape
9680 (match-string-no-properties 1)))))
9681 ((or (org-in-regexp org-angle-link-re)
9682 (org-in-regexp org-plain-link-re))
9683 ;; Convert to bracket link
9684 (setq remove (list (match-beginning 0) (match-end 0))
9685 link (read-string "Link: "
9686 (org-unbracket-string "<" ">" (match-string 0)))))
9687 ((member complete-file '((4) (16)))
9688 ;; Completing read for file names.
9689 (setq link (org-file-complete-link complete-file)))
9691 ;; Read link, with completion for stored links.
9692 (org-link-fontify-links-to-this-file)
9693 (org-switch-to-buffer-other-window "*Org Links*")
9694 (with-current-buffer "*Org Links*"
9695 (erase-buffer)
9696 (insert "Insert a link.
9697 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9698 (when org-stored-links
9699 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9700 (insert (mapconcat 'org-link-prettify
9701 (reverse org-stored-links) "\n")))
9702 (goto-char (point-min)))
9703 (let ((cw (selected-window)))
9704 (select-window (get-buffer-window "*Org Links*" 'visible))
9705 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9706 (unless (pos-visible-in-window-p (point-max))
9707 (org-fit-window-to-buffer))
9708 (and (window-live-p cw) (select-window cw)))
9709 (setq all-prefixes (append (mapcar 'car abbrevs)
9710 (mapcar 'car org-link-abbrev-alist)
9711 (org-link-types)))
9712 (unwind-protect
9713 ;; Fake a link history, containing the stored links.
9714 (let ((org--links-history
9715 (append (mapcar #'car org-stored-links)
9716 org-insert-link-history)))
9717 (setq link
9718 (org-completing-read
9719 "Link: "
9720 (append
9721 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9722 (mapcar #'car org-stored-links))
9723 nil nil nil
9724 'org--links-history
9725 (caar org-stored-links)))
9726 (unless (org-string-nw-p link) (user-error "No link selected"))
9727 (dolist (l org-stored-links)
9728 (when (equal link (cadr l))
9729 (setq link (car l))
9730 (setq auto-desc t)))
9731 (when (or (member link all-prefixes)
9732 (and (equal ":" (substring link -1))
9733 (member (substring link 0 -1) all-prefixes)
9734 (setq link (substring link 0 -1))))
9735 (setq link (with-current-buffer origbuf
9736 (org-link-try-special-completion link)))))
9737 (set-window-configuration wcf)
9738 (kill-buffer "*Org Links*"))
9739 (setq entry (assoc link org-stored-links))
9740 (or entry (push link org-insert-link-history))
9741 (setq desc (or desc (nth 1 entry)))))
9743 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9744 (not org-keep-stored-link-after-insertion))
9745 (setq org-stored-links (delq (assoc link org-stored-links)
9746 org-stored-links)))
9748 (when (and (string-match org-plain-link-re link)
9749 (not (string-match org-ts-regexp link)))
9750 ;; URL-like link, normalize the use of angular brackets.
9751 (setq link (org-unbracket-string "<" ">" link)))
9753 ;; Check if we are linking to the current file with a search
9754 ;; option If yes, simplify the link by using only the search
9755 ;; option.
9756 (when (and buffer-file-name
9757 (let ((case-fold-search nil))
9758 (string-match "\\`file:\\(.+?\\)::" link)))
9759 (let ((path (match-string-no-properties 1 link))
9760 (search (substring-no-properties link (match-end 0))))
9761 (save-match-data
9762 (when (equal (file-truename buffer-file-name) (file-truename path))
9763 ;; We are linking to this same file, with a search option
9764 (setq link search)))))
9766 ;; Check if we can/should use a relative path. If yes, simplify
9767 ;; the link.
9768 (let ((case-fold-search nil))
9769 (when (string-match "\\`\\(file\\|docview\\):" link)
9770 (let* ((type (match-string-no-properties 0 link))
9771 (path-start (match-end 0))
9772 (search (and (string-match "::\\(.*\\)\\'" link)
9773 (match-string 1 link)))
9774 (path
9775 (if search
9776 (substring-no-properties
9777 link path-start (match-beginning 0))
9778 (substring-no-properties link (match-end 0))))
9779 (origpath path))
9780 (cond
9781 ((or (eq org-link-file-path-type 'absolute)
9782 (equal complete-file '(16)))
9783 (setq path (abbreviate-file-name (expand-file-name path))))
9784 ((eq org-link-file-path-type 'noabbrev)
9785 (setq path (expand-file-name path)))
9786 ((eq org-link-file-path-type 'relative)
9787 (setq path (file-relative-name path)))
9789 (save-match-data
9790 (if (string-match (concat "^" (regexp-quote
9791 (expand-file-name
9792 (file-name-as-directory
9793 default-directory))))
9794 (expand-file-name path))
9795 ;; We are linking a file with relative path name.
9796 (setq path (substring (expand-file-name path)
9797 (match-end 0)))
9798 (setq path (abbreviate-file-name (expand-file-name path)))))))
9799 (setq link (concat type path (and search (concat "::" search))))
9800 (when (equal desc origpath)
9801 (setq desc path)))))
9803 (unless auto-desc
9804 (let ((initial-input
9805 (cond
9806 (default-description)
9807 ((not org-make-link-description-function) desc)
9808 (t (condition-case nil
9809 (funcall org-make-link-description-function link desc)
9810 (error
9811 (message "Can't get link description from `%s'"
9812 (symbol-name org-make-link-description-function))
9813 (sit-for 2)
9814 nil))))))
9815 (setq desc (if (called-interactively-p 'any)
9816 (read-string "Description: " initial-input)
9817 initial-input))))
9819 (unless (string-match "\\S-" desc) (setq desc nil))
9820 (when remove (apply 'delete-region remove))
9821 (insert (org-make-link-string link desc))
9822 ;; Redisplay so as the new link has proper invisible characters.
9823 (sit-for 0)))
9825 (defun org-link-try-special-completion (type)
9826 "If there is completion support for link type TYPE, offer it."
9827 (let ((fun (org-link-get-parameter type :complete)))
9828 (if (functionp fun)
9829 (funcall fun)
9830 (read-string "Link (no completion support): " (concat type ":")))))
9832 (defun org-file-complete-link (&optional arg)
9833 "Create a file link using completion."
9834 (let ((file (read-file-name "File: "))
9835 (pwd (file-name-as-directory (expand-file-name ".")))
9836 (pwd1 (file-name-as-directory (abbreviate-file-name
9837 (expand-file-name ".")))))
9838 (cond ((equal arg '(16))
9839 (concat "file:"
9840 (abbreviate-file-name (expand-file-name file))))
9841 ((string-match
9842 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9843 (concat "file:" (match-string 1 file)))
9844 ((string-match
9845 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9846 (expand-file-name file))
9847 (concat "file:"
9848 (match-string 1 (expand-file-name file))))
9849 (t (concat "file:" file)))))
9852 ;;; Opening/following a link
9854 (defvar org-link-search-failed nil)
9856 (defvar org-open-link-functions nil
9857 "Hook for functions finding a plain text link.
9858 These functions must take a single argument, the link content.
9859 They will be called for links that look like [[link text][description]]
9860 when LINK TEXT does not have a protocol like \"http:\" and does not look
9861 like a filename (e.g. \"./blue.png\").
9863 These functions will be called *before* Org attempts to resolve the
9864 link by doing text searches in the current buffer - so if you want a
9865 link \"[[target]]\" to still find \"<<target>>\", your function should
9866 handle this as a special case.
9868 When the function does handle the link, it must return a non-nil value.
9869 If it decides that it is not responsible for this link, it must return
9870 nil to indicate that that Org can continue with other options like
9871 exact and fuzzy text search.")
9873 (defun org-next-link (&optional search-backward)
9874 "Move forward to the next link.
9875 If the link is in hidden text, expose it."
9876 (interactive "P")
9877 (when (and org-link-search-failed (eq this-command last-command))
9878 (goto-char (point-min))
9879 (message "Link search wrapped back to beginning of buffer"))
9880 (setq org-link-search-failed nil)
9881 (let* ((pos (point))
9882 (ct (org-context))
9883 (a (assq :link ct))
9884 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9885 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9886 ((looking-at org-any-link-re)
9887 ;; Don't stay stuck at link without an org-link face
9888 (forward-char (if search-backward -1 1))))
9889 (if (funcall srch-fun org-any-link-re nil t)
9890 (progn
9891 (goto-char (match-beginning 0))
9892 (when (org-invisible-p) (org-show-context)))
9893 (goto-char pos)
9894 (setq org-link-search-failed t)
9895 (message "No further link found"))))
9897 (defun org-previous-link ()
9898 "Move backward to the previous link.
9899 If the link is in hidden text, expose it."
9900 (interactive)
9901 (funcall 'org-next-link t))
9903 (defun org-translate-link (s)
9904 "Translate a link string if a translation function has been defined."
9905 (with-temp-buffer
9906 (insert (org-trim s))
9907 (org-trim (org-element-interpret-data (org-element-context)))))
9909 (defun org-translate-link-from-planner (type path)
9910 "Translate a link from Emacs Planner syntax so that Org can follow it.
9911 This is still an experimental function, your mileage may vary."
9912 (cond
9913 ((member type '("http" "https" "news" "ftp"))
9914 ;; standard Internet links are the same.
9915 nil)
9916 ((and (equal type "irc") (string-match "^//" path))
9917 ;; Planner has two / at the beginning of an irc link, we have 1.
9918 ;; We should have zero, actually....
9919 (setq path (substring path 1)))
9920 ((and (equal type "lisp") (string-match "^/" path))
9921 ;; Planner has a slash, we do not.
9922 (setq type "elisp" path (substring path 1)))
9923 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9924 ;; A typical message link. Planner has the id after the final slash,
9925 ;; we separate it with a hash mark
9926 (setq path (concat (match-string 1 path) "#"
9927 (org-unbracket-string "<" ">" (match-string 2 path))))))
9928 (cons type path))
9930 (defun org-find-file-at-mouse (ev)
9931 "Open file link or URL at mouse."
9932 (interactive "e")
9933 (mouse-set-point ev)
9934 (org-open-at-point 'in-emacs))
9936 (defun org-open-at-mouse (ev)
9937 "Open file link or URL at mouse.
9938 See the docstring of `org-open-file' for details."
9939 (interactive "e")
9940 (mouse-set-point ev)
9941 (when (eq major-mode 'org-agenda-mode)
9942 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9943 (org-open-at-point))
9945 (defvar org-window-config-before-follow-link nil
9946 "The window configuration before following a link.
9947 This is saved in case the need arises to restore it.")
9949 ;;;###autoload
9950 (defun org-open-at-point-global ()
9951 "Follow a link or time-stamp like Org mode does.
9952 This command can be called in any mode to follow an external link
9953 or a time-stamp that has Org mode syntax. Its behavior is
9954 undefined when called on internal links (e.g., fuzzy links).
9955 Raise an error when there is nothing to follow. "
9956 (interactive)
9957 (cond ((org-in-regexp org-any-link-re)
9958 (org-open-link-from-string (match-string-no-properties 0)))
9959 ((or (org-in-regexp org-ts-regexp-both nil t)
9960 (org-in-regexp org-tsr-regexp-both nil t))
9961 (org-follow-timestamp-link))
9962 (t (user-error "No link found"))))
9964 ;;;###autoload
9965 (defun org-open-link-from-string (s &optional arg reference-buffer)
9966 "Open a link in the string S, as if it was in Org mode."
9967 (interactive "sLink: \nP")
9968 (let ((reference-buffer (or reference-buffer (current-buffer))))
9969 (with-temp-buffer
9970 (let ((org-inhibit-startup (not reference-buffer)))
9971 (org-mode)
9972 (insert s)
9973 (goto-char (point-min))
9974 (when reference-buffer
9975 (setq org-link-abbrev-alist-local
9976 (with-current-buffer reference-buffer
9977 org-link-abbrev-alist-local)))
9978 (org-open-at-point arg reference-buffer)))))
9980 (defvar org-open-at-point-functions nil
9981 "Hook that is run when following a link at point.
9983 Functions in this hook must return t if they identify and follow
9984 a link at point. If they don't find anything interesting at point,
9985 they must return nil.")
9987 (defvar org-link-search-inhibit-query nil)
9988 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9989 (defun org--open-doi-link (path)
9990 "Open a \"doi\" type link.
9991 PATH is a the path to search for, as a string."
9992 (browse-url (url-encode-url (concat org-doi-server-url path))))
9994 (defun org--open-elisp-link (path)
9995 "Open a \"elisp\" type link.
9996 PATH is the sexp to evaluate, as a string."
9997 (let ((cmd path))
9998 (if (or (and (org-string-nw-p
9999 org-confirm-elisp-link-not-regexp)
10000 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10001 (not org-confirm-elisp-link-function)
10002 (funcall org-confirm-elisp-link-function
10003 (format "Execute \"%s\" as elisp? "
10004 (org-add-props cmd nil 'face 'org-warning))))
10005 (message "%s => %s" cmd
10006 (if (eq (string-to-char cmd) ?\()
10007 (eval (read cmd))
10008 (call-interactively (read cmd))))
10009 (user-error "Abort"))))
10011 (defun org--open-help-link (path)
10012 "Open a \"help\" type link.
10013 PATH is a symbol name, as a string."
10014 (pcase (intern path)
10015 ((and (pred fboundp) variable) (describe-function variable))
10016 ((and (pred boundp) function) (describe-variable function))
10017 (name (user-error "Unknown function or variable: %s" name))))
10019 (defun org--open-shell-link (path)
10020 "Open a \"shell\" type link.
10021 PATH is the command to execute, as a string."
10022 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10023 (cmd path))
10024 (if (or (and (org-string-nw-p
10025 org-confirm-shell-link-not-regexp)
10026 (string-match
10027 org-confirm-shell-link-not-regexp cmd))
10028 (not org-confirm-shell-link-function)
10029 (funcall org-confirm-shell-link-function
10030 (format "Execute \"%s\" in shell? "
10031 (org-add-props cmd nil
10032 'face 'org-warning))))
10033 (progn
10034 (message "Executing %s" cmd)
10035 (shell-command cmd buf)
10036 (when (featurep 'midnight)
10037 (setq clean-buffer-list-kill-buffer-names
10038 (cons (buffer-name buf)
10039 clean-buffer-list-kill-buffer-names))))
10040 (user-error "Abort"))))
10042 (defun org-open-at-point (&optional arg reference-buffer)
10043 "Open link, timestamp, footnote or tags at point.
10045 When point is on a link, follow it. Normally, files will be
10046 opened by an appropriate application. If the optional prefix
10047 argument ARG is non-nil, Emacs will visit the file. With
10048 a double prefix argument, try to open outside of Emacs, in the
10049 application the system uses for this file type.
10051 When point is on a timestamp, open the agenda at the day
10052 specified.
10054 When point is a footnote definition, move to the first reference
10055 found. If it is on a reference, move to the associated
10056 definition.
10058 When point is on a headline, display a list of every link in the
10059 entry, so it is possible to pick one, or all, of them. If point
10060 is on a tag, call `org-tags-view' instead.
10062 When optional argument REFERENCE-BUFFER is non-nil, it should
10063 specify a buffer from where the link search should happen. This
10064 is used internally by `org-open-link-from-string'.
10066 On top of syntactically correct links, this function will also
10067 try to open links and time-stamps in comments, example
10068 blocks... i.e., whenever point is on something looking like
10069 a timestamp or a link."
10070 (interactive "P")
10071 ;; On a code block, open block's results.
10072 (unless (call-interactively 'org-babel-open-src-block-result)
10073 (org-load-modules-maybe)
10074 (setq org-window-config-before-follow-link (current-window-configuration))
10075 (org-remove-occur-highlights nil nil t)
10076 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10077 (let* ((context
10078 ;; Only consider supported types, even if they are not
10079 ;; the closest one.
10080 (org-element-lineage
10081 (org-element-context)
10082 '(clock footnote-definition footnote-reference headline
10083 inlinetask link timestamp)
10085 (type (org-element-type context))
10086 (value (org-element-property :value context)))
10087 (cond
10088 ;; On a headline or an inlinetask, but not on a timestamp,
10089 ;; a link, a footnote reference.
10090 ((memq type '(headline inlinetask))
10091 (org-match-line org-complex-heading-regexp)
10092 (if (and (match-beginning 5)
10093 (>= (point) (match-beginning 5))
10094 (< (point) (match-end 5)))
10095 ;; On tags.
10096 (org-tags-view arg (substring (match-string 5) 0 -1))
10097 ;; Not on tags.
10098 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10099 (`(nil . ,_)
10100 (require 'org-attach)
10101 (org-attach-reveal 'if-exists))
10102 (`(,links . ,links-end)
10103 (dolist (link (if (stringp links) (list links) links))
10104 (search-forward link nil links-end)
10105 (goto-char (match-beginning 0))
10106 (org-open-at-point))))))
10107 ;; On a footnote reference or at definition's label.
10108 ((or (eq type 'footnote-reference)
10109 (and (eq type 'footnote-definition)
10110 (save-excursion
10111 ;; Do not validate action when point is on the
10112 ;; spaces right after the footnote label, in
10113 ;; order to be on par with behaviour on links.
10114 (skip-chars-forward " \t")
10115 (let ((begin
10116 (org-element-property :contents-begin context)))
10117 (if begin (< (point) begin)
10118 (= (org-element-property :post-affiliated context)
10119 (line-beginning-position)))))))
10120 (org-footnote-action))
10121 ;; No valid context. Ignore catch-all types like `headline'.
10122 ;; If point is on something looking like a link or
10123 ;; a time-stamp, try opening it. It may be useful in
10124 ;; comments, example blocks...
10125 ((memq type '(footnote-definition headline inlinetask nil))
10126 (call-interactively #'org-open-at-point-global))
10127 ;; On a clock line, make sure point is on the timestamp
10128 ;; before opening it.
10129 ((and (eq type 'clock)
10130 value
10131 (>= (point) (org-element-property :begin value))
10132 (<= (point) (org-element-property :end value)))
10133 (org-follow-timestamp-link))
10134 ;; Do nothing on white spaces after an object.
10135 ((>= (point)
10136 (save-excursion
10137 (goto-char (org-element-property :end context))
10138 (skip-chars-backward " \t")
10139 (point)))
10140 (user-error "No link found"))
10141 ((eq type 'timestamp) (org-follow-timestamp-link))
10142 ((eq type 'link)
10143 (let ((type (org-element-property :type context))
10144 (path (org-link-unescape (org-element-property :path context))))
10145 ;; Switch back to REFERENCE-BUFFER needed when called in
10146 ;; a temporary buffer through `org-open-link-from-string'.
10147 (with-current-buffer (or reference-buffer (current-buffer))
10148 (cond
10149 ((equal type "file")
10150 (if (string-match "[*?{]" (file-name-nondirectory path))
10151 (dired path)
10152 ;; Look into `org-link-parameters' in order to find
10153 ;; a DEDICATED-FUNCTION to open file. The function
10154 ;; will be applied on raw link instead of parsed
10155 ;; link due to the limitation in `org-add-link-type'
10156 ;; ("open" function called with a single argument).
10157 ;; If no such function is found, fallback to
10158 ;; `org-open-file'.
10159 (let* ((option (org-element-property :search-option context))
10160 (app (org-element-property :application context))
10161 (dedicated-function
10162 (org-link-get-parameter
10163 (if app (concat type "+" app) type)
10164 :follow)))
10165 (if dedicated-function
10166 (funcall dedicated-function
10167 (concat path
10168 (and option (concat "::" option))))
10169 (apply #'org-open-file
10170 path
10171 (cond (arg)
10172 ((equal app "emacs") 'emacs)
10173 ((equal app "sys") 'system))
10174 (cond ((not option) nil)
10175 ((string-match-p "\\`[0-9]+\\'" option)
10176 (list (string-to-number option)))
10177 (t (list nil
10178 (org-link-unescape option)))))))))
10179 ((functionp (org-link-get-parameter type :follow))
10180 (funcall (org-link-get-parameter type :follow) path))
10181 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10182 (unless (run-hook-with-args-until-success
10183 'org-open-link-functions path)
10184 (if (not arg) (org-mark-ring-push)
10185 (switch-to-buffer-other-window
10186 (org-get-buffer-for-internal-link (current-buffer))))
10187 (let ((destination
10188 (org-with-wide-buffer
10189 (if (equal type "radio")
10190 (org-search-radio-target
10191 (org-element-property :path context))
10192 (org-link-search
10193 (if (member type '("custom-id" "coderef"))
10194 (org-element-property :raw-link context)
10195 path)
10196 ;; Prevent fuzzy links from matching
10197 ;; themselves.
10198 (and (equal type "fuzzy")
10199 (+ 2 (org-element-property :begin context)))))
10200 (point))))
10201 (unless (and (<= (point-min) destination)
10202 (>= (point-max) destination))
10203 (widen))
10204 (goto-char destination))))
10205 (t (browse-url-at-point))))))
10206 (t (user-error "No link found")))))
10207 (run-hook-with-args 'org-follow-link-hook)))
10209 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10210 "Offer links in the current entry and return the selected link.
10211 If there is only one link, return it.
10212 If NTH is an integer, return the NTH link found.
10213 If ZERO is a string, check also this string for a link, and if
10214 there is one, return it."
10215 (with-current-buffer buffer
10216 (org-with-wide-buffer
10217 (goto-char marker)
10218 (let ((cnt ?0)
10219 have-zero end links link c)
10220 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10221 (push (match-string 0 zero) links)
10222 (setq cnt (1- cnt) have-zero t))
10223 (save-excursion
10224 (org-back-to-heading t)
10225 (setq end (save-excursion (outline-next-heading) (point)))
10226 (while (re-search-forward org-any-link-re end t)
10227 (push (match-string 0) links))
10228 (setq links (org-uniquify (reverse links))))
10229 (cond
10230 ((null links)
10231 (message "No links"))
10232 ((equal (length links) 1)
10233 (setq link (car links)))
10234 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10235 (setq link (nth (if have-zero nth (1- nth)) links)))
10236 (t ; we have to select a link
10237 (save-excursion
10238 (save-window-excursion
10239 (delete-other-windows)
10240 (with-output-to-temp-buffer "*Select Link*"
10241 (dolist (l links)
10242 (cond
10243 ((not (string-match org-bracket-link-regexp l))
10244 (princ (format "[%c] %s\n" (cl-incf cnt)
10245 (org-unbracket-string "<" ">" l))))
10246 ((match-end 3)
10247 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10248 (match-string 3 l) (match-string 1 l))))
10249 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10250 (match-string 1 l)))))))
10251 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10252 (message "Select link to open, RET to open all:")
10253 (setq c (read-char-exclusive))
10254 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10255 (when (equal c ?q) (user-error "Abort"))
10256 (if (equal c ?\C-m)
10257 (setq link links)
10258 (setq nth (- c ?0))
10259 (when have-zero (setq nth (1+ nth)))
10260 (unless (and (integerp nth) (>= (length links) nth))
10261 (user-error "Invalid link selection"))
10262 (setq link (nth (1- nth) links)))))
10263 (cons link end)))))
10265 ;; TODO: These functions are deprecated since `org-open-at-point'
10266 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10267 (defun org-open-file-with-system (path)
10268 "Open file at PATH using the system way of opening it."
10269 (org-open-file path 'system))
10270 (defun org-open-file-with-emacs (path)
10271 "Open file at PATH in Emacs."
10272 (org-open-file path 'emacs))
10275 ;;; File search
10277 (defvar org-create-file-search-functions nil
10278 "List of functions to construct the right search string for a file link.
10279 These functions are called in turn with point at the location to
10280 which the link should point.
10282 A function in the hook should first test if it would like to
10283 handle this file type, for example by checking the `major-mode'
10284 or the file extension. If it decides not to handle this file, it
10285 should just return nil to give other functions a chance. If it
10286 does handle the file, it must return the search string to be used
10287 when following the link. The search string will be part of the
10288 file link, given after a double colon, and `org-open-at-point'
10289 will automatically search for it. If special measures must be
10290 taken to make the search successful, another function should be
10291 added to the companion hook `org-execute-file-search-functions',
10292 which see.
10294 A function in this hook may also use `setq' to set the variable
10295 `description' to provide a suggestion for the descriptive text to
10296 be used for this link when it gets inserted into an Org buffer
10297 with \\[org-insert-link].")
10299 (defvar org-execute-file-search-functions nil
10300 "List of functions to execute a file search triggered by a link.
10302 Functions added to this hook must accept a single argument, the
10303 search string that was part of the file link, the part after the
10304 double colon. The function must first check if it would like to
10305 handle this search, for example by checking the `major-mode' or
10306 the file extension. If it decides not to handle this search, it
10307 should just return nil to give other functions a chance. If it
10308 does handle the search, it must return a non-nil value to keep
10309 other functions from trying.
10311 Each function can access the current prefix argument through the
10312 variable `current-prefix-arg'. Note that a single prefix is used
10313 to force opening a link in Emacs, so it may be good to only use a
10314 numeric or double prefix to guide the search function.
10316 In case this is needed, a function in this hook can also restore
10317 the window configuration before `org-open-at-point' was called using:
10319 (set-window-configuration org-window-config-before-follow-link)")
10321 (defun org-search-radio-target (target)
10322 "Search a radio target matching TARGET in current buffer.
10323 White spaces are not significant."
10324 (let ((re (format "<<<%s>>>"
10325 (mapconcat #'regexp-quote
10326 (split-string target)
10327 "[ \t]+\\(?:\n[ \t]*\\)?")))
10328 (origin (point)))
10329 (goto-char (point-min))
10330 (catch :radio-match
10331 (while (re-search-forward re nil t)
10332 (backward-char)
10333 (let ((object (org-element-context)))
10334 (when (eq (org-element-type object) 'radio-target)
10335 (goto-char (org-element-property :begin object))
10336 (org-show-context 'link-search)
10337 (throw :radio-match nil))))
10338 (goto-char origin)
10339 (user-error "No match for radio target: %s" target))))
10341 (defun org-link-search (s &optional avoid-pos stealth)
10342 "Search for a search string S.
10344 If S starts with \"#\", it triggers a custom ID search.
10346 If S is enclosed within parenthesis, it initiates a coderef
10347 search.
10349 If S is surrounded by forward slashes, it is interpreted as
10350 a regular expression. In Org mode files, this will create an
10351 `org-occur' sparse tree. In ordinary files, `occur' will be used
10352 to list matches. If the current buffer is in `dired-mode', grep
10353 will be used to search in all files.
10355 When AVOID-POS is given, ignore matches near that position.
10357 When optional argument STEALTH is non-nil, do not modify
10358 visibility around point, thus ignoring `org-show-context-detail'
10359 variable.
10361 Search is case-insensitive and ignores white spaces. Return type
10362 of matched result, which is either `dedicated' or `fuzzy'."
10363 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10364 (let* ((case-fold-search t)
10365 (origin (point))
10366 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10367 (starred (eq (string-to-char normalized) ?*))
10368 (words (split-string (if starred (substring s 1) s)))
10369 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10370 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10371 type)
10372 (cond
10373 ;; Check if there are any special search functions.
10374 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10375 ((eq (string-to-char s) ?#)
10376 ;; Look for a custom ID S if S starts with "#".
10377 (let* ((id (substring normalized 1))
10378 (match (org-find-property "CUSTOM_ID" id)))
10379 (if match (progn (goto-char match) (setf type 'dedicated))
10380 (error "No match for custom ID: %s" id))))
10381 ((string-match "\\`(\\(.*\\))\\'" normalized)
10382 ;; Look for coderef targets if S is enclosed within parenthesis.
10383 (let ((coderef (match-string-no-properties 1 normalized))
10384 (re (substring s-single-re 1 -1)))
10385 (goto-char (point-min))
10386 (catch :coderef-match
10387 (while (re-search-forward re nil t)
10388 (let ((element (org-element-at-point)))
10389 (when (and (memq (org-element-type element)
10390 '(example-block src-block))
10391 ;; Build proper regexp according to current
10392 ;; block's label format.
10393 (let ((label-fmt
10394 (regexp-quote
10395 (or (org-element-property :label-fmt element)
10396 org-coderef-label-format))))
10397 (save-excursion
10398 (beginning-of-line)
10399 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10400 (format label-fmt coderef))))))
10401 (setq type 'dedicated)
10402 (goto-char (match-beginning 1))
10403 (throw :coderef-match nil))))
10404 (goto-char origin)
10405 (error "No match for coderef: %s" coderef))))
10406 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10407 ;; Look for a regular expression.
10408 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10409 (match-string 1 s)))
10410 ;; From here, we handle fuzzy links.
10412 ;; Look for targets, only if not in a headline search.
10413 ((and (not starred)
10414 (let ((target (format "<<%s>>" s-multi-re)))
10415 (catch :target-match
10416 (goto-char (point-min))
10417 (while (re-search-forward target nil t)
10418 (backward-char)
10419 (let ((context (org-element-context)))
10420 (when (eq (org-element-type context) 'target)
10421 (setq type 'dedicated)
10422 (goto-char (org-element-property :begin context))
10423 (throw :target-match t))))
10424 nil))))
10425 ;; Look for elements named after S, only if not in a headline
10426 ;; search.
10427 ((and (not starred)
10428 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10429 (catch :name-match
10430 (goto-char (point-min))
10431 (while (re-search-forward name nil t)
10432 (let ((element (org-element-at-point)))
10433 (when (equal words
10434 (split-string
10435 (org-element-property :name element)))
10436 (setq type 'dedicated)
10437 (beginning-of-line)
10438 (throw :name-match t))))
10439 nil))))
10440 ;; Regular text search. Prefer headlines in Org mode buffers.
10441 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10442 ;; statistics cookies and tags.
10443 ((and (derived-mode-p 'org-mode)
10444 (let ((title-re
10445 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10446 org-outline-regexp-bol
10447 org-comment-string
10448 (mapconcat #'regexp-quote words ".+")))
10449 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10450 (comment-re (eval-when-compile
10451 (format "\\`%s[ \t]+" org-comment-string))))
10452 (goto-char (point-min))
10453 (catch :found
10454 (while (re-search-forward title-re nil t)
10455 (when (equal words
10456 (split-string
10457 (replace-regexp-in-string
10458 cookie-re ""
10459 (replace-regexp-in-string
10460 comment-re "" (org-get-heading t t t)))))
10461 (throw :found t)))
10462 nil)))
10463 (beginning-of-line)
10464 (setq type 'dedicated))
10465 ;; Offer to create non-existent headline depending on
10466 ;; `org-link-search-must-match-exact-headline'.
10467 ((and (derived-mode-p 'org-mode)
10468 (not org-link-search-inhibit-query)
10469 (eq org-link-search-must-match-exact-headline 'query-to-create)
10470 (yes-or-no-p "No match - create this as a new heading? "))
10471 (goto-char (point-max))
10472 (unless (bolp) (newline))
10473 (org-insert-heading nil t t)
10474 (insert s "\n")
10475 (beginning-of-line 0))
10476 ;; Only headlines are looked after. No need to process
10477 ;; further: throw an error.
10478 ((and (derived-mode-p 'org-mode)
10479 (or starred org-link-search-must-match-exact-headline))
10480 (goto-char origin)
10481 (error "No match for fuzzy expression: %s" normalized))
10482 ;; Regular text search.
10483 ((catch :fuzzy-match
10484 (goto-char (point-min))
10485 (while (re-search-forward s-multi-re nil t)
10486 ;; Skip match if it contains AVOID-POS or it is included in
10487 ;; a link with a description but outside the description.
10488 (unless (or (and avoid-pos
10489 (<= (match-beginning 0) avoid-pos)
10490 (> (match-end 0) avoid-pos))
10491 (and (save-match-data
10492 (org-in-regexp org-bracket-link-regexp))
10493 (match-beginning 3)
10494 (or (> (match-beginning 3) (point))
10495 (<= (match-end 3) (point)))
10496 (org-element-lineage
10497 (save-match-data (org-element-context))
10498 '(link) t)))
10499 (goto-char (match-beginning 0))
10500 (setq type 'fuzzy)
10501 (throw :fuzzy-match t)))
10502 nil))
10503 ;; All failed. Throw an error.
10504 (t (goto-char origin)
10505 (error "No match for fuzzy expression: %s" normalized)))
10506 ;; Disclose surroundings of match, if appropriate.
10507 (when (and (derived-mode-p 'org-mode) (not stealth))
10508 (org-show-context 'link-search))
10509 type))
10511 (defun org-get-buffer-for-internal-link (buffer)
10512 "Return a buffer to be used for displaying the link target of internal links."
10513 (cond
10514 ((not org-display-internal-link-with-indirect-buffer)
10515 buffer)
10516 ((string-suffix-p "(Clone)" (buffer-name buffer))
10517 (message "Buffer is already a clone, not making another one")
10518 ;; we also do not modify visibility in this case
10519 buffer)
10520 (t ; make a new indirect buffer for displaying the link
10521 (let* ((bn (buffer-name buffer))
10522 (ibn (concat bn "(Clone)"))
10523 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10524 (with-current-buffer ib (org-overview))
10525 ib))))
10527 (defun org-do-occur (regexp &optional cleanup)
10528 "Call the Emacs command `occur'.
10529 If CLEANUP is non-nil, remove the printout of the regular expression
10530 in the *Occur* buffer. This is useful if the regex is long and not useful
10531 to read."
10532 (occur regexp)
10533 (when cleanup
10534 (let ((cwin (selected-window)) win beg end)
10535 (when (setq win (get-buffer-window "*Occur*"))
10536 (select-window win))
10537 (goto-char (point-min))
10538 (when (re-search-forward "match[a-z]+" nil t)
10539 (setq beg (match-end 0))
10540 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10541 (setq end (1- (match-beginning 0)))))
10542 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10543 (goto-char (point-min))
10544 (select-window cwin))))
10546 ;;; The mark ring for links jumps
10548 (defvar org-mark-ring nil
10549 "Mark ring for positions before jumps in Org mode.")
10550 (defvar org-mark-ring-last-goto nil
10551 "Last position in the mark ring used to go back.")
10552 ;; Fill and close the ring
10553 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10554 (dotimes (_ org-mark-ring-length)
10555 (push (make-marker) org-mark-ring))
10556 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10557 org-mark-ring)
10559 (defun org-mark-ring-push (&optional pos buffer)
10560 "Put the current position or POS into the mark ring and rotate it."
10561 (interactive)
10562 (setq pos (or pos (point)))
10563 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10564 (move-marker (car org-mark-ring)
10565 (or pos (point))
10566 (or buffer (current-buffer)))
10567 (message "%s"
10568 (substitute-command-keys
10569 "Position saved to mark ring, go back with \
10570 `\\[org-mark-ring-goto]'.")))
10572 (defun org-mark-ring-goto (&optional n)
10573 "Jump to the previous position in the mark ring.
10574 With prefix arg N, jump back that many stored positions. When
10575 called several times in succession, walk through the entire ring.
10576 Org mode commands jumping to a different position in the current file,
10577 or to another Org file, automatically push the old position onto the ring."
10578 (interactive "p")
10579 (let (p m)
10580 (if (eq last-command this-command)
10581 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10582 (setq p org-mark-ring))
10583 (setq org-mark-ring-last-goto p)
10584 (setq m (car p))
10585 (pop-to-buffer-same-window (marker-buffer m))
10586 (goto-char m)
10587 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10589 (defun org-add-angle-brackets (s)
10590 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10591 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10594 ;;; Following specific links
10596 (defvar org-agenda-buffer-tmp-name)
10597 (defvar org-agenda-start-on-weekday)
10598 (defun org-follow-timestamp-link ()
10599 "Open an agenda view for the time-stamp date/range at point."
10600 (cond
10601 ((org-at-date-range-p t)
10602 (let ((org-agenda-start-on-weekday)
10603 (t1 (match-string 1))
10604 (t2 (match-string 2)) tt1 tt2)
10605 (setq tt1 (time-to-days (org-time-string-to-time t1))
10606 tt2 (time-to-days (org-time-string-to-time t2)))
10607 (let ((org-agenda-buffer-tmp-name
10608 (format "*Org Agenda(a:%s)"
10609 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10610 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10611 ((org-at-timestamp-p 'lax)
10612 (let ((org-agenda-buffer-tmp-name
10613 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10614 (org-agenda-list nil (time-to-days (org-time-string-to-time
10615 (substring (match-string 1) 0 10)))
10616 1)))
10617 (t (error "This should not happen"))))
10620 ;;; Following file links
10621 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10622 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10623 (declare-function mailcap-mime-info
10624 "mailcap" (string &optional request no-decode))
10625 (defvar org-wait nil)
10626 (defun org-open-file (path &optional in-emacs line search)
10627 "Open the file at PATH.
10628 First, this expands any special file name abbreviations. Then the
10629 configuration variable `org-file-apps' is checked if it contains an
10630 entry for this file type, and if yes, the corresponding command is launched.
10632 If no application is found, Emacs simply visits the file.
10634 With optional prefix argument IN-EMACS, Emacs will visit the file.
10635 With a double \\[universal-argument] \\[universal-argument] \
10636 prefix arg, Org tries to avoid opening in Emacs
10637 and to use an external application to visit the file.
10639 Optional LINE specifies a line to go to, optional SEARCH a string
10640 to search for. If LINE or SEARCH is given, the file will be
10641 opened in Emacs, unless an entry from org-file-apps that makes
10642 use of groups in a regexp matches.
10644 If you want to change the way frames are used when following a
10645 link, please customize `org-link-frame-setup'.
10647 If the file does not exist, an error is thrown."
10648 (let* ((file (if (equal path "")
10649 buffer-file-name
10650 (substitute-in-file-name (expand-file-name path))))
10651 (file-apps (append org-file-apps (org-default-apps)))
10652 (apps (cl-remove-if
10653 'org-file-apps-entry-match-against-dlink-p file-apps))
10654 (apps-dlink (cl-remove-if-not
10655 'org-file-apps-entry-match-against-dlink-p file-apps))
10656 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10657 (dirp (unless remp (file-directory-p file)))
10658 (file (if (and dirp org-open-directory-means-index-dot-org)
10659 (concat (file-name-as-directory file) "index.org")
10660 file))
10661 (a-m-a-p (assq 'auto-mode apps))
10662 (dfile (downcase file))
10663 ;; Reconstruct the original link from the PATH, LINE and
10664 ;; SEARCH args.
10665 (link (cond (line (concat file "::" (number-to-string line)))
10666 (search (concat file "::" search))
10667 (t file)))
10668 (dlink (downcase link))
10669 (ext
10670 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10671 (match-string 1 dfile)))
10672 (save-position-maybe
10673 (let ((old-buffer (current-buffer))
10674 (old-pos (point))
10675 (old-mode major-mode))
10676 (lambda ()
10677 (and (derived-mode-p 'org-mode)
10678 (eq old-mode 'org-mode)
10679 (or (not (eq old-buffer (current-buffer)))
10680 (not (eq old-pos (point))))
10681 (org-mark-ring-push old-pos old-buffer)))))
10682 cmd link-match-data)
10683 (cond
10684 ((member in-emacs '((16) system))
10685 (setq cmd (cdr (assq 'system apps))))
10686 (in-emacs (setq cmd 'emacs))
10688 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10689 (and dirp (cdr (assq 'directory apps)))
10690 ;; First, try matching against apps-dlink if we
10691 ;; get a match here, store the match data for
10692 ;; later.
10693 (let ((match (assoc-default dlink apps-dlink
10694 'string-match)))
10695 (if match
10696 (progn (setq link-match-data (match-data))
10697 match)
10698 (progn (setq in-emacs (or in-emacs line search))
10699 nil))) ; if we have no match in apps-dlink,
10700 ; always open the file in emacs if line or search
10701 ; is given (for backwards compatibility)
10702 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10703 'string-match)
10704 (cdr (assoc ext apps))
10705 (cdr (assq t apps))))))
10706 (when (eq cmd 'system)
10707 (setq cmd (cdr (assq 'system apps))))
10708 (when (eq cmd 'default)
10709 (setq cmd (cdr (assoc t apps))))
10710 (when (eq cmd 'mailcap)
10711 (require 'mailcap)
10712 (mailcap-parse-mailcaps)
10713 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10714 (command (mailcap-mime-info mime-type)))
10715 (if (stringp command)
10716 (setq cmd command)
10717 (setq cmd 'emacs))))
10718 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10719 (not (file-exists-p file))
10720 (not org-open-non-existing-files))
10721 (user-error "No such file: %s" file))
10722 (cond
10723 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10724 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10725 (while (string-match "['\"]%s['\"]" cmd)
10726 (setq cmd (replace-match "%s" t t cmd)))
10727 (setq cmd (replace-regexp-in-string
10728 "%s"
10729 (shell-quote-argument (convert-standard-filename file))
10731 nil t))
10733 ;; Replace "%1", "%2" etc. in command with group matches from regex
10734 (save-match-data
10735 (let ((match-index 1)
10736 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10737 (set-match-data link-match-data)
10738 (while (<= match-index number-of-groups)
10739 (let ((regex (concat "%" (number-to-string match-index)))
10740 (replace-with (match-string match-index dlink)))
10741 (while (string-match regex cmd)
10742 (setq cmd (replace-match replace-with t t cmd))))
10743 (setq match-index (+ match-index 1)))))
10745 (save-window-excursion
10746 (message "Running %s...done" cmd)
10747 (start-process-shell-command cmd nil cmd)
10748 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10749 ((or (stringp cmd)
10750 (eq cmd 'emacs))
10751 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10752 (widen)
10753 (cond (line (org-goto-line line)
10754 (when (derived-mode-p 'org-mode) (org-reveal)))
10755 (search (condition-case err
10756 (org-link-search search)
10757 ;; Save position before error-ing out so user
10758 ;; can easily move back to the original buffer.
10759 (error (funcall save-position-maybe)
10760 (error (nth 1 err)))))))
10761 ((functionp cmd)
10762 (save-match-data
10763 (set-match-data link-match-data)
10764 (condition-case nil
10765 (funcall cmd file link)
10766 ;; FIXME: Remove this check when most default installations
10767 ;; of Emacs have at least Org 9.0.
10768 ((debug wrong-number-of-arguments wrong-type-argument
10769 invalid-function)
10770 (user-error "Please see Org News for version 9.0 about \
10771 `org-file-apps'--Lisp error: %S" cmd)))))
10772 ((consp cmd)
10773 ;; FIXME: Remove this check when most default installations of
10774 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10775 ;; fall back to `org-link-frame-setup' for an old usage of
10776 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10777 (user-error "Please see Org News for version 9.0 about \
10778 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10779 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10780 (funcall save-position-maybe)))
10782 (defun org-file-apps-entry-match-against-dlink-p (entry)
10783 "This function returns non-nil if `entry' uses a regular
10784 expression which should be matched against the whole link by
10785 org-open-file.
10787 It assumes that is the case when the entry uses a regular
10788 expression which has at least one grouping construct and the
10789 action is either a lisp form or a command string containing
10790 `%1', i.e. using at least one subexpression match as a
10791 parameter."
10792 (let ((selector (car entry))
10793 (action (cdr entry)))
10794 (if (stringp selector)
10795 (and (> (regexp-opt-depth selector) 0)
10796 (or (and (stringp action)
10797 (string-match "%[0-9]" action))
10798 (consp action)))
10799 nil)))
10801 (defun org-default-apps ()
10802 "Return the default applications for this operating system."
10803 (cond
10804 ((eq system-type 'darwin)
10805 org-file-apps-defaults-macosx)
10806 ((eq system-type 'windows-nt)
10807 org-file-apps-defaults-windowsnt)
10808 (t org-file-apps-defaults-gnu)))
10810 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10811 "Convert extensions to regular expressions in the cars of LIST.
10812 Also, weed out any non-string entries, because the return value is used
10813 only for regexp matching.
10814 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10815 point to the symbol `emacs', indicating that the file should
10816 be opened in Emacs."
10817 (append
10818 (delq nil
10819 (mapcar (lambda (x)
10820 (unless (not (stringp (car x)))
10821 (if (string-match "\\W" (car x))
10823 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10824 list))
10825 (when add-auto-mode
10826 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10828 (defvar ange-ftp-name-format)
10829 (defun org-file-remote-p (file)
10830 "Test whether FILE specifies a location on a remote system.
10831 Return non-nil if the location is indeed remote.
10833 For example, the filename \"/user@host:/foo\" specifies a location
10834 on the system \"/user@host:\"."
10835 (cond ((fboundp 'file-remote-p)
10836 (file-remote-p file))
10837 ((fboundp 'tramp-handle-file-remote-p)
10838 (tramp-handle-file-remote-p file))
10839 ((and (boundp 'ange-ftp-name-format)
10840 (string-match (car ange-ftp-name-format) file))
10841 t)))
10844 ;;;; Refiling
10846 (defun org-get-org-file ()
10847 "Read a filename, with default directory `org-directory'."
10848 (let ((default (or org-default-notes-file remember-data-file)))
10849 (read-file-name (format "File name [%s]: " default)
10850 (file-name-as-directory org-directory)
10851 default)))
10853 (defun org-notes-order-reversed-p ()
10854 "Check if the current file should receive notes in reversed order."
10855 (cond
10856 ((not org-reverse-note-order) nil)
10857 ((eq t org-reverse-note-order) t)
10858 ((not (listp org-reverse-note-order)) nil)
10859 (t (catch 'exit
10860 (dolist (entry org-reverse-note-order)
10861 (when (string-match (car entry) buffer-file-name)
10862 (throw 'exit (cdr entry))))))))
10864 (defvar org-refile-target-table nil
10865 "The list of refile targets, created by `org-refile'.")
10867 (defvar org-agenda-new-buffers nil
10868 "Buffers created to visit agenda files.")
10870 (defvar org-refile-cache nil
10871 "Cache for refile targets.")
10873 (defvar org-refile-markers nil
10874 "All the markers used for caching refile locations.")
10876 (defun org-refile-marker (pos)
10877 "Get a new refile marker, but only if caching is in use."
10878 (if (not org-refile-use-cache)
10880 (let ((m (make-marker)))
10881 (move-marker m pos)
10882 (push m org-refile-markers)
10883 m)))
10885 (defun org-refile-cache-clear ()
10886 "Clear the refile cache and disable all the markers."
10887 (dolist (m org-refile-markers) (move-marker m nil))
10888 (setq org-refile-markers nil)
10889 (setq org-refile-cache nil)
10890 (message "Refile cache has been cleared"))
10892 (defun org-refile-cache-check-set (set)
10893 "Check if all the markers in the cache still have live buffers."
10894 (let (marker)
10895 (catch 'exit
10896 (while (and set (setq marker (nth 3 (pop set))))
10897 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10898 (when (and marker (null (marker-buffer marker)))
10899 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10900 (sit-for 3)
10901 (throw 'exit nil)))
10902 t)))
10904 (defun org-refile-cache-put (set &rest identifiers)
10905 "Push the refile targets SET into the cache, under IDENTIFIERS."
10906 (let* ((key (sha1 (prin1-to-string identifiers)))
10907 (entry (assoc key org-refile-cache)))
10908 (if entry
10909 (setcdr entry set)
10910 (push (cons key set) org-refile-cache))))
10912 (defun org-refile-cache-get (&rest identifiers)
10913 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10914 (cond
10915 ((not org-refile-cache) nil)
10916 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10918 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10919 org-refile-cache))))
10920 (and set (org-refile-cache-check-set set) set)))))
10922 (defvar org-outline-path-cache nil
10923 "Alist between buffer positions and outline paths.
10924 It value is an alist (POSITION . PATH) where POSITION is the
10925 buffer position at the beginning of an entry and PATH is a list
10926 of strings describing the outline path for that entry, in reverse
10927 order.")
10929 (defun org-refile-get-targets (&optional default-buffer)
10930 "Produce a table with refile targets."
10931 (let ((case-fold-search nil)
10932 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10933 (entries (or org-refile-targets '((nil . (:level . 1)))))
10934 targets tgs files desc descre)
10935 (message "Getting targets...")
10936 (with-current-buffer (or default-buffer (current-buffer))
10937 (dolist (entry entries)
10938 (setq files (car entry) desc (cdr entry))
10939 (cond
10940 ((null files) (setq files (list (current-buffer))))
10941 ((eq files 'org-agenda-files)
10942 (setq files (org-agenda-files 'unrestricted)))
10943 ((and (symbolp files) (fboundp files))
10944 (setq files (funcall files)))
10945 ((and (symbolp files) (boundp files))
10946 (setq files (symbol-value files))))
10947 (when (stringp files) (setq files (list files)))
10948 (cond
10949 ((eq (car desc) :tag)
10950 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10951 ((eq (car desc) :todo)
10952 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10953 ((eq (car desc) :regexp)
10954 (setq descre (cdr desc)))
10955 ((eq (car desc) :level)
10956 (setq descre (concat "^\\*\\{" (number-to-string
10957 (if org-odd-levels-only
10958 (1- (* 2 (cdr desc)))
10959 (cdr desc)))
10960 "\\}[ \t]")))
10961 ((eq (car desc) :maxlevel)
10962 (setq descre (concat "^\\*\\{1," (number-to-string
10963 (if org-odd-levels-only
10964 (1- (* 2 (cdr desc)))
10965 (cdr desc)))
10966 "\\}[ \t]")))
10967 (t (error "Bad refiling target description %s" desc)))
10968 (dolist (f files)
10969 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10971 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10972 (progn
10973 (when (bufferp f)
10974 (setq f (buffer-file-name (buffer-base-buffer f))))
10975 (setq f (and f (expand-file-name f)))
10976 (when (eq org-refile-use-outline-path 'file)
10977 (push (list (file-name-nondirectory f) f nil nil) tgs))
10978 (when (eq org-refile-use-outline-path 'buffer-name)
10979 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10980 (when (eq org-refile-use-outline-path 'full-file-path)
10981 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10982 (org-with-wide-buffer
10983 (goto-char (point-min))
10984 (setq org-outline-path-cache nil)
10985 (while (re-search-forward descre nil t)
10986 (beginning-of-line)
10987 (let ((case-fold-search nil))
10988 (looking-at org-complex-heading-regexp))
10989 (let ((begin (point))
10990 (heading (match-string-no-properties 4)))
10991 (unless (or (and
10992 org-refile-target-verify-function
10993 (not
10994 (funcall org-refile-target-verify-function)))
10995 (not heading))
10996 (let ((re (format org-complex-heading-regexp-format
10997 (regexp-quote heading)))
10998 (target
10999 (if (not org-refile-use-outline-path) heading
11000 (mapconcat
11001 #'identity
11002 (append
11003 (pcase org-refile-use-outline-path
11004 (`file (list (file-name-nondirectory
11005 (buffer-file-name
11006 (buffer-base-buffer)))))
11007 (`full-file-path
11008 (list (buffer-file-name
11009 (buffer-base-buffer))))
11010 (`buffer-name
11011 (list (buffer-name
11012 (buffer-base-buffer))))
11013 (_ nil))
11014 (mapcar (lambda (s) (replace-regexp-in-string
11015 "/" "\\/" s nil t))
11016 (org-get-outline-path t t)))
11017 "/"))))
11018 (push (list target f re (org-refile-marker (point)))
11019 tgs)))
11020 (when (= (point) begin)
11021 ;; Verification function has not moved point.
11022 (end-of-line)))))))
11023 (when org-refile-use-cache
11024 (org-refile-cache-put tgs (buffer-file-name) descre))
11025 (setq targets (append tgs targets))))))
11026 (message "Getting targets...done")
11027 (delete-dups (nreverse targets))))
11029 (defun org--get-outline-path-1 (&optional use-cache)
11030 "Return outline path to current headline.
11032 Outline path is a list of strings, in reverse order. When
11033 optional argument USE-CACHE is non-nil, make use of a cache. See
11034 `org-get-outline-path' for details.
11036 Assume buffer is widened and point is on a headline."
11037 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11038 (let ((p (point))
11039 (heading (let ((case-fold-search nil))
11040 (looking-at org-complex-heading-regexp)
11041 (if (not (match-end 4)) ""
11042 ;; Remove statistics cookies.
11043 (org-trim
11044 (org-link-display-format
11045 (replace-regexp-in-string
11046 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11047 (match-string-no-properties 4))))))))
11048 (if (org-up-heading-safe)
11049 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11050 (when use-cache
11051 (push (cons p path) org-outline-path-cache))
11052 path)
11053 ;; This is a new root node. Since we assume we are moving
11054 ;; forward, we can drop previous cache so as to limit number
11055 ;; of associations there.
11056 (let ((path (list heading)))
11057 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11058 path)))))
11060 (defun org-get-outline-path (&optional with-self use-cache)
11061 "Return the outline path to the current entry.
11063 An outline path is a list of ancestors for current headline, as
11064 a list of strings. Statistics cookies are removed and links are
11065 replaced with their description, if any, or their path otherwise.
11067 When optional argument WITH-SELF is non-nil, the path also
11068 includes the current headline.
11070 When optional argument USE-CACHE is non-nil, cache outline paths
11071 between calls to this function so as to avoid backtracking. This
11072 argument is useful when planning to find more than one outline
11073 path in the same document. In that case, there are two
11074 conditions to satisfy:
11075 - `org-outline-path-cache' is set to nil before starting the
11076 process;
11077 - outline paths are computed by increasing buffer positions."
11078 (org-with-wide-buffer
11079 (and (or (and with-self (org-back-to-heading t))
11080 (org-up-heading-safe))
11081 (reverse (org--get-outline-path-1 use-cache)))))
11083 (defun org-format-outline-path (path &optional width prefix separator)
11084 "Format the outline path PATH for display.
11085 WIDTH is the maximum number of characters that is available.
11086 PREFIX is a prefix to be included in the returned string,
11087 such as the file name.
11088 SEPARATOR is inserted between the different parts of the path,
11089 the default is \"/\"."
11090 (setq width (or width 79))
11091 (setq path (delq nil path))
11092 (unless (> width 0)
11093 (user-error "Argument `width' must be positive"))
11094 (setq separator (or separator "/"))
11095 (let* ((org-odd-levels-only nil)
11096 (fpath (concat
11097 prefix (and prefix path separator)
11098 (mapconcat
11099 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11100 (cl-loop for head in path
11101 for n from 0
11102 collect (org-add-props
11103 head nil 'face
11104 (nth (% n org-n-level-faces) org-level-faces)))
11105 separator))))
11106 (when (> (length fpath) width)
11107 (if (< width 7)
11108 ;; It's unlikely that `width' will be this small, but don't
11109 ;; waste characters by adding ".." if it is.
11110 (setq fpath (substring fpath 0 width))
11111 (setf (substring fpath (- width 2)) "..")))
11112 fpath))
11114 (defun org-display-outline-path (&optional file current separator just-return-string)
11115 "Display the current outline path in the echo area.
11117 If FILE is non-nil, prepend the output with the file name.
11118 If CURRENT is non-nil, append the current heading to the output.
11119 SEPARATOR is passed through to `org-format-outline-path'. It separates
11120 the different parts of the path and defaults to \"/\".
11121 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11122 (interactive "P")
11123 (let* (case-fold-search
11124 (bfn (buffer-file-name (buffer-base-buffer)))
11125 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11126 res)
11127 (when current (setq path (append path
11128 (save-excursion
11129 (org-back-to-heading t)
11130 (when (looking-at org-complex-heading-regexp)
11131 (list (match-string 4)))))))
11132 (setq res
11133 (org-format-outline-path
11134 path
11135 (1- (frame-width))
11136 (and file bfn (concat (file-name-nondirectory bfn) separator))
11137 separator))
11138 (if just-return-string
11139 (org-no-properties res)
11140 (org-unlogged-message "%s" res))))
11142 (defvar org-refile-history nil
11143 "History for refiling operations.")
11145 (defvar org-after-refile-insert-hook nil
11146 "Hook run after `org-refile' has inserted its stuff at the new location.
11147 Note that this is still *before* the stuff will be removed from
11148 the *old* location.")
11150 (defvar org-capture-last-stored-marker)
11151 (defvar org-refile-keep nil
11152 "Non-nil means `org-refile' will copy instead of refile.")
11154 (defun org-copy ()
11155 "Like `org-refile', but copy."
11156 (interactive)
11157 (let ((org-refile-keep t))
11158 (funcall 'org-refile nil nil nil "Copy")))
11160 (defun org-refile (&optional arg default-buffer rfloc msg)
11161 "Move the entry or entries at point to another heading.
11163 The list of target headings is compiled using the information in
11164 `org-refile-targets', which see.
11166 At the target location, the entry is filed as a subitem of the
11167 target heading. Depending on `org-reverse-note-order', the new
11168 subitem will either be the first or the last subitem.
11170 If there is an active region, all entries in that region will be
11171 refiled. However, the region must fulfill the requirement that
11172 the first heading sets the top-level of the moved text.
11174 With a `\\[universal-argument]' ARG, the command will only visit the target \
11175 location
11176 and not actually move anything.
11178 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11179 location where the last
11180 refiling operation has put the subtree.
11182 With a numeric prefix argument of `2', refile to the running clock.
11184 With a numeric prefix argument of `3', emulate `org-refile-keep'
11185 being set to t and copy to the target location, don't move it.
11186 Beware that keeping refiled entries may result in duplicated ID
11187 properties.
11189 RFLOC can be a refile location obtained in a different way.
11191 MSG is a string to replace \"Refile\" in the default prompt with
11192 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11194 See also `org-refile-use-outline-path'.
11196 If you are using target caching (see `org-refile-use-cache'), you
11197 have to clear the target cache in order to find new targets.
11198 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11199 prefix argument (`C-u C-u C-u C-c C-w')."
11200 (interactive "P")
11201 (if (member arg '(0 (64)))
11202 (org-refile-cache-clear)
11203 (let* ((actionmsg (cond (msg msg)
11204 ((equal arg 3) "Refile (and keep)")
11205 (t "Refile")))
11206 (regionp (org-region-active-p))
11207 (region-start (and regionp (region-beginning)))
11208 (region-end (and regionp (region-end)))
11209 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11210 pos it nbuf file level reversed)
11211 (setq last-command nil)
11212 (when regionp
11213 (goto-char region-start)
11214 (or (bolp) (goto-char (point-at-bol)))
11215 (setq region-start (point))
11216 (unless (or (org-kill-is-subtree-p
11217 (buffer-substring region-start region-end))
11218 (prog1 org-refile-active-region-within-subtree
11219 (let ((s (point-at-eol)))
11220 (org-toggle-heading)
11221 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11222 (user-error "The region is not a (sequence of) subtree(s)")))
11223 (if (equal arg '(16))
11224 (org-refile-goto-last-stored)
11225 (when (or
11226 (and (equal arg 2)
11227 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11228 (prog1
11229 (setq it (list (or org-clock-heading "running clock")
11230 (buffer-file-name
11231 (marker-buffer org-clock-hd-marker))
11233 (marker-position org-clock-hd-marker)))
11234 (setq arg nil)))
11235 (setq it
11236 (or rfloc
11237 (let (heading-text)
11238 (save-excursion
11239 (unless (and arg (listp arg))
11240 (org-back-to-heading t)
11241 (setq heading-text
11242 (replace-regexp-in-string
11243 org-bracket-link-regexp
11244 "\\3"
11245 (or (nth 4 (org-heading-components))
11246 ""))))
11247 (org-refile-get-location
11248 (cond ((and arg (listp arg)) "Goto")
11249 (regionp (concat actionmsg " region to"))
11250 (t (concat actionmsg " subtree \""
11251 heading-text "\" to")))
11252 default-buffer
11253 (and (not (equal '(4) arg))
11254 org-refile-allow-creating-parent-nodes)))))))
11255 (setq file (nth 1 it)
11256 pos (nth 3 it))
11257 (when (and (not arg)
11259 (equal (buffer-file-name) file)
11260 (if regionp
11261 (and (>= pos region-start)
11262 (<= pos region-end))
11263 (and (>= pos (point))
11264 (< pos (save-excursion
11265 (org-end-of-subtree t t))))))
11266 (error "Cannot refile to position inside the tree or region"))
11267 (setq nbuf (or (find-buffer-visiting file)
11268 (find-file-noselect file)))
11269 (if (and arg (not (equal arg 3)))
11270 (progn
11271 (pop-to-buffer-same-window nbuf)
11272 (goto-char (cond (pos)
11273 ((org-notes-order-reversed-p) (point-min))
11274 (t (point-max))))
11275 (org-show-context 'org-goto))
11276 (if regionp
11277 (progn
11278 (org-kill-new (buffer-substring region-start region-end))
11279 (org-save-markers-in-region region-start region-end))
11280 (org-copy-subtree 1 nil t))
11281 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11282 (find-file-noselect file)))
11283 (setq reversed (org-notes-order-reversed-p))
11284 (org-with-wide-buffer
11285 (if pos
11286 (progn
11287 (goto-char pos)
11288 (setq level (org-get-valid-level (funcall outline-level) 1))
11289 (goto-char
11290 (if reversed
11291 (or (outline-next-heading) (point-max))
11292 (or (save-excursion (org-get-next-sibling))
11293 (org-end-of-subtree t t)
11294 (point-max)))))
11295 (setq level 1)
11296 (if (not reversed)
11297 (goto-char (point-max))
11298 (goto-char (point-min))
11299 (or (outline-next-heading) (goto-char (point-max)))))
11300 (unless (bolp) (newline))
11301 (org-paste-subtree level nil nil t)
11302 (when org-log-refile
11303 (org-add-log-setup 'refile nil nil org-log-refile)
11304 (unless (eq org-log-refile 'note)
11305 (save-excursion (org-add-log-note))))
11306 (and org-auto-align-tags
11307 (let ((org-loop-over-headlines-in-active-region nil))
11308 (org-set-tags nil t)))
11309 (let ((bookmark-name (plist-get org-bookmark-names-plist
11310 :last-refile)))
11311 (when bookmark-name
11312 (with-demoted-errors
11313 (bookmark-set bookmark-name))))
11314 ;; If we are refiling for capture, make sure that the
11315 ;; last-capture pointers point here
11316 (when (bound-and-true-p org-capture-is-refiling)
11317 (let ((bookmark-name (plist-get org-bookmark-names-plist
11318 :last-capture-marker)))
11319 (when bookmark-name
11320 (with-demoted-errors
11321 (bookmark-set bookmark-name))))
11322 (move-marker org-capture-last-stored-marker (point)))
11323 (when (fboundp 'deactivate-mark) (deactivate-mark))
11324 (run-hooks 'org-after-refile-insert-hook)))
11325 (unless org-refile-keep
11326 (if regionp
11327 (delete-region (point) (+ (point) (- region-end region-start)))
11328 (org-preserve-local-variables
11329 (delete-region
11330 (and (org-back-to-heading t) (point))
11331 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11332 (when (featurep 'org-inlinetask)
11333 (org-inlinetask-remove-END-maybe))
11334 (setq org-markers-to-move nil)
11335 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11337 (defun org-refile-goto-last-stored ()
11338 "Go to the location where the last refile was stored."
11339 (interactive)
11340 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11341 (message "This is the location of the last refile"))
11343 (defun org-refile--get-location (refloc tbl)
11344 "When user refile to REFLOC, find the associated target in TBL.
11345 Also check `org-refile-target-table'."
11346 (car (delq
11348 (mapcar
11349 (lambda (r) (or (assoc r tbl)
11350 (assoc r org-refile-target-table)))
11351 (list (replace-regexp-in-string "/$" "" refloc)
11352 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11354 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11355 "Prompt the user for a refile location, using PROMPT.
11356 PROMPT should not be suffixed with a colon and a space, because
11357 this function appends the default value from
11358 `org-refile-history' automatically, if that is not empty."
11359 (let ((org-refile-targets org-refile-targets)
11360 (org-refile-use-outline-path org-refile-use-outline-path))
11361 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11362 (unless org-refile-target-table
11363 (user-error "No refile targets"))
11364 (let* ((cbuf (current-buffer))
11365 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11366 (cfunc (if (and org-refile-use-outline-path
11367 org-outline-path-complete-in-steps)
11368 #'org-olpath-completing-read
11369 #'completing-read))
11370 (extra (if org-refile-use-outline-path "/" ""))
11371 (cbnex (concat (buffer-name) extra))
11372 (filename (and cfn (expand-file-name cfn)))
11373 (tbl (mapcar
11374 (lambda (x)
11375 (if (and (not (member org-refile-use-outline-path
11376 '(file full-file-path)))
11377 (not (equal filename (nth 1 x))))
11378 (cons (concat (car x) extra " ("
11379 (file-name-nondirectory (nth 1 x)) ")")
11380 (cdr x))
11381 (cons (concat (car x) extra) (cdr x))))
11382 org-refile-target-table))
11383 (completion-ignore-case t)
11384 cdef
11385 (prompt (concat prompt
11386 (or (and (car org-refile-history)
11387 (concat " (default " (car org-refile-history) ")"))
11388 (and (assoc cbnex tbl) (setq cdef cbnex)
11389 (concat " (default " cbnex ")"))) ": "))
11390 pa answ parent-target child parent old-hist)
11391 (setq old-hist org-refile-history)
11392 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11393 nil 'org-refile-history (or cdef (car org-refile-history))))
11394 (if (setq pa (org-refile--get-location answ tbl))
11395 (progn
11396 (org-refile-check-position pa)
11397 (when (or (not org-refile-history)
11398 (not (eq old-hist org-refile-history))
11399 (not (equal (car pa) (car org-refile-history))))
11400 (setq org-refile-history
11401 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11402 org-refile-history
11403 (cdr org-refile-history))))
11404 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11405 (pop org-refile-history)))
11407 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11408 (progn
11409 (setq parent (match-string 1 answ)
11410 child (match-string 2 answ))
11411 (setq parent-target (org-refile--get-location parent tbl))
11412 (when (and parent-target
11413 (or (eq new-nodes t)
11414 (and (eq new-nodes 'confirm)
11415 (y-or-n-p (format "Create new node \"%s\"? "
11416 child)))))
11417 (org-refile-new-child parent-target child)))
11418 (user-error "Invalid target location")))))
11420 (declare-function org-string-nw-p "org-macs" (s))
11421 (defun org-refile-check-position (refile-pointer)
11422 "Check if the refile pointer matches the headline to which it points."
11423 (let* ((file (nth 1 refile-pointer))
11424 (re (nth 2 refile-pointer))
11425 (pos (nth 3 refile-pointer))
11426 buffer)
11427 (if (and (not (markerp pos)) (not file))
11428 (user-error "Please indicate a target file in the refile path")
11429 (when (org-string-nw-p re)
11430 (setq buffer (if (markerp pos)
11431 (marker-buffer pos)
11432 (or (find-buffer-visiting file)
11433 (find-file-noselect file))))
11434 (with-current-buffer buffer
11435 (org-with-wide-buffer
11436 (goto-char pos)
11437 (beginning-of-line 1)
11438 (unless (looking-at-p re)
11439 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11441 (defun org-refile-new-child (parent-target child)
11442 "Use refile target PARENT-TARGET to add new CHILD below it."
11443 (unless parent-target
11444 (error "Cannot find parent for new node"))
11445 (let ((file (nth 1 parent-target))
11446 (pos (nth 3 parent-target))
11447 level)
11448 (with-current-buffer (or (find-buffer-visiting file)
11449 (find-file-noselect file))
11450 (org-with-wide-buffer
11451 (if pos
11452 (goto-char pos)
11453 (goto-char (point-max))
11454 (unless (bolp) (newline)))
11455 (when (looking-at org-outline-regexp)
11456 (setq level (funcall outline-level))
11457 (org-end-of-subtree t t))
11458 (org-back-over-empty-lines)
11459 (insert "\n" (make-string
11460 (if pos (org-get-valid-level level 1) 1) ?*)
11461 " " child "\n")
11462 (beginning-of-line 0)
11463 (list (concat (car parent-target) "/" child) file "" (point))))))
11465 (defun org-olpath-completing-read (prompt collection &rest args)
11466 "Read an outline path like a file name."
11467 (let ((thetable collection))
11468 (apply #'completing-read
11469 prompt
11470 (lambda (string predicate &optional flag)
11471 (cond
11472 ((eq flag nil) (try-completion string thetable))
11473 ((eq flag t)
11474 (let ((l (length string)))
11475 (mapcar (lambda (x)
11476 (let ((r (substring x l))
11477 (f (if (string-match " ([^)]*)$" x)
11478 (match-string 0 x)
11479 "")))
11480 (if (string-match "/" r)
11481 (concat string (substring r 0 (match-end 0)) f)
11482 x)))
11483 (all-completions string thetable predicate))))
11484 ;; Exact match?
11485 ((eq flag 'lambda) (assoc string thetable))))
11486 args)))
11488 ;;;; Dynamic blocks
11490 (defun org-find-dblock (name)
11491 "Find the first dynamic block with name NAME in the buffer.
11492 If not found, stay at current position and return nil."
11493 (let ((case-fold-search t) pos)
11494 (save-excursion
11495 (goto-char (point-min))
11496 (setq pos (and (re-search-forward
11497 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11498 (match-beginning 0))))
11499 (when pos (goto-char pos))
11500 pos))
11502 (defun org-create-dblock (plist)
11503 "Create a dynamic block section, with parameters taken from PLIST.
11504 PLIST must contain a :name entry which is used as the name of the block."
11505 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11506 (end-of-line 1)
11507 (newline))
11508 (let ((col (current-column))
11509 (name (plist-get plist :name)))
11510 (insert "#+BEGIN: " name)
11511 (while plist
11512 (if (eq (car plist) :name)
11513 (setq plist (cddr plist))
11514 (insert " " (prin1-to-string (pop plist)))))
11515 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11516 (beginning-of-line -2)))
11518 (defun org-prepare-dblock ()
11519 "Prepare dynamic block for refresh.
11520 This empties the block, puts the cursor at the insert position and returns
11521 the property list including an extra property :name with the block name."
11522 (unless (looking-at org-dblock-start-re)
11523 (user-error "Not at a dynamic block"))
11524 (let* ((begdel (1+ (match-end 0)))
11525 (name (org-no-properties (match-string 1)))
11526 (params (append (list :name name)
11527 (read (concat "(" (match-string 3) ")")))))
11528 (save-excursion
11529 (beginning-of-line 1)
11530 (skip-chars-forward " \t")
11531 (setq params (plist-put params :indentation-column (current-column))))
11532 (unless (re-search-forward org-dblock-end-re nil t)
11533 (error "Dynamic block not terminated"))
11534 (setq params
11535 (append params
11536 (list :content (buffer-substring
11537 begdel (match-beginning 0)))))
11538 (delete-region begdel (match-beginning 0))
11539 (goto-char begdel)
11540 (open-line 1)
11541 params))
11543 (defun org-map-dblocks (&optional command)
11544 "Apply COMMAND to all dynamic blocks in the current buffer.
11545 If COMMAND is not given, use `org-update-dblock'."
11546 (let ((cmd (or command 'org-update-dblock)))
11547 (save-excursion
11548 (goto-char (point-min))
11549 (while (re-search-forward org-dblock-start-re nil t)
11550 (goto-char (match-beginning 0))
11551 (save-excursion
11552 (condition-case nil
11553 (funcall cmd)
11554 (error (message "Error during update of dynamic block"))))
11555 (unless (re-search-forward org-dblock-end-re nil t)
11556 (error "Dynamic block not terminated"))))))
11558 (defun org-dblock-update (&optional arg)
11559 "User command for updating dynamic blocks.
11560 Update the dynamic block at point. With prefix ARG, update all dynamic
11561 blocks in the buffer."
11562 (interactive "P")
11563 (if arg
11564 (org-update-all-dblocks)
11565 (or (looking-at org-dblock-start-re)
11566 (org-beginning-of-dblock))
11567 (org-update-dblock)))
11569 (defun org-update-dblock ()
11570 "Update the dynamic block at point.
11571 This means to empty the block, parse for parameters and then call
11572 the correct writing function."
11573 (interactive)
11574 (save-excursion
11575 (let* ((win (selected-window))
11576 (pos (point))
11577 (line (org-current-line))
11578 (params (org-prepare-dblock))
11579 (name (plist-get params :name))
11580 (indent (plist-get params :indentation-column))
11581 (cmd (intern (concat "org-dblock-write:" name))))
11582 (message "Updating dynamic block `%s' at line %d..." name line)
11583 (funcall cmd params)
11584 (message "Updating dynamic block `%s' at line %d...done" name line)
11585 (goto-char pos)
11586 (when (and indent (> indent 0))
11587 (setq indent (make-string indent ?\ ))
11588 (save-excursion
11589 (select-window win)
11590 (org-beginning-of-dblock)
11591 (forward-line 1)
11592 (while (not (looking-at org-dblock-end-re))
11593 (insert indent)
11594 (beginning-of-line 2))
11595 (when (looking-at org-dblock-end-re)
11596 (and (looking-at "[ \t]+")
11597 (replace-match ""))
11598 (insert indent)))))))
11600 (defun org-beginning-of-dblock ()
11601 "Find the beginning of the dynamic block at point.
11602 Error if there is no such block at point."
11603 (let ((pos (point))
11604 beg)
11605 (end-of-line 1)
11606 (if (and (re-search-backward org-dblock-start-re nil t)
11607 (setq beg (match-beginning 0))
11608 (re-search-forward org-dblock-end-re nil t)
11609 (> (match-end 0) pos))
11610 (goto-char beg)
11611 (goto-char pos)
11612 (error "Not in a dynamic block"))))
11614 (defun org-update-all-dblocks ()
11615 "Update all dynamic blocks in the buffer.
11616 This function can be used in a hook."
11617 (interactive)
11618 (when (derived-mode-p 'org-mode)
11619 (org-map-dblocks 'org-update-dblock)))
11622 ;;;; Completion
11624 (declare-function org-export-backend-options "ox" (cl-x) t)
11625 (defun org-get-export-keywords ()
11626 "Return a list of all currently understood export keywords.
11627 Export keywords include options, block names, attributes and
11628 keywords relative to each registered export back-end."
11629 (let (keywords)
11630 (dolist (backend
11631 (bound-and-true-p org-export-registered-backends)
11632 (delq nil keywords))
11633 ;; Back-end name (for keywords, like #+LATEX:)
11634 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11635 (dolist (option-entry (org-export-backend-options backend))
11636 ;; Back-end options.
11637 (push (nth 1 option-entry) keywords)))))
11639 (defconst org-options-keywords
11640 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11641 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11642 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11643 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11644 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11646 (defcustom org-structure-template-alist
11647 '((?a . "export ascii")
11648 (?c . "center")
11649 (?C . "comment")
11650 (?e . "example")
11651 (?E . "export")
11652 (?h . "export html")
11653 (?l . "export latex")
11654 (?q . "quote")
11655 (?s . "src")
11656 (?v . "verse"))
11657 "Structure completion elements.
11658 This is an alist of characters and values. When
11659 `org-insert-structure-template' is called, an additional key is
11660 read. The key is first looked up in this alist, and the
11661 corresponding structure is inserted, with \"#+BEGIN_\" and
11662 \"#+END_\" added automatically."
11663 :group 'org-edit-structure
11664 :type '(repeat
11665 (cons (character :tag "Key")
11666 (string :tag "Template")))
11667 :package-version '(Org . "9.2"))
11669 (defun org-insert-structure-template (type)
11670 "Insert a block structure of the type #+begin_foo/#+end_foo.
11671 First read a character, which can be one of the keys in
11672 `org-structure-template-alist'. When it is <TAB>, prompt the
11673 user for a string to use. With an active region, wrap the region
11674 in the block. Otherwise, insert an empty block."
11675 (interactive
11676 (list
11677 (let* ((key (read-key "Key: "))
11678 (struct-string
11679 (or (cdr (assq key org-structure-template-alist))
11680 (and (= key ?\t)
11681 (read-string "Structure type: "))
11682 (user-error "`%c' has no structure definition" key))))
11683 struct-string)))
11684 (let* ((region? (use-region-p))
11685 (s (if region? (region-beginning) (point)))
11686 (e (copy-marker (if region? (region-end) (point)) t))
11687 column)
11688 (when (string-match-p
11689 (concat "\\`" (regexp-opt '("example" "export" "src")))
11690 type)
11691 (org-escape-code-in-region s e))
11692 (goto-char s)
11693 (setq column (current-indentation))
11694 (beginning-of-line)
11695 (indent-to column)
11696 (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
11697 (goto-char e)
11698 (if (bolp)
11699 (progn
11700 (skip-chars-backward " \n\t")
11701 (forward-line))
11702 (end-of-line)
11703 (insert "\n"))
11704 (indent-to column)
11705 (insert (format "#+end_%s\n"
11706 (car (split-string type))))
11707 (when (or (not region?)
11708 (string-match-p "src\\|\\`export\\'" type))
11709 (goto-char s)
11710 (end-of-line))
11711 (set-marker e nil)))
11713 ;;;; TODO, DEADLINE, Comments
11715 (defun org-toggle-comment ()
11716 "Change the COMMENT state of an entry."
11717 (interactive)
11718 (save-excursion
11719 (org-back-to-heading)
11720 (let ((case-fold-search nil))
11721 (looking-at org-complex-heading-regexp))
11722 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11723 (skip-chars-forward " \t")
11724 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11725 (if (org-in-commented-heading-p t)
11726 (delete-region (point)
11727 (progn (search-forward " " (line-end-position) 'move)
11728 (skip-chars-forward " \t")
11729 (point)))
11730 (insert org-comment-string)
11731 (unless (eolp) (insert " ")))))
11733 (defvar org-last-todo-state-is-todo nil
11734 "This is non-nil when the last TODO state change led to a TODO state.
11735 If the last change removed the TODO tag or switched to DONE, then
11736 this is nil.")
11738 (defvar org-setting-tags nil) ; dynamically skipped
11740 (defvar org-todo-setup-filter-hook nil
11741 "Hook for functions that pre-filter todo specs.
11742 Each function takes a todo spec and returns either nil or the spec
11743 transformed into canonical form." )
11745 (defvar org-todo-get-default-hook nil
11746 "Hook for functions that get a default item for todo.
11747 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11748 nil or a string to be used for the todo mark." )
11750 (defvar org-agenda-headline-snapshot-before-repeat)
11752 (defun org-current-effective-time ()
11753 "Return current time adjusted for `org-extend-today-until' variable."
11754 (let* ((ct (org-current-time))
11755 (dct (decode-time ct))
11756 (ct1
11757 (cond
11758 (org-use-last-clock-out-time-as-effective-time
11759 (or (org-clock-get-last-clock-out-time) ct))
11760 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11761 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11762 (t ct))))
11763 ct1))
11765 (defun org-todo-yesterday (&optional arg)
11766 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11767 (interactive "P")
11768 (if (eq major-mode 'org-agenda-mode)
11769 (apply 'org-agenda-todo-yesterday arg)
11770 (let* ((org-use-effective-time t)
11771 (hour (nth 2 (decode-time (org-current-time))))
11772 (org-extend-today-until (1+ hour)))
11773 (org-todo arg))))
11775 (defvar org-block-entry-blocking ""
11776 "First entry preventing the TODO state change.")
11778 (defun org-cancel-repeater ()
11779 "Cancel a repeater by setting its numeric value to zero."
11780 (interactive)
11781 (save-excursion
11782 (org-back-to-heading t)
11783 (let ((bound1 (point))
11784 (bound0 (save-excursion (outline-next-heading) (point))))
11785 (when (and (re-search-forward
11786 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11787 org-deadline-time-regexp "\\)\\|\\("
11788 org-ts-regexp "\\)")
11789 bound0 t)
11790 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11791 bound1 t))
11792 (replace-match "0" t nil nil 1)))))
11794 (defvar org-state)
11795 (defvar org-blocked-by-checkboxes)
11796 (defun org-todo (&optional arg)
11797 "Change the TODO state of an item.
11799 The state of an item is given by a keyword at the start of the heading,
11800 like
11801 *** TODO Write paper
11802 *** DONE Call mom
11804 The different keywords are specified in the variable `org-todo-keywords'.
11805 By default the available states are \"TODO\" and \"DONE\". So, for this
11806 example: when the item starts with TODO, it is changed to DONE.
11807 When it starts with DONE, the DONE is removed. And when neither TODO nor
11808 DONE are present, add TODO at the beginning of the heading.
11810 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11811 state.
11812 With numeric prefix ARG, switch to that state.
11813 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11814 next set of TODO \
11815 keywords (nextset).
11816 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11817 prefix, circumvent any state blocking.
11818 With a numeric prefix arg of 0, inhibit note taking for the change.
11819 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11821 When called through ELisp, arg is also interpreted in the following way:
11822 `none' -> empty state
11823 \"\" -> switch to empty state
11824 `done' -> switch to DONE
11825 `nextset' -> switch to the next set of keywords
11826 `previousset' -> switch to the previous set of keywords
11827 \"WAITING\" -> switch to the specified keyword, but only if it
11828 really is a member of `org-todo-keywords'."
11829 (interactive "P")
11830 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11831 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11832 'region-start-level 'region))
11833 org-loop-over-headlines-in-active-region)
11834 (org-map-entries
11835 `(org-todo ,arg)
11836 org-loop-over-headlines-in-active-region
11837 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11838 (when (equal arg '(16)) (setq arg 'nextset))
11839 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11840 (let ((org-blocker-hook org-blocker-hook)
11841 commentp
11842 case-fold-search)
11843 (when (equal arg '(64))
11844 (setq arg nil org-blocker-hook nil))
11845 (when (and org-blocker-hook
11846 (or org-inhibit-blocking
11847 (org-entry-get nil "NOBLOCKING")))
11848 (setq org-blocker-hook nil))
11849 (save-excursion
11850 (catch 'exit
11851 (org-back-to-heading t)
11852 (when (org-in-commented-heading-p t)
11853 (org-toggle-comment)
11854 (setq commentp t))
11855 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11856 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11857 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11858 (let* ((match-data (match-data))
11859 (startpos (copy-marker (line-beginning-position)))
11860 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11861 (org-log-done org-log-done)
11862 (org-log-repeat org-log-repeat)
11863 (org-todo-log-states org-todo-log-states)
11864 (org-inhibit-logging
11865 (if (equal arg 0)
11866 (progn (setq arg nil) 'note) org-inhibit-logging))
11867 (this (match-string 1))
11868 (hl-pos (match-beginning 0))
11869 (head (org-get-todo-sequence-head this))
11870 (ass (assoc head org-todo-kwd-alist))
11871 (interpret (nth 1 ass))
11872 (done-word (nth 3 ass))
11873 (final-done-word (nth 4 ass))
11874 (org-last-state (or this ""))
11875 (completion-ignore-case t)
11876 (member (member this org-todo-keywords-1))
11877 (tail (cdr member))
11878 (org-state (cond
11879 ((and org-todo-key-trigger
11880 (or (and (equal arg '(4))
11881 (eq org-use-fast-todo-selection 'prefix))
11882 (and (not arg) org-use-fast-todo-selection
11883 (not (eq org-use-fast-todo-selection
11884 'prefix)))))
11885 ;; Use fast selection.
11886 (org-fast-todo-selection))
11887 ((and (equal arg '(4))
11888 (or (not org-use-fast-todo-selection)
11889 (not org-todo-key-trigger)))
11890 ;; Read a state with completion.
11891 (completing-read
11892 "State: " (mapcar #'list org-todo-keywords-1)
11893 nil t))
11894 ((eq arg 'right)
11895 (if this
11896 (if tail (car tail) nil)
11897 (car org-todo-keywords-1)))
11898 ((eq arg 'left)
11899 (unless (equal member org-todo-keywords-1)
11900 (if this
11901 (nth (- (length org-todo-keywords-1)
11902 (length tail) 2)
11903 org-todo-keywords-1)
11904 (org-last org-todo-keywords-1))))
11905 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11906 (setq arg nil))) ;hack to fall back to cycling
11907 (arg
11908 ;; User or caller requests a specific state.
11909 (cond
11910 ((equal arg "") nil)
11911 ((eq arg 'none) nil)
11912 ((eq arg 'done) (or done-word (car org-done-keywords)))
11913 ((eq arg 'nextset)
11914 (or (car (cdr (member head org-todo-heads)))
11915 (car org-todo-heads)))
11916 ((eq arg 'previousset)
11917 (let ((org-todo-heads (reverse org-todo-heads)))
11918 (or (car (cdr (member head org-todo-heads)))
11919 (car org-todo-heads))))
11920 ((car (member arg org-todo-keywords-1)))
11921 ((stringp arg)
11922 (user-error "State `%s' not valid in this file" arg))
11923 ((nth (1- (prefix-numeric-value arg))
11924 org-todo-keywords-1))))
11925 ((null member) (or head (car org-todo-keywords-1)))
11926 ((equal this final-done-word) nil) ;-> make empty
11927 ((null tail) nil) ;-> first entry
11928 ((memq interpret '(type priority))
11929 (if (eq this-command last-command)
11930 (car tail)
11931 (if (> (length tail) 0)
11932 (or done-word (car org-done-keywords))
11933 nil)))
11935 (car tail))))
11936 (org-state (or
11937 (run-hook-with-args-until-success
11938 'org-todo-get-default-hook org-state org-last-state)
11939 org-state))
11940 (next (if org-state (concat " " org-state " ") " "))
11941 (change-plist (list :type 'todo-state-change :from this :to org-state
11942 :position startpos))
11943 dolog now-done-p)
11944 (when org-blocker-hook
11945 (let (org-blocked-by-checkboxes block-reason)
11946 (setq org-last-todo-state-is-todo
11947 (not (member this org-done-keywords)))
11948 (unless (save-excursion
11949 (save-match-data
11950 (org-with-wide-buffer
11951 (run-hook-with-args-until-failure
11952 'org-blocker-hook change-plist))))
11953 (setq block-reason (if org-blocked-by-checkboxes
11954 "contained checkboxes"
11955 (format "\"%s\"" org-block-entry-blocking)))
11956 (if (called-interactively-p 'interactive)
11957 (user-error "TODO state change from %s to %s blocked (by %s)"
11958 this org-state block-reason)
11959 ;; Fail silently.
11960 (message "TODO state change from %s to %s blocked (by %s)"
11961 this org-state block-reason)
11962 (throw 'exit nil)))))
11963 (store-match-data match-data)
11964 (replace-match next t t)
11965 (cond ((equal this org-state)
11966 (message "TODO state was already %s" (org-trim next)))
11967 ((not (pos-visible-in-window-p hl-pos))
11968 (message "TODO state changed to %s" (org-trim next))))
11969 (unless head
11970 (setq head (org-get-todo-sequence-head org-state)
11971 ass (assoc head org-todo-kwd-alist)
11972 interpret (nth 1 ass)
11973 done-word (nth 3 ass)
11974 final-done-word (nth 4 ass)))
11975 (when (memq arg '(nextset previousset))
11976 (message "Keyword-Set %d/%d: %s"
11977 (- (length org-todo-sets) -1
11978 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11979 (length org-todo-sets)
11980 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11981 (setq org-last-todo-state-is-todo
11982 (not (member org-state org-done-keywords)))
11983 (setq now-done-p (and (member org-state org-done-keywords)
11984 (not (member this org-done-keywords))))
11985 (and logging (org-local-logging logging))
11986 (when (and (or org-todo-log-states org-log-done)
11987 (not (eq org-inhibit-logging t))
11988 (not (memq arg '(nextset previousset))))
11989 ;; We need to look at recording a time and note.
11990 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11991 (nth 2 (assoc this org-todo-log-states))))
11992 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11993 (setq dolog 'time))
11994 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
11995 (and org-state
11996 (member org-state org-not-done-keywords)
11997 (not (member this org-not-done-keywords))))
11998 ;; This is now a todo state and was not one before
11999 ;; If there was a CLOSED time stamp, get rid of it.
12000 (org-add-planning-info nil nil 'closed))
12001 (when (and now-done-p org-log-done)
12002 ;; It is now done, and it was not done before.
12003 (org-add-planning-info 'closed (org-current-effective-time))
12004 (when (and (not dolog) (eq 'note org-log-done))
12005 (org-add-log-setup 'done org-state this 'note)))
12006 (when (and org-state dolog)
12007 ;; This is a non-nil state, and we need to log it.
12008 (org-add-log-setup 'state org-state this dolog)))
12009 ;; Fixup tag positioning.
12010 (org-todo-trigger-tag-changes org-state)
12011 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12012 (when org-provide-todo-statistics
12013 (org-update-parent-todo-statistics))
12014 (run-hooks 'org-after-todo-state-change-hook)
12015 (when (and arg (not (member org-state org-done-keywords)))
12016 (setq head (org-get-todo-sequence-head org-state)))
12017 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12018 ;; Do we need to trigger a repeat?
12019 (when now-done-p
12020 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12021 ;; This is for the agenda, take a snapshot of the headline.
12022 (save-match-data
12023 (setq org-agenda-headline-snapshot-before-repeat
12024 (org-get-heading))))
12025 (org-auto-repeat-maybe org-state))
12026 ;; Fixup cursor location if close to the keyword.
12027 (when (and (outline-on-heading-p)
12028 (not (bolp))
12029 (save-excursion (beginning-of-line 1)
12030 (looking-at org-todo-line-regexp))
12031 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12032 (goto-char (or (match-end 2) (match-end 1)))
12033 (and (looking-at " ") (just-one-space)))
12034 (when org-trigger-hook
12035 (save-excursion
12036 (run-hook-with-args 'org-trigger-hook change-plist)))
12037 (when commentp (org-toggle-comment))))))))
12039 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12040 "Block turning an entry into a TODO, using the hierarchy.
12041 This checks whether the current task should be blocked from state
12042 changes. Such blocking occurs when:
12044 1. The task has children which are not all in a completed state.
12046 2. A task has a parent with the property :ORDERED:, and there
12047 are siblings prior to the current task with incomplete
12048 status.
12050 3. The parent of the task is blocked because it has siblings that should
12051 be done first, or is child of a block grandparent TODO entry."
12053 (if (not org-enforce-todo-dependencies)
12054 t ; if locally turned off don't block
12055 (catch 'dont-block
12056 ;; If this is not a todo state change, or if this entry is already DONE,
12057 ;; do not block
12058 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12059 (member (plist-get change-plist :from)
12060 (cons 'done org-done-keywords))
12061 (member (plist-get change-plist :to)
12062 (cons 'todo org-not-done-keywords))
12063 (not (plist-get change-plist :to)))
12064 (throw 'dont-block t))
12065 ;; If this task has children, and any are undone, it's blocked
12066 (save-excursion
12067 (org-back-to-heading t)
12068 (let ((this-level (funcall outline-level)))
12069 (outline-next-heading)
12070 (let ((child-level (funcall outline-level)))
12071 (while (and (not (eobp))
12072 (> child-level this-level))
12073 ;; this todo has children, check whether they are all
12074 ;; completed
12075 (when (and (not (org-entry-is-done-p))
12076 (org-entry-is-todo-p))
12077 (setq org-block-entry-blocking (org-get-heading))
12078 (throw 'dont-block nil))
12079 (outline-next-heading)
12080 (setq child-level (funcall outline-level))))))
12081 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12082 ;; any previous siblings are undone, it's blocked
12083 (save-excursion
12084 (org-back-to-heading t)
12085 (let* ((pos (point))
12086 (parent-pos (and (org-up-heading-safe) (point)))
12087 (case-fold-search nil))
12088 (unless parent-pos (throw 'dont-block t)) ; no parent
12089 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12090 (forward-line 1)
12091 (re-search-forward org-not-done-heading-regexp pos t))
12092 (setq org-block-entry-blocking (match-string 0))
12093 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12094 ;; Search further up the hierarchy, to see if an ancestor is blocked
12095 (while t
12096 (goto-char parent-pos)
12097 (unless (looking-at org-not-done-heading-regexp)
12098 (throw 'dont-block t)) ; do not block, parent is not a TODO
12099 (setq pos (point))
12100 (setq parent-pos (and (org-up-heading-safe) (point)))
12101 (unless parent-pos (throw 'dont-block t)) ; no parent
12102 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12103 (forward-line 1)
12104 (re-search-forward org-not-done-heading-regexp pos t)
12105 (setq org-block-entry-blocking (org-get-heading)))
12106 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12108 (defcustom org-track-ordered-property-with-tag nil
12109 "Should the ORDERED property also be shown as a tag?
12110 The ORDERED property decides if an entry should require subtasks to be
12111 completed in sequence. Since a property is not very visible, setting
12112 this option means that toggling the ORDERED property with the command
12113 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12114 not relevant for the behavior, but it makes things more visible.
12116 Note that toggling the tag with tags commands will not change the property
12117 and therefore not influence behavior!
12119 This can be t, meaning the tag ORDERED should be used, It can also be a
12120 string to select a different tag for this task."
12121 :group 'org-todo
12122 :type '(choice
12123 (const :tag "No tracking" nil)
12124 (const :tag "Track with ORDERED tag" t)
12125 (string :tag "Use other tag")))
12127 (defun org-toggle-ordered-property ()
12128 "Toggle the ORDERED property of the current entry.
12129 For better visibility, you can track the value of this property with a tag.
12130 See variable `org-track-ordered-property-with-tag'."
12131 (interactive)
12132 (let* ((t1 org-track-ordered-property-with-tag)
12133 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12134 (save-excursion
12135 (org-back-to-heading)
12136 (if (org-entry-get nil "ORDERED")
12137 (progn
12138 (org-delete-property "ORDERED")
12139 (and tag (org-toggle-tag tag 'off))
12140 (message "Subtasks can be completed in arbitrary order"))
12141 (org-entry-put nil "ORDERED" "t")
12142 (and tag (org-toggle-tag tag 'on))
12143 (message "Subtasks must be completed in sequence")))))
12145 (defun org-block-todo-from-checkboxes (change-plist)
12146 "Block turning an entry into a TODO, using checkboxes.
12147 This checks whether the current task should be blocked from state
12148 changes because there are unchecked boxes in this entry."
12149 (if (not org-enforce-todo-checkbox-dependencies)
12150 t ; if locally turned off don't block
12151 (catch 'dont-block
12152 ;; If this is not a todo state change, or if this entry is already DONE,
12153 ;; do not block
12154 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12155 (member (plist-get change-plist :from)
12156 (cons 'done org-done-keywords))
12157 (member (plist-get change-plist :to)
12158 (cons 'todo org-not-done-keywords))
12159 (not (plist-get change-plist :to)))
12160 (throw 'dont-block t))
12161 ;; If this task has checkboxes that are not checked, it's blocked
12162 (save-excursion
12163 (org-back-to-heading t)
12164 (let ((beg (point)) end)
12165 (outline-next-heading)
12166 (setq end (point))
12167 (goto-char beg)
12168 (when (org-list-search-forward
12169 (concat (org-item-beginning-re)
12170 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12171 "\\[[- ]\\]")
12172 end t)
12173 (when (boundp 'org-blocked-by-checkboxes)
12174 (setq org-blocked-by-checkboxes t))
12175 (throw 'dont-block nil))))
12176 t))) ; do not block
12178 (defun org-entry-blocked-p ()
12179 "Non-nil if entry at point is blocked."
12180 (and (not (org-entry-get nil "NOBLOCKING"))
12181 (member (org-entry-get nil "TODO") org-not-done-keywords)
12182 (not (run-hook-with-args-until-failure
12183 'org-blocker-hook
12184 (list :type 'todo-state-change
12185 :position (point)
12186 :from 'todo
12187 :to 'done)))))
12189 (defun org-update-statistics-cookies (all)
12190 "Update the statistics cookie, either from TODO or from checkboxes.
12191 This should be called with the cursor in a line with a statistics
12192 cookie. When called with a \\[universal-argument] prefix, update
12193 all statistics cookies in the buffer."
12194 (interactive "P")
12195 (if all
12196 (progn
12197 (org-update-checkbox-count 'all)
12198 (org-map-entries 'org-update-parent-todo-statistics))
12199 (if (not (org-at-heading-p))
12200 (org-update-checkbox-count)
12201 (let ((pos (point-marker))
12202 end l1 l2)
12203 (ignore-errors (org-back-to-heading t))
12204 (if (not (org-at-heading-p))
12205 (org-update-checkbox-count)
12206 (setq l1 (org-outline-level))
12207 (setq end (save-excursion
12208 (outline-next-heading)
12209 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12210 (point)))
12211 (if (and (save-excursion
12212 (re-search-forward
12213 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12214 (not (save-excursion (re-search-forward
12215 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12216 (org-update-checkbox-count)
12217 (if (and l2 (> l2 l1))
12218 (progn
12219 (goto-char end)
12220 (org-update-parent-todo-statistics))
12221 (goto-char pos)
12222 (beginning-of-line 1)
12223 (while (re-search-forward
12224 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12225 (point-at-eol) t)
12226 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12227 (goto-char pos)
12228 (move-marker pos nil)))))
12230 (defvar org-entry-property-inherited-from) ;; defined below
12231 (defun org-update-parent-todo-statistics ()
12232 "Update any statistics cookie in the parent of the current headline.
12233 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12234 the entire subtree and this will travel up the hierarchy and update
12235 statistics everywhere."
12236 (let* ((prop (save-excursion (org-up-heading-safe)
12237 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12238 (recursive (or (not org-hierarchical-todo-statistics)
12239 (and prop (string-match "\\<recursive\\>" prop))))
12240 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12242 (first t)
12243 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12244 level ltoggle l1 new ndel
12245 (cnt-all 0) (cnt-done 0) is-percent kwd
12246 checkbox-beg cookie-present)
12247 (catch 'exit
12248 (save-excursion
12249 (beginning-of-line 1)
12250 (setq ltoggle (funcall outline-level))
12251 ;; Three situations are to consider:
12253 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12254 ;; to the top-level ancestor on the headline;
12256 ;; 2. If parent has "recursive" property, repeat up to the
12257 ;; headline setting that property, taking inheritance into
12258 ;; account;
12260 ;; 3. Else, move up to direct parent and proceed only once.
12261 (while (and (setq level (org-up-heading-safe))
12262 (or recursive first)
12263 (>= (point) lim))
12264 (setq first nil cookie-present nil)
12265 (unless (and level
12266 (not (string-match
12267 "\\<checkbox\\>"
12268 (downcase (or (org-entry-get nil "COOKIE_DATA")
12269 "")))))
12270 (throw 'exit nil))
12271 (while (re-search-forward box-re (point-at-eol) t)
12272 (setq cnt-all 0 cnt-done 0 cookie-present t)
12273 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12274 (save-match-data
12275 (unless (outline-next-heading) (throw 'exit nil))
12276 (while (and (looking-at org-complex-heading-regexp)
12277 (> (setq l1 (length (match-string 1))) level))
12278 (setq kwd (and (or recursive (= l1 ltoggle))
12279 (match-string 2)))
12280 (if (or (eq org-provide-todo-statistics 'all-headlines)
12281 (and (eq org-provide-todo-statistics t)
12282 (or (member kwd org-done-keywords)))
12283 (and (listp org-provide-todo-statistics)
12284 (stringp (car org-provide-todo-statistics))
12285 (or (member kwd org-provide-todo-statistics)
12286 (member kwd org-done-keywords)))
12287 (and (listp org-provide-todo-statistics)
12288 (listp (car org-provide-todo-statistics))
12289 (or (member kwd (car org-provide-todo-statistics))
12290 (and (member kwd org-done-keywords)
12291 (member kwd (cadr org-provide-todo-statistics))))))
12292 (setq cnt-all (1+ cnt-all))
12293 (and (eq org-provide-todo-statistics t)
12295 (setq cnt-all (1+ cnt-all))))
12296 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12297 (member kwd org-done-keywords))
12298 (and (listp org-provide-todo-statistics)
12299 (listp (car org-provide-todo-statistics))
12300 (member kwd org-done-keywords)
12301 (member kwd (cadr org-provide-todo-statistics)))
12302 (and (listp org-provide-todo-statistics)
12303 (stringp (car org-provide-todo-statistics))
12304 (member kwd org-done-keywords)))
12305 (setq cnt-done (1+ cnt-done)))
12306 (outline-next-heading)))
12307 (setq new
12308 (if is-percent
12309 (format "[%d%%]" (floor (* 100.0 cnt-done)
12310 (max 1 cnt-all)))
12311 (format "[%d/%d]" cnt-done cnt-all))
12312 ndel (- (match-end 0) checkbox-beg))
12313 (goto-char checkbox-beg)
12314 (insert new)
12315 (delete-region (point) (+ (point) ndel))
12316 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12317 (when cookie-present
12318 (run-hook-with-args 'org-after-todo-statistics-hook
12319 cnt-done (- cnt-all cnt-done))))))
12320 (run-hooks 'org-todo-statistics-hook)))
12322 (defvar org-after-todo-statistics-hook nil
12323 "Hook that is called after a TODO statistics cookie has been updated.
12324 Each function is called with two arguments: the number of not-done entries
12325 and the number of done entries.
12327 For example, the following function, when added to this hook, will switch
12328 an entry to DONE when all children are done, and back to TODO when new
12329 entries are set to a TODO status. Note that this hook is only called
12330 when there is a statistics cookie in the headline!
12332 (defun org-summary-todo (n-done n-not-done)
12333 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12334 (let (org-log-done org-log-states) ; turn off logging
12335 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12338 (defvar org-todo-statistics-hook nil
12339 "Hook that is run whenever Org thinks TODO statistics should be updated.
12340 This hook runs even if there is no statistics cookie present, in which case
12341 `org-after-todo-statistics-hook' would not run.")
12343 (defun org-todo-trigger-tag-changes (state)
12344 "Apply the changes defined in `org-todo-state-tags-triggers'."
12345 (let ((l org-todo-state-tags-triggers)
12346 changes)
12347 (when (or (not state) (equal state ""))
12348 (setq changes (append changes (cdr (assoc "" l)))))
12349 (when (and (stringp state) (> (length state) 0))
12350 (setq changes (append changes (cdr (assoc state l)))))
12351 (when (member state org-not-done-keywords)
12352 (setq changes (append changes (cdr (assq 'todo l)))))
12353 (when (member state org-done-keywords)
12354 (setq changes (append changes (cdr (assq 'done l)))))
12355 (dolist (c changes)
12356 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12358 (defun org-local-logging (value)
12359 "Get logging settings from a property VALUE."
12360 ;; Directly set the variables, they are already local.
12361 (setq org-log-done nil
12362 org-log-repeat nil
12363 org-todo-log-states nil)
12364 (dolist (w (split-string value))
12365 (let (a)
12366 (cond
12367 ((setq a (assoc w org-startup-options))
12368 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12369 (set (nth 1 a) (nth 2 a))))
12370 ((setq a (org-extract-log-state-settings w))
12371 (and (member (car a) org-todo-keywords-1)
12372 (push a org-todo-log-states)))))))
12374 (defun org-get-todo-sequence-head (kwd)
12375 "Return the head of the TODO sequence to which KWD belongs.
12376 If KWD is not set, check if there is a text property remembering the
12377 right sequence."
12378 (let (p)
12379 (cond
12380 ((not kwd)
12381 (or (get-text-property (point-at-bol) 'org-todo-head)
12382 (progn
12383 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12384 nil (point-at-eol)))
12385 (get-text-property p 'org-todo-head))))
12386 ((not (member kwd org-todo-keywords-1))
12387 (car org-todo-keywords-1))
12388 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12390 (defun org-fast-todo-selection ()
12391 "Fast TODO keyword selection with single keys.
12392 Returns the new TODO keyword, or nil if no state change should occur."
12393 (let* ((fulltable org-todo-key-alist)
12394 (done-keywords org-done-keywords) ;; needed for the faces.
12395 (maxlen (apply 'max (mapcar
12396 (lambda (x)
12397 (if (stringp (car x)) (string-width (car x)) 0))
12398 fulltable)))
12399 (expert nil)
12400 (fwidth (+ maxlen 3 1 3))
12401 (ncol (/ (- (window-width) 4) fwidth))
12402 tg cnt e c tbl
12403 groups ingroup)
12404 (save-excursion
12405 (save-window-excursion
12406 (if expert
12407 (set-buffer (get-buffer-create " *Org todo*"))
12408 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12409 (erase-buffer)
12410 (setq-local org-done-keywords done-keywords)
12411 (setq tbl fulltable cnt 0)
12412 (while (setq e (pop tbl))
12413 (cond
12414 ((equal e '(:startgroup))
12415 (push '() groups) (setq ingroup t)
12416 (unless (= cnt 0)
12417 (setq cnt 0)
12418 (insert "\n"))
12419 (insert "{ "))
12420 ((equal e '(:endgroup))
12421 (setq ingroup nil cnt 0)
12422 (insert "}\n"))
12423 ((equal e '(:newline))
12424 (unless (= cnt 0)
12425 (setq cnt 0)
12426 (insert "\n")
12427 (setq e (car tbl))
12428 (while (equal (car tbl) '(:newline))
12429 (insert "\n")
12430 (setq tbl (cdr tbl)))))
12432 (setq tg (car e) c (cdr e))
12433 (when ingroup (push tg (car groups)))
12434 (setq tg (org-add-props tg nil 'face
12435 (org-get-todo-face tg)))
12436 (when (and (= cnt 0) (not ingroup)) (insert " "))
12437 (insert "[" c "] " tg (make-string
12438 (- fwidth 4 (length tg)) ?\ ))
12439 (when (= (setq cnt (1+ cnt)) ncol)
12440 (insert "\n")
12441 (when ingroup (insert " "))
12442 (setq cnt 0)))))
12443 (insert "\n")
12444 (goto-char (point-min))
12445 (unless expert (org-fit-window-to-buffer))
12446 (message "[a-z..]:Set [SPC]:clear")
12447 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12448 (cond
12449 ((or (= c ?\C-g)
12450 (and (= c ?q) (not (rassoc c fulltable))))
12451 (setq quit-flag t))
12452 ((= c ?\ ) nil)
12453 ((setq e (rassoc c fulltable) tg (car e))
12455 (t (setq quit-flag t)))))))
12457 (defun org-entry-is-todo-p ()
12458 (member (org-get-todo-state) org-not-done-keywords))
12460 (defun org-entry-is-done-p ()
12461 (member (org-get-todo-state) org-done-keywords))
12463 (defun org-get-todo-state ()
12464 "Return the TODO keyword of the current subtree."
12465 (save-excursion
12466 (org-back-to-heading t)
12467 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12468 (match-end 2)
12469 (match-string 2))))
12471 (defun org-at-date-range-p (&optional inactive-ok)
12472 "Non-nil if point is inside a date range.
12474 When optional argument INACTIVE-OK is non-nil, also consider
12475 inactive time ranges.
12477 When this function returns a non-nil value, match data is set
12478 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12479 on INACTIVE-OK."
12480 (interactive)
12481 (save-excursion
12482 (catch 'exit
12483 (let ((pos (point)))
12484 (skip-chars-backward "^[<\r\n")
12485 (skip-chars-backward "<[")
12486 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12487 (>= (match-end 0) pos)
12488 (throw 'exit t))
12489 (skip-chars-backward "^<[\r\n")
12490 (skip-chars-backward "<[")
12491 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12492 (>= (match-end 0) pos)
12493 (throw 'exit t)))
12494 nil)))
12496 (defun org-get-repeat (&optional timestamp)
12497 "Check if there is a time-stamp with repeater in this entry.
12499 Return the repeater, as a string, or nil. Also return nil when
12500 this function is called before first heading.
12502 When optional argument TIMESTAMP is a string, extract the
12503 repeater from there instead."
12504 (save-match-data
12505 (cond (timestamp
12506 (and (string-match org-repeat-re timestamp)
12507 (match-string-no-properties 1 timestamp)))
12508 ((org-before-first-heading-p) nil)
12510 (save-excursion
12511 (org-back-to-heading t)
12512 (let ((end (org-entry-end-position)))
12513 (catch :repeat
12514 (while (re-search-forward org-repeat-re end t)
12515 (when (save-match-data (org-at-timestamp-p 'agenda))
12516 (throw :repeat (match-string-no-properties 1)))))))))))
12518 (defvar org-last-changed-timestamp)
12519 (defvar org-last-inserted-timestamp)
12520 (defvar org-log-post-message)
12521 (defvar org-log-note-purpose)
12522 (defvar org-log-note-how nil)
12523 (defvar org-log-note-extra)
12524 (defun org-auto-repeat-maybe (done-word)
12525 "Check if the current headline contains a repeated time-stamp.
12527 If yes, set TODO state back to what it was and change the base date
12528 of repeating deadline/scheduled time stamps to new date.
12530 This function is run automatically after each state change to a DONE state."
12531 (let* ((repeat (org-get-repeat))
12532 (aa (assoc org-last-state org-todo-kwd-alist))
12533 (interpret (nth 1 aa))
12534 (head (nth 2 aa))
12535 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12536 (msg "Entry repeats: ")
12537 (org-log-done nil)
12538 (org-todo-log-states nil)
12539 (end (copy-marker (org-entry-end-position))))
12540 (unwind-protect
12541 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12542 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12543 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12544 (and (stringp org-todo-repeat-to-state)
12545 org-todo-repeat-to-state)
12546 (and org-todo-repeat-to-state org-last-state))))
12547 (org-todo (cond
12548 ((and to-state (member to-state org-todo-keywords-1))
12549 to-state)
12550 ((eq interpret 'type) org-last-state)
12551 (head)
12552 (t 'none))))
12553 (org-back-to-heading t)
12554 (org-add-planning-info nil nil 'closed)
12555 ;; When `org-log-repeat' is non-nil or entry contains
12556 ;; a clock, set LAST_REPEAT property.
12557 (when (or org-log-repeat
12558 (catch :clock
12559 (save-excursion
12560 (while (re-search-forward org-clock-line-re end t)
12561 (when (org-at-clock-log-p) (throw :clock t))))))
12562 (org-entry-put nil "LAST_REPEAT" (format-time-string
12563 (org-time-stamp-format t t)
12564 (current-time))))
12565 (when org-log-repeat
12566 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12567 (memq 'org-add-log-note post-command-hook))
12568 ;; We are already setup for some record.
12569 (when (eq org-log-repeat 'note)
12570 ;; Make sure we take a note, not only a time stamp.
12571 (setq org-log-note-how 'note))
12572 ;; Set up for taking a record.
12573 (org-add-log-setup 'state
12574 (or done-word (car org-done-keywords))
12575 org-last-state
12576 org-log-repeat)))
12577 (let ((planning-re (regexp-opt
12578 (list org-scheduled-string org-deadline-string))))
12579 (while (re-search-forward org-ts-regexp end t)
12580 (let* ((ts (match-string 0))
12581 (planning? (org-at-planning-p))
12582 (type (if (not planning?) "Plain:"
12583 (save-excursion
12584 (re-search-backward
12585 planning-re (line-beginning-position) t)
12586 (match-string 0)))))
12587 (cond
12588 ;; Ignore fake time-stamps (e.g., within comments).
12589 ((not (org-at-timestamp-p 'agenda)))
12590 ;; Time-stamps without a repeater are usually
12591 ;; skipped. However, a SCHEDULED time-stamp without
12592 ;; one is removed, as they are no longer relevant.
12593 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12594 ts))
12595 (when (equal type org-scheduled-string)
12596 (org-remove-timestamp-with-keyword type)))
12598 (let ((n (string-to-number (match-string 2 ts)))
12599 (what (match-string 3 ts)))
12600 (when (equal what "w") (setq n (* n 7) what "d"))
12601 (when (and (equal what "h")
12602 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12603 ts)))
12604 (user-error
12605 "Cannot repeat in Repeat in %d hour(s) because no hour \
12606 has been set"
12608 ;; Preparation, see if we need to modify the start
12609 ;; date for the change.
12610 (when (match-end 1)
12611 (let ((time (save-match-data
12612 (org-time-string-to-time ts))))
12613 (cond
12614 ((equal (match-string 1 ts) ".")
12615 ;; Shift starting date to today
12616 (org-timestamp-change
12617 (- (org-today) (time-to-days time))
12618 'day))
12619 ((equal (match-string 1 ts) "+")
12620 (let ((nshiftmax 10)
12621 (nshift 0))
12622 (while (or (= nshift 0)
12623 (not (time-less-p (current-time) time)))
12624 (when (= (cl-incf nshift) nshiftmax)
12625 (or (y-or-n-p
12626 (format "%d repeater intervals were not \
12627 enough to shift date past today. Continue? "
12628 nshift))
12629 (user-error "Abort")))
12630 (org-timestamp-change n (cdr (assoc what whata)))
12631 (org-in-regexp org-ts-regexp3)
12632 (setq ts (match-string 1))
12633 (setq time
12634 (save-match-data
12635 (org-time-string-to-time ts)))))
12636 (org-timestamp-change (- n) (cdr (assoc what whata)))
12637 ;; Rematch, so that we have everything in place
12638 ;; for the real shift.
12639 (org-in-regexp org-ts-regexp3)
12640 (setq ts (match-string 1))
12641 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12642 ts)))))
12643 (save-excursion
12644 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12645 (setq msg
12646 (concat
12647 msg type " " org-last-changed-timestamp " "))))))))
12648 (setq org-log-post-message msg)
12649 (message "%s" msg))
12650 (set-marker end nil))))
12652 (defun org-show-todo-tree (arg)
12653 "Make a compact tree which shows all headlines marked with TODO.
12654 The tree will show the lines where the regexp matches, and all higher
12655 headlines above the match.
12656 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12657 With a numeric prefix N, construct a sparse tree for the Nth element
12658 of `org-todo-keywords-1'."
12659 (interactive "P")
12660 (let ((case-fold-search nil)
12661 (kwd-re
12662 (cond ((null arg) org-not-done-regexp)
12663 ((equal arg '(4))
12664 (let ((kwd
12665 (completing-read "Keyword (or KWD1|KWD2|...): "
12666 (mapcar #'list org-todo-keywords-1))))
12667 (concat "\\("
12668 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12669 "\\)\\>")))
12670 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12671 (regexp-quote (nth (1- (prefix-numeric-value arg))
12672 org-todo-keywords-1)))
12673 (t (user-error "Invalid prefix argument: %s" arg)))))
12674 (message "%d TODO entries found"
12675 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12677 (defun org--deadline-or-schedule (arg type time)
12678 "Insert DEADLINE or SCHEDULE information in current entry.
12679 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12680 `org-schedule' for information about ARG and TIME arguments."
12681 (let* ((deadline? (eq type 'deadline))
12682 (keyword (if deadline? org-deadline-string org-scheduled-string))
12683 (log (if deadline? org-log-redeadline org-log-reschedule))
12684 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12685 (old-date-time (and old-date (org-time-string-to-time old-date)))
12686 ;; Save repeater cookie from either TIME or current scheduled
12687 ;; time stamp. We are going to insert it back at the end of
12688 ;; the process.
12689 (repeater (or (and (org-string-nw-p time)
12690 ;; We use `org-repeat-re' because we need
12691 ;; to tell the difference between a real
12692 ;; repeater and a time delta, e.g. "+2d".
12693 (string-match org-repeat-re time)
12694 (match-string 1 time))
12695 (and (org-string-nw-p old-date)
12696 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12697 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12698 old-date)
12699 (match-string 1 old-date)))))
12700 (pcase arg
12701 (`(4)
12702 (when (and old-date log)
12703 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12704 nil old-date log))
12705 (org-remove-timestamp-with-keyword keyword)
12706 (message (if deadline? "Item no longer has a deadline."
12707 "Item is no longer scheduled.")))
12708 (`(16)
12709 (save-excursion
12710 (org-back-to-heading t)
12711 (let ((regexp (if deadline? org-deadline-time-regexp
12712 org-scheduled-time-regexp)))
12713 (if (not (re-search-forward regexp (line-end-position 2) t))
12714 (user-error (if deadline? "No deadline information to update"
12715 "No scheduled information to update"))
12716 (let* ((rpl0 (match-string 1))
12717 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12718 (msg (if deadline? "Warn starting from" "Delay until")))
12719 (replace-match
12720 (concat keyword
12721 " <" rpl
12722 (format " -%dd"
12723 (abs (- (time-to-days
12724 (save-match-data
12725 (org-read-date
12726 nil t nil msg old-date-time)))
12727 (time-to-days old-date-time))))
12728 ">") t t))))))
12730 (org-add-planning-info type time 'closed)
12731 (when (and old-date
12733 (not (equal old-date org-last-inserted-timestamp)))
12734 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12735 org-last-inserted-timestamp
12736 old-date
12737 log))
12738 (when repeater
12739 (save-excursion
12740 (org-back-to-heading t)
12741 (when (re-search-forward
12742 (concat keyword " " org-last-inserted-timestamp)
12743 (line-end-position 2)
12745 (goto-char (1- (match-end 0)))
12746 (insert " " repeater)
12747 (setq org-last-inserted-timestamp
12748 (concat (substring org-last-inserted-timestamp 0 -1)
12749 " " repeater
12750 (substring org-last-inserted-timestamp -1))))))
12751 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12752 org-last-inserted-timestamp)))))
12754 (defun org-deadline (arg &optional time)
12755 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12756 With one universal prefix argument, remove any deadline from the item.
12757 With two universal prefix arguments, prompt for a warning delay.
12758 With argument TIME, set the deadline at the corresponding date. TIME
12759 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12760 (interactive "P")
12761 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12762 (org-map-entries
12763 (lambda () (org--deadline-or-schedule arg 'deadline time))
12765 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12766 'region-start-level
12767 'region)
12768 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12769 (org--deadline-or-schedule arg 'deadline time)))
12771 (defun org-schedule (arg &optional time)
12772 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12773 With one universal prefix argument, remove any scheduling date from the item.
12774 With two universal prefix arguments, prompt for a delay cookie.
12775 With argument TIME, scheduled at the corresponding date. TIME can
12776 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12777 (interactive "P")
12778 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12779 (org-map-entries
12780 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12782 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12783 'region-start-level
12784 'region)
12785 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12786 (org--deadline-or-schedule arg 'scheduled time)))
12788 (defun org-get-scheduled-time (pom &optional inherit)
12789 "Get the scheduled time as a time tuple, of a format suitable
12790 for calling org-schedule with, or if there is no scheduling,
12791 returns nil."
12792 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12793 (when time
12794 (apply 'encode-time (org-parse-time-string time)))))
12796 (defun org-get-deadline-time (pom &optional inherit)
12797 "Get the deadline as a time tuple, of a format suitable for
12798 calling org-deadline with, or if there is no scheduling, returns
12799 nil."
12800 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12801 (when time
12802 (apply 'encode-time (org-parse-time-string time)))))
12804 (defun org-remove-timestamp-with-keyword (keyword)
12805 "Remove all time stamps with KEYWORD in the current entry."
12806 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12807 beg)
12808 (save-excursion
12809 (org-back-to-heading t)
12810 (setq beg (point))
12811 (outline-next-heading)
12812 (while (re-search-backward re beg t)
12813 (replace-match "")
12814 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12815 (equal (char-before) ?\ ))
12816 (backward-delete-char 1)
12817 (when (string-match "^[ \t]*$" (buffer-substring
12818 (point-at-bol) (point-at-eol)))
12819 (delete-region (point-at-bol)
12820 (min (point-max) (1+ (point-at-eol))))))))))
12822 (defvar org-time-was-given) ; dynamically scoped parameter
12823 (defvar org-end-time-was-given) ; dynamically scoped parameter
12825 (defun org-at-planning-p ()
12826 "Non-nil when point is on a planning info line."
12827 ;; This is as accurate and faster than `org-element-at-point' since
12828 ;; planning info location is fixed in the section.
12829 (org-with-wide-buffer
12830 (beginning-of-line)
12831 (and (looking-at-p org-planning-line-re)
12832 (eq (point)
12833 (ignore-errors
12834 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12835 (org-back-to-heading t)
12836 (org-with-limited-levels (org-back-to-heading t)))
12837 (line-beginning-position 2))))))
12839 (defun org-add-planning-info (what &optional time &rest remove)
12840 "Insert new timestamp with keyword in the planning line.
12841 WHAT indicates what kind of time stamp to add. It is a symbol
12842 among `closed', `deadline', `scheduled' and nil. TIME indicates
12843 the time to use. If none is given, the user is prompted for
12844 a date. REMOVE indicates what kind of entries to remove. An old
12845 WHAT entry will also be removed."
12846 (let (org-time-was-given org-end-time-was-given default-time default-input)
12847 (catch 'exit
12848 (when (and (memq what '(scheduled deadline))
12849 (or (not time)
12850 (and (stringp time)
12851 (string-match "^[-+]+[0-9]" time))))
12852 ;; Try to get a default date/time from existing timestamp
12853 (save-excursion
12854 (org-back-to-heading t)
12855 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12856 (when (re-search-forward (if (eq what 'scheduled)
12857 org-scheduled-time-regexp
12858 org-deadline-time-regexp)
12859 end t)
12860 (setq ts (match-string 1)
12861 default-time (apply 'encode-time (org-parse-time-string ts))
12862 default-input (and ts (org-get-compact-tod ts)))))))
12863 (when what
12864 (setq time
12865 (if (stringp time)
12866 ;; This is a string (relative or absolute), set
12867 ;; proper date.
12868 (apply #'encode-time
12869 (org-read-date-analyze
12870 time default-time (decode-time default-time)))
12871 ;; If necessary, get the time from the user
12872 (or time (org-read-date nil 'to-time nil nil
12873 default-time default-input)))))
12875 (org-with-wide-buffer
12876 (org-back-to-heading t)
12877 (forward-line)
12878 (unless (bolp) (insert "\n"))
12879 (cond ((looking-at-p org-planning-line-re)
12880 ;; Move to current indentation.
12881 (skip-chars-forward " \t")
12882 ;; Check if we have to remove something.
12883 (dolist (type (if what (cons what remove) remove))
12884 (save-excursion
12885 (when (re-search-forward
12886 (cl-case type
12887 (closed org-closed-time-regexp)
12888 (deadline org-deadline-time-regexp)
12889 (scheduled org-scheduled-time-regexp)
12890 (otherwise
12891 (error "Invalid planning type: %s" type)))
12892 (line-end-position) t)
12893 ;; Delete until next keyword or end of line.
12894 (delete-region
12895 (match-beginning 0)
12896 (if (re-search-forward org-keyword-time-not-clock-regexp
12897 (line-end-position)
12899 (match-beginning 0)
12900 (line-end-position))))))
12901 ;; If there is nothing more to add and no more keyword
12902 ;; is left, remove the line completely.
12903 (if (and (looking-at-p "[ \t]*$") (not what))
12904 (delete-region (line-beginning-position)
12905 (line-beginning-position 2))
12906 ;; If we removed last keyword, do not leave trailing
12907 ;; white space at the end of line.
12908 (let ((p (point)))
12909 (save-excursion
12910 (end-of-line)
12911 (unless (= (skip-chars-backward " \t" p) 0)
12912 (delete-region (point) (line-end-position)))))))
12913 ((not what) (throw 'exit nil)) ; Nothing to do.
12914 (t (insert-before-markers "\n")
12915 (backward-char 1)
12916 (when org-adapt-indentation
12917 (indent-to-column (1+ (org-outline-level))))))
12918 (when what
12919 ;; Insert planning keyword.
12920 (insert (cl-case what
12921 (closed org-closed-string)
12922 (deadline org-deadline-string)
12923 (scheduled org-scheduled-string)
12924 (otherwise (error "Invalid planning type: %s" what)))
12925 " ")
12926 ;; Insert associated timestamp.
12927 (let ((ts (org-insert-time-stamp
12928 time
12929 (or org-time-was-given
12930 (and (eq what 'closed) org-log-done-with-time))
12931 (eq what 'closed)
12932 nil nil (list org-end-time-was-given))))
12933 (unless (eolp) (insert " "))
12934 ts))))))
12936 (defvar org-log-note-marker (make-marker)
12937 "Marker pointing at the entry where the note is to be inserted.")
12938 (defvar org-log-note-purpose nil)
12939 (defvar org-log-note-state nil)
12940 (defvar org-log-note-previous-state nil)
12941 (defvar org-log-note-extra nil)
12942 (defvar org-log-note-window-configuration nil)
12943 (defvar org-log-note-return-to (make-marker))
12944 (defvar org-log-note-effective-time nil
12945 "Remembered current time so that dynamically scoped
12946 `org-extend-today-until' affects timestamps in state change log")
12948 (defvar org-log-post-message nil
12949 "Message to be displayed after a log note has been stored.
12950 The auto-repeater uses this.")
12952 (defun org-add-note ()
12953 "Add a note to the current entry.
12954 This is done in the same way as adding a state change note."
12955 (interactive)
12956 (org-add-log-setup 'note))
12958 (defun org-log-beginning (&optional create)
12959 "Return expected start of log notes in current entry.
12960 When optional argument CREATE is non-nil, the function creates
12961 a drawer to store notes, if necessary. Returned position ignores
12962 narrowing."
12963 (org-with-wide-buffer
12964 (let ((drawer (org-log-into-drawer)))
12965 (cond
12966 (drawer
12967 (org-end-of-meta-data)
12968 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
12969 (end (if (org-at-heading-p) (point)
12970 (save-excursion (outline-next-heading) (point))))
12971 (case-fold-search t))
12972 (catch 'exit
12973 ;; Try to find existing drawer.
12974 (while (re-search-forward regexp end t)
12975 (let ((element (org-element-at-point)))
12976 (when (eq (org-element-type element) 'drawer)
12977 (let ((cend (org-element-property :contents-end element)))
12978 (when (and (not org-log-states-order-reversed) cend)
12979 (goto-char cend)))
12980 (throw 'exit nil))))
12981 ;; No drawer found. Create one, if permitted.
12982 (when create
12983 (unless (bolp) (insert "\n"))
12984 (let ((beg (point)))
12985 (insert ":" drawer ":\n:END:\n")
12986 (org-indent-region beg (point))
12987 (org-flag-region
12988 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
12989 (end-of-line -1)))))
12991 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
12992 (skip-chars-forward " \t\n")
12993 (beginning-of-line)
12994 (unless org-log-states-order-reversed
12995 (org-skip-over-state-notes)
12996 (skip-chars-backward " \t\n")
12997 (forward-line)))))
12998 (if (bolp) (point) (line-beginning-position 2))))
13000 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13001 "Set up the post command hook to take a note.
13002 If this is about to TODO state change, the new state is expected in STATE.
13003 HOW is an indicator what kind of note should be created.
13004 EXTRA is additional text that will be inserted into the notes buffer."
13005 (move-marker org-log-note-marker (point))
13006 (setq org-log-note-purpose purpose
13007 org-log-note-state state
13008 org-log-note-previous-state prev-state
13009 org-log-note-how how
13010 org-log-note-extra extra
13011 org-log-note-effective-time (org-current-effective-time))
13012 (add-hook 'post-command-hook 'org-add-log-note 'append))
13014 (defun org-skip-over-state-notes ()
13015 "Skip past the list of State notes in an entry."
13016 (when (ignore-errors (goto-char (org-in-item-p)))
13017 (let* ((struct (org-list-struct))
13018 (prevs (org-list-prevs-alist struct))
13019 (regexp
13020 (concat "[ \t]*- +"
13021 (replace-regexp-in-string
13022 " +" " +"
13023 (org-replace-escapes
13024 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13025 `(("%d" . ,org-ts-regexp-inactive)
13026 ("%D" . ,org-ts-regexp)
13027 ("%s" . "\"\\S-+\"")
13028 ("%S" . "\"\\S-+\"")
13029 ("%t" . ,org-ts-regexp-inactive)
13030 ("%T" . ,org-ts-regexp)
13031 ("%u" . ".*?")
13032 ("%U" . ".*?")))))))
13033 (while (looking-at-p regexp)
13034 (goto-char (or (org-list-get-next-item (point) struct prevs)
13035 (org-list-get-item-end (point) struct)))))))
13037 (defun org-add-log-note (&optional _purpose)
13038 "Pop up a window for taking a note, and add this note later."
13039 (remove-hook 'post-command-hook 'org-add-log-note)
13040 (setq org-log-note-window-configuration (current-window-configuration))
13041 (delete-other-windows)
13042 (move-marker org-log-note-return-to (point))
13043 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13044 (goto-char org-log-note-marker)
13045 (org-switch-to-buffer-other-window "*Org Note*")
13046 (erase-buffer)
13047 (if (memq org-log-note-how '(time state))
13048 (org-store-log-note)
13049 (let ((org-inhibit-startup t)) (org-mode))
13050 (insert (format "# Insert note for %s.
13051 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13052 (cond
13053 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13054 ((eq org-log-note-purpose 'done) "closed todo item")
13055 ((eq org-log-note-purpose 'state)
13056 (format "state change from \"%s\" to \"%s\""
13057 (or org-log-note-previous-state "")
13058 (or org-log-note-state "")))
13059 ((eq org-log-note-purpose 'reschedule)
13060 "rescheduling")
13061 ((eq org-log-note-purpose 'delschedule)
13062 "no longer scheduled")
13063 ((eq org-log-note-purpose 'redeadline)
13064 "changing deadline")
13065 ((eq org-log-note-purpose 'deldeadline)
13066 "removing deadline")
13067 ((eq org-log-note-purpose 'refile)
13068 "refiling")
13069 ((eq org-log-note-purpose 'note)
13070 "this entry")
13071 (t (error "This should not happen")))))
13072 (when org-log-note-extra (insert org-log-note-extra))
13073 (setq-local org-finish-function 'org-store-log-note)
13074 (run-hooks 'org-log-buffer-setup-hook)))
13076 (defvar org-note-abort nil) ; dynamically scoped
13077 (defun org-store-log-note ()
13078 "Finish taking a log note, and insert it to where it belongs."
13079 (let ((txt (prog1 (buffer-string)
13080 (kill-buffer)))
13081 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13082 lines)
13083 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13084 (setq txt (replace-match "" t t txt)))
13085 (when (string-match "\\s-+\\'" txt)
13086 (setq txt (replace-match "" t t txt)))
13087 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13088 (when (org-string-nw-p note)
13089 (setq note
13090 (org-replace-escapes
13091 note
13092 (list (cons "%u" (user-login-name))
13093 (cons "%U" user-full-name)
13094 (cons "%t" (format-time-string
13095 (org-time-stamp-format 'long 'inactive)
13096 org-log-note-effective-time))
13097 (cons "%T" (format-time-string
13098 (org-time-stamp-format 'long nil)
13099 org-log-note-effective-time))
13100 (cons "%d" (format-time-string
13101 (org-time-stamp-format nil 'inactive)
13102 org-log-note-effective-time))
13103 (cons "%D" (format-time-string
13104 (org-time-stamp-format nil nil)
13105 org-log-note-effective-time))
13106 (cons "%s" (cond
13107 ((not org-log-note-state) "")
13108 ((string-match-p org-ts-regexp
13109 org-log-note-state)
13110 (format "\"[%s]\""
13111 (substring org-log-note-state 1 -1)))
13112 (t (format "\"%s\"" org-log-note-state))))
13113 (cons "%S"
13114 (cond
13115 ((not org-log-note-previous-state) "")
13116 ((string-match-p org-ts-regexp
13117 org-log-note-previous-state)
13118 (format "\"[%s]\""
13119 (substring
13120 org-log-note-previous-state 1 -1)))
13121 (t (format "\"%s\""
13122 org-log-note-previous-state)))))))
13123 (when lines (setq note (concat note " \\\\")))
13124 (push note lines))
13125 (when (and lines (not org-note-abort))
13126 (with-current-buffer (marker-buffer org-log-note-marker)
13127 (org-with-wide-buffer
13128 ;; Find location for the new note.
13129 (goto-char org-log-note-marker)
13130 (set-marker org-log-note-marker nil)
13131 ;; Note associated to a clock is to be located right after
13132 ;; the clock. Do not move point.
13133 (unless (eq org-log-note-purpose 'clock-out)
13134 (goto-char (org-log-beginning t)))
13135 ;; Make sure point is at the beginning of an empty line.
13136 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13137 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13138 ;; In an existing list, add a new item at the top level.
13139 ;; Otherwise, indent line like a regular one.
13140 (let ((itemp (org-in-item-p)))
13141 (if itemp
13142 (indent-line-to
13143 (let ((struct (save-excursion
13144 (goto-char itemp) (org-list-struct))))
13145 (org-list-get-ind (org-list-get-top-point struct) struct)))
13146 (org-indent-line)))
13147 (insert (org-list-bullet-string "-") (pop lines))
13148 (let ((ind (org-list-item-body-column (line-beginning-position))))
13149 (dolist (line lines)
13150 (insert "\n")
13151 (indent-line-to ind)
13152 (insert line)))
13153 (message "Note stored")
13154 (org-back-to-heading t))
13155 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13156 ;; from within `org-add-log-note' because `buffer-undo-list'
13157 ;; is then modified outside of `org-with-remote-undo'.
13158 (when (eq this-command 'org-agenda-todo)
13159 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13160 ;; Don't add undo information when called from `org-agenda-todo'.
13161 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13162 (set-window-configuration org-log-note-window-configuration)
13163 (with-current-buffer (marker-buffer org-log-note-return-to)
13164 (goto-char org-log-note-return-to))
13165 (move-marker org-log-note-return-to nil)
13166 (when org-log-post-message (message "%s" org-log-post-message))))
13168 (defun org-remove-empty-drawer-at (pos)
13169 "Remove an empty drawer at position POS.
13170 POS may also be a marker."
13171 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13172 (org-with-wide-buffer
13173 (goto-char pos)
13174 (let ((drawer (org-element-at-point)))
13175 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13176 (not (org-element-property :contents-begin drawer)))
13177 (delete-region (org-element-property :begin drawer)
13178 (progn (goto-char (org-element-property :end drawer))
13179 (skip-chars-backward " \r\t\n")
13180 (forward-line)
13181 (point))))))))
13183 (defvar org-ts-type nil)
13184 (defun org-sparse-tree (&optional arg type)
13185 "Create a sparse tree, prompt for the details.
13186 This command can create sparse trees. You first need to select the type
13187 of match used to create the tree:
13189 t Show all TODO entries.
13190 T Show entries with a specific TODO keyword.
13191 m Show entries selected by a tags/property match.
13192 p Enter a property name and its value (both with completion on existing
13193 names/values) and show entries with that property.
13194 r Show entries matching a regular expression (`/' can be used as well).
13195 b Show deadlines and scheduled items before a date.
13196 a Show deadlines and scheduled items after a date.
13197 d Show deadlines due within `org-deadline-warning-days'.
13198 D Show deadlines and scheduled items between a date range."
13199 (interactive "P")
13200 (setq type (or type org-sparse-tree-default-date-type))
13201 (setq org-ts-type type)
13202 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13203 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13204 \[c]ycle through date types: %s"
13205 (cl-case type
13206 (all "all timestamps")
13207 (scheduled "only scheduled")
13208 (deadline "only deadline")
13209 (active "only active timestamps")
13210 (inactive "only inactive timestamps")
13211 (closed "with a closed time-stamp")
13212 (otherwise "scheduled/deadline")))
13213 (let ((answer (read-char-exclusive)))
13214 (cl-case answer
13216 (org-sparse-tree
13218 (cadr
13219 (memq type '(nil all scheduled deadline active inactive closed)))))
13220 (?d (call-interactively 'org-check-deadlines))
13221 (?b (call-interactively 'org-check-before-date))
13222 (?a (call-interactively 'org-check-after-date))
13223 (?D (call-interactively 'org-check-dates-range))
13224 (?t (call-interactively 'org-show-todo-tree))
13225 (?T (org-show-todo-tree '(4)))
13226 (?m (call-interactively 'org-match-sparse-tree))
13227 ((?p ?P)
13228 (let* ((kwd (completing-read
13229 "Property: " (mapcar #'list (org-buffer-property-keys))))
13230 (value (completing-read
13231 "Value: " (mapcar #'list (org-property-values kwd)))))
13232 (unless (string-match "\\`{.*}\\'" value)
13233 (setq value (concat "\"" value "\"")))
13234 (org-match-sparse-tree arg (concat kwd "=" value))))
13235 ((?r ?R ?/) (call-interactively 'org-occur))
13236 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13238 (defvar-local org-occur-highlights nil
13239 "List of overlays used for occur matches.")
13240 (defvar-local org-occur-parameters nil
13241 "Parameters of the active org-occur calls.
13242 This is a list, each call to org-occur pushes as cons cell,
13243 containing the regular expression and the callback, onto the list.
13244 The list can contain several entries if `org-occur' has been called
13245 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13246 will only contain one set of parameters. When the highlights are
13247 removed (for example with `C-c C-c', or with the next edit (depending
13248 on `org-remove-highlights-with-change'), this variable is emptied
13249 as well.")
13251 (defun org-occur (regexp &optional keep-previous callback)
13252 "Make a compact tree which shows all matches of REGEXP.
13254 The tree will show the lines where the regexp matches, and any other context
13255 defined in `org-show-context-detail', which see.
13257 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13258 done by a previous call to `org-occur' will be kept, to allow stacking of
13259 calls to this command.
13261 Optional argument CALLBACK can be a function of no argument. In this case,
13262 it is called with point at the end of the match, match data being set
13263 accordingly. Current match is shown only if the return value is non-nil.
13264 The function must neither move point nor alter narrowing."
13265 (interactive "sRegexp: \nP")
13266 (when (equal regexp "")
13267 (user-error "Regexp cannot be empty"))
13268 (unless keep-previous
13269 (org-remove-occur-highlights nil nil t))
13270 (push (cons regexp callback) org-occur-parameters)
13271 (let ((cnt 0))
13272 (save-excursion
13273 (goto-char (point-min))
13274 (when (or (not keep-previous) ; do not want to keep
13275 (not org-occur-highlights)) ; no previous matches
13276 ;; hide everything
13277 (org-overview))
13278 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13279 (isearch-no-upper-case-p regexp t)
13280 org-occur-case-fold-search)))
13281 (while (re-search-forward regexp nil t)
13282 (when (or (not callback)
13283 (save-match-data (funcall callback)))
13284 (setq cnt (1+ cnt))
13285 (when org-highlight-sparse-tree-matches
13286 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13287 (org-show-context 'occur-tree)))))
13288 (when org-remove-highlights-with-change
13289 (add-hook 'before-change-functions 'org-remove-occur-highlights
13290 nil 'local))
13291 (unless org-sparse-tree-open-archived-trees
13292 (org-hide-archived-subtrees (point-min) (point-max)))
13293 (run-hooks 'org-occur-hook)
13294 (when (called-interactively-p 'interactive)
13295 (message "%d match(es) for regexp %s" cnt regexp))
13296 cnt))
13298 (defun org-occur-next-match (&optional n _reset)
13299 "Function for `next-error-function' to find sparse tree matches.
13300 N is the number of matches to move, when negative move backwards.
13301 This function always goes back to the starting point when no
13302 match is found."
13303 (let* ((limit (if (< n 0) (point-min) (point-max)))
13304 (search-func (if (< n 0)
13305 'previous-single-char-property-change
13306 'next-single-char-property-change))
13307 (n (abs n))
13308 (pos (point))
13310 (catch 'exit
13311 (while (setq p1 (funcall search-func (point) 'org-type))
13312 (when (equal p1 limit)
13313 (goto-char pos)
13314 (user-error "No more matches"))
13315 (when (equal (get-char-property p1 'org-type) 'org-occur)
13316 (setq n (1- n))
13317 (when (= n 0)
13318 (goto-char p1)
13319 (throw 'exit (point))))
13320 (goto-char p1))
13321 (goto-char p1)
13322 (user-error "No more matches"))))
13324 (defun org-highlight-new-match (beg end)
13325 "Highlight from BEG to END and mark the highlight is an occur headline."
13326 (let ((ov (make-overlay beg end)))
13327 (overlay-put ov 'face 'secondary-selection)
13328 (overlay-put ov 'org-type 'org-occur)
13329 (push ov org-occur-highlights)))
13331 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13332 "Remove the occur highlights from the buffer.
13333 BEG and END are ignored. If NOREMOVE is nil, remove this function
13334 from the `before-change-functions' in the current buffer."
13335 (interactive)
13336 (unless org-inhibit-highlight-removal
13337 (mapc #'delete-overlay org-occur-highlights)
13338 (setq org-occur-highlights nil)
13339 (setq org-occur-parameters nil)
13340 (unless noremove
13341 (remove-hook 'before-change-functions
13342 'org-remove-occur-highlights 'local))))
13344 ;;;; Priorities
13346 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13347 "Regular expression matching the priority indicator.")
13349 (defvar org-remove-priority-next-time nil)
13351 (defun org-priority-up ()
13352 "Increase the priority of the current item."
13353 (interactive)
13354 (org-priority 'up))
13356 (defun org-priority-down ()
13357 "Decrease the priority of the current item."
13358 (interactive)
13359 (org-priority 'down))
13361 (defun org-priority (&optional action _show)
13362 "Change the priority of an item.
13363 ACTION can be `set', `up', `down', or a character."
13364 (interactive "P")
13365 (if (equal action '(4))
13366 (org-show-priority)
13367 (unless org-enable-priority-commands
13368 (user-error "Priority commands are disabled"))
13369 (setq action (or action 'set))
13370 (let (current new news have remove)
13371 (save-excursion
13372 (org-back-to-heading t)
13373 (when (looking-at org-priority-regexp)
13374 (setq current (string-to-char (match-string 2))
13375 have t))
13376 (cond
13377 ((eq action 'remove)
13378 (setq remove t new ?\ ))
13379 ((or (eq action 'set)
13380 (integerp action))
13381 (if (not (eq action 'set))
13382 (setq new action)
13383 (message "Priority %c-%c, SPC to remove: "
13384 org-highest-priority org-lowest-priority)
13385 (save-match-data
13386 (setq new (read-char-exclusive))))
13387 (when (and (= (upcase org-highest-priority) org-highest-priority)
13388 (= (upcase org-lowest-priority) org-lowest-priority))
13389 (setq new (upcase new)))
13390 (cond ((equal new ?\ ) (setq remove t))
13391 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13392 (user-error "Priority must be between `%c' and `%c'"
13393 org-highest-priority org-lowest-priority))))
13394 ((eq action 'up)
13395 (setq new (if have
13396 (1- current) ; normal cycling
13397 ;; last priority was empty
13398 (if (eq last-command this-command)
13399 org-lowest-priority ; wrap around empty to lowest
13400 ;; default
13401 (if org-priority-start-cycle-with-default
13402 org-default-priority
13403 (1- org-default-priority))))))
13404 ((eq action 'down)
13405 (setq new (if have
13406 (1+ current) ; normal cycling
13407 ;; last priority was empty
13408 (if (eq last-command this-command)
13409 org-highest-priority ; wrap around empty to highest
13410 ;; default
13411 (if org-priority-start-cycle-with-default
13412 org-default-priority
13413 (1+ org-default-priority))))))
13414 (t (user-error "Invalid action")))
13415 (when (or (< (upcase new) org-highest-priority)
13416 (> (upcase new) org-lowest-priority))
13417 (if (and (memq action '(up down))
13418 (not have) (not (eq last-command this-command)))
13419 ;; `new' is from default priority
13420 (error
13421 "The default can not be set, see `org-default-priority' why")
13422 ;; normal cycling: `new' is beyond highest/lowest priority
13423 ;; and is wrapped around to the empty priority
13424 (setq remove t)))
13425 (setq news (format "%c" new))
13426 (if have
13427 (if remove
13428 (replace-match "" t t nil 1)
13429 (replace-match news t t nil 2))
13430 (if remove
13431 (user-error "No priority cookie found in line")
13432 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13433 (if (match-end 2)
13434 (progn
13435 (goto-char (match-end 2))
13436 (insert " [#" news "]"))
13437 (goto-char (match-beginning 3))
13438 (insert "[#" news "] "))))
13439 (org-set-tags nil 'align))
13440 (if remove
13441 (message "Priority removed")
13442 (message "Priority of current item set to %s" news)))))
13444 (defun org-show-priority ()
13445 "Show the priority of the current item.
13446 This priority is composed of the main priority given with the [#A] cookies,
13447 and by additional input from the age of a schedules or deadline entry."
13448 (interactive)
13449 (let ((pri (if (eq major-mode 'org-agenda-mode)
13450 (org-get-at-bol 'priority)
13451 (save-excursion
13452 (save-match-data
13453 (beginning-of-line)
13454 (and (looking-at org-heading-regexp)
13455 (org-get-priority (match-string 0))))))))
13456 (message "Priority is %d" (if pri pri -1000))))
13458 (defun org-get-priority (s)
13459 "Find priority cookie and return priority."
13460 (save-match-data
13461 (if (functionp org-get-priority-function)
13462 (funcall org-get-priority-function)
13463 (if (not (string-match org-priority-regexp s))
13464 (* 1000 (- org-lowest-priority org-default-priority))
13465 (* 1000 (- org-lowest-priority
13466 (string-to-char (match-string 2 s))))))))
13468 ;;;; Tags
13470 (defvar org-agenda-archives-mode)
13471 (defvar org-map-continue-from nil
13472 "Position from where mapping should continue.
13473 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13475 (defvar org-scanner-tags nil
13476 "The current tag list while the tags scanner is running.")
13478 (defvar org-trust-scanner-tags nil
13479 "Should `org-get-tags-at' use the tags for the scanner.
13480 This is for internal dynamical scoping only.
13481 When this is non-nil, the function `org-get-tags-at' will return the value
13482 of `org-scanner-tags' instead of building the list by itself. This
13483 can lead to large speed-ups when the tags scanner is used in a file with
13484 many entries, and when the list of tags is retrieved, for example to
13485 obtain a list of properties. Building the tags list for each entry in such
13486 a file becomes an N^2 operation - but with this variable set, it scales
13487 as N.")
13489 (defvar org--matcher-tags-todo-only nil)
13491 (defun org-scan-tags (action matcher todo-only &optional start-level)
13492 "Scan headline tags with inheritance and produce output ACTION.
13494 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13495 or `agenda' to produce an entry list for an agenda view. It can also be
13496 a Lisp form or a function that should be called at each matched headline, in
13497 this case the return value is a list of all return values from these calls.
13499 MATCHER is a function accepting three arguments, returning
13500 a non-nil value whenever a given set of tags qualifies a headline
13501 for inclusion. See `org-make-tags-matcher' for more information.
13502 As a special case, it can also be set to t (respectively nil) in
13503 order to match all (respectively none) headline.
13505 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13506 included in the output.
13508 START-LEVEL can be a string with asterisks, reducing the scope to
13509 headlines matching this string."
13510 (require 'org-agenda)
13511 (let* ((re (concat "^"
13512 (if start-level
13513 ;; Get the correct level to match
13514 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13515 org-outline-regexp)
13516 " *\\(\\<\\("
13517 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13518 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13519 (props (list 'face 'default
13520 'done-face 'org-agenda-done
13521 'undone-face 'default
13522 'mouse-face 'highlight
13523 'org-not-done-regexp org-not-done-regexp
13524 'org-todo-regexp org-todo-regexp
13525 'org-complex-heading-regexp org-complex-heading-regexp
13526 'help-echo
13527 (format "mouse-2 or RET jump to Org file %S"
13528 (abbreviate-file-name
13529 (or (buffer-file-name (buffer-base-buffer))
13530 (buffer-name (buffer-base-buffer)))))))
13531 (org-map-continue-from nil)
13532 lspos tags tags-list
13533 (tags-alist (list (cons 0 org-file-tags)))
13534 (llast 0) rtn rtn1 level category i txt
13535 todo marker entry priority
13536 ts-date ts-date-type ts-date-pair)
13537 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13538 (setq action (list 'lambda nil action)))
13539 (save-excursion
13540 (goto-char (point-min))
13541 (when (eq action 'sparse-tree)
13542 (org-overview)
13543 (org-remove-occur-highlights))
13544 (while (let (case-fold-search)
13545 (re-search-forward re nil t))
13546 (setq org-map-continue-from nil)
13547 (catch :skip
13548 (setq todo
13549 ;; TODO: is the 1-2 difference a bug?
13550 (when (match-end 1) (match-string-no-properties 2))
13551 tags (when (match-end 4) (match-string-no-properties 4)))
13552 (goto-char (setq lspos (match-beginning 0)))
13553 (setq level (org-reduced-level (org-outline-level))
13554 category (org-get-category))
13555 (when (eq action 'agenda)
13556 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13557 ts-date (car ts-date-pair)
13558 ts-date-type (cdr ts-date-pair)))
13559 (setq i llast llast level)
13560 ;; remove tag lists from same and sublevels
13561 (while (>= i level)
13562 (when (setq entry (assoc i tags-alist))
13563 (setq tags-alist (delete entry tags-alist)))
13564 (setq i (1- i)))
13565 ;; add the next tags
13566 (when tags
13567 (setq tags (org-split-string tags ":")
13568 tags-alist
13569 (cons (cons level tags) tags-alist)))
13570 ;; compile tags for current headline
13571 (setq tags-list
13572 (if org-use-tag-inheritance
13573 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13574 tags)
13575 org-scanner-tags tags-list)
13576 (when org-use-tag-inheritance
13577 (setcdr (car tags-alist)
13578 (mapcar (lambda (x)
13579 (setq x (copy-sequence x))
13580 (org-add-prop-inherited x))
13581 (cdar tags-alist))))
13582 (when (and tags org-use-tag-inheritance
13583 (or (not (eq t org-use-tag-inheritance))
13584 org-tags-exclude-from-inheritance))
13585 ;; Selective inheritance, remove uninherited ones.
13586 (setcdr (car tags-alist)
13587 (org-remove-uninherited-tags (cdar tags-alist))))
13588 (when (and
13590 ;; eval matcher only when the todo condition is OK
13591 (and (or (not todo-only) (member todo org-todo-keywords-1))
13592 (if (functionp matcher)
13593 (let ((case-fold-search t) (org-trust-scanner-tags t))
13594 (funcall matcher todo tags-list level))
13595 matcher))
13597 ;; Call the skipper, but return t if it does not
13598 ;; skip, so that the `and' form continues evaluating.
13599 (progn
13600 (unless (eq action 'sparse-tree) (org-agenda-skip))
13603 ;; Check if timestamps are deselecting this entry
13604 (or (not todo-only)
13605 (and (member todo org-todo-keywords-1)
13606 (or (not org-agenda-tags-todo-honor-ignore-options)
13607 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13609 ;; select this headline
13610 (cond
13611 ((eq action 'sparse-tree)
13612 (and org-highlight-sparse-tree-matches
13613 (org-get-heading) (match-end 0)
13614 (org-highlight-new-match
13615 (match-beginning 1) (match-end 1)))
13616 (org-show-context 'tags-tree))
13617 ((eq action 'agenda)
13618 (setq txt (org-agenda-format-item
13620 (concat
13621 (if (eq org-tags-match-list-sublevels 'indented)
13622 (make-string (1- level) ?.) "")
13623 (org-get-heading))
13624 (make-string level ?\s)
13625 category
13626 tags-list)
13627 priority (org-get-priority txt))
13628 (goto-char lspos)
13629 (setq marker (org-agenda-new-marker))
13630 (org-add-props txt props
13631 'org-marker marker 'org-hd-marker marker 'org-category category
13632 'todo-state todo
13633 'ts-date ts-date
13634 'priority priority
13635 'type (concat "tagsmatch" ts-date-type))
13636 (push txt rtn))
13637 ((functionp action)
13638 (setq org-map-continue-from nil)
13639 (save-excursion
13640 (setq rtn1 (funcall action))
13641 (push rtn1 rtn)))
13642 (t (user-error "Invalid action")))
13644 ;; if we are to skip sublevels, jump to end of subtree
13645 (unless org-tags-match-list-sublevels
13646 (org-end-of-subtree t)
13647 (backward-char 1))))
13648 ;; Get the correct position from where to continue
13649 (if org-map-continue-from
13650 (goto-char org-map-continue-from)
13651 (and (= (point) lspos) (end-of-line 1)))))
13652 (when (and (eq action 'sparse-tree)
13653 (not org-sparse-tree-open-archived-trees))
13654 (org-hide-archived-subtrees (point-min) (point-max)))
13655 (nreverse rtn)))
13657 (defun org-remove-uninherited-tags (tags)
13658 "Remove all tags that are not inherited from the list TAGS."
13659 (cond
13660 ((eq org-use-tag-inheritance t)
13661 (if org-tags-exclude-from-inheritance
13662 (org-delete-all org-tags-exclude-from-inheritance tags)
13663 tags))
13664 ((not org-use-tag-inheritance) nil)
13665 ((stringp org-use-tag-inheritance)
13666 (delq nil (mapcar
13667 (lambda (x)
13668 (if (and (string-match org-use-tag-inheritance x)
13669 (not (member x org-tags-exclude-from-inheritance)))
13670 x nil))
13671 tags)))
13672 ((listp org-use-tag-inheritance)
13673 (delq nil (mapcar
13674 (lambda (x)
13675 (if (member x org-use-tag-inheritance) x nil))
13676 tags)))))
13678 (defun org-match-sparse-tree (&optional todo-only match)
13679 "Create a sparse tree according to tags string MATCH.
13681 MATCH is a string with match syntax. It can contain a selection
13682 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13683 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13684 those. See the manual for details.
13686 If optional argument TODO-ONLY is non-nil, only select lines that
13687 are also TODO tasks."
13688 (interactive "P")
13689 (org-agenda-prepare-buffers (list (current-buffer)))
13690 (let ((org--matcher-tags-todo-only todo-only))
13691 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13692 org--matcher-tags-todo-only)))
13694 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13696 (defvar org-cached-props nil)
13697 (defun org-cached-entry-get (pom property)
13698 (if (or (eq t org-use-property-inheritance)
13699 (and (stringp org-use-property-inheritance)
13700 (let ((case-fold-search t))
13701 (string-match-p org-use-property-inheritance property)))
13702 (and (listp org-use-property-inheritance)
13703 (member-ignore-case property org-use-property-inheritance)))
13704 ;; Caching is not possible, check it directly.
13705 (org-entry-get pom property 'inherit)
13706 ;; Get all properties, so we can do complicated checks easily.
13707 (cdr (assoc-string property
13708 (or org-cached-props
13709 (setq org-cached-props (org-entry-properties pom)))
13710 t))))
13712 (defun org-global-tags-completion-table (&optional files)
13713 "Return the list of all tags in all agenda buffer/files.
13714 Optional FILES argument is a list of files which can be used
13715 instead of the agenda files."
13716 (save-excursion
13717 (org-uniquify
13718 (delq nil
13719 (apply #'append
13720 (mapcar
13721 (lambda (file)
13722 (set-buffer (find-file-noselect file))
13723 (mapcar (lambda (x)
13724 (and (stringp (car-safe x))
13725 (list (car-safe x))))
13726 (or org-current-tag-alist (org-get-buffer-tags))))
13727 (if (car-safe files) files
13728 (org-agenda-files))))))))
13730 (defun org-make-tags-matcher (match)
13731 "Create the TAGS/TODO matcher form for the selection string MATCH.
13733 Returns a cons of the selection string MATCH and a function
13734 implementing the matcher.
13736 The matcher is to be called at an Org entry, with point on the
13737 headline, and returns non-nil if the entry matches the selection
13738 string MATCH. It must be called with three arguments: the TODO
13739 keyword at the entry (or nil if none), the list of all tags at
13740 the entry including inherited ones and the reduced level of the
13741 headline. Additionally, the category of the entry, if any, must
13742 be specified as the text property `org-category' on the headline.
13744 This function sets the variable `org--matcher-tags-todo-only' to
13745 a non-nil value if the matcher restricts matching to TODO
13746 entries, otherwise it is not touched.
13748 See also `org-scan-tags'."
13749 (unless match
13750 ;; Get a new match request, with completion against the global
13751 ;; tags table and the local tags in current buffer.
13752 (let ((org-last-tags-completion-table
13753 (org-uniquify
13754 (delq nil (append (org-get-buffer-tags)
13755 (org-global-tags-completion-table))))))
13756 (setq match
13757 (completing-read
13758 "Match: "
13759 'org-tags-completion-function nil nil nil 'org-tags-history))))
13761 (let ((match0 match)
13762 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
13763 (start 0)
13764 tagsmatch todomatch tagsmatcher todomatcher)
13766 ;; Expand group tags.
13767 (setq match (org-tags-expand match))
13769 ;; Check if there is a TODO part of this match, which would be the
13770 ;; part after a "/". To make sure that this slash is not part of
13771 ;; a property value to be matched against, we also check that
13772 ;; there is no / after that slash. First, find the last slash.
13773 (let ((s 0))
13774 (while (string-match "/+" match s)
13775 (setq start (match-beginning 0))
13776 (setq s (match-end 0))))
13777 (if (and (string-match "/+" match start)
13778 (not (string-match-p "\"" match start)))
13779 ;; Match contains also a TODO-matching request.
13780 (progn
13781 (setq tagsmatch (substring match 0 (match-beginning 0)))
13782 (setq todomatch (substring match (match-end 0)))
13783 (when (string-prefix-p "!" todomatch)
13784 (setq org--matcher-tags-todo-only t)
13785 (setq todomatch (substring todomatch 1)))
13786 (when (string-match "\\`\\s-*\\'" todomatch)
13787 (setq todomatch nil)))
13788 ;; Only matching tags.
13789 (setq tagsmatch match)
13790 (setq todomatch nil))
13792 ;; Make the tags matcher.
13793 (when (org-string-nw-p tagsmatch)
13794 (let ((orlist nil)
13795 (orterms (org-split-string tagsmatch "|"))
13796 term)
13797 (while (setq term (pop orterms))
13798 (while (and (equal (substring term -1) "\\") orterms)
13799 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13800 (while (string-match re term)
13801 (let* ((rest (substring term (match-end 0)))
13802 (minus (and (match-end 1)
13803 (equal (match-string 1 term) "-")))
13804 (tag (save-match-data
13805 (replace-regexp-in-string
13806 "\\\\-" "-" (match-string 2 term))))
13807 (regexp (eq (string-to-char tag) ?{))
13808 (levelp (match-end 4))
13809 (propp (match-end 5))
13811 (cond
13812 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13813 (levelp
13814 `(,(org-op-to-function (match-string 3 term))
13815 level
13816 ,(string-to-number (match-string 4 term))))
13817 (propp
13818 (let* ((gv (pcase (upcase (match-string 5 term))
13819 ("CATEGORY"
13820 '(get-text-property (point) 'org-category))
13821 ("TODO" 'todo)
13822 (p `(org-cached-entry-get nil ,p))))
13823 (pv (match-string 7 term))
13824 (regexp (eq (string-to-char pv) ?{))
13825 (strp (eq (string-to-char pv) ?\"))
13826 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13827 (po (org-op-to-function (match-string 6 term)
13828 (if timep 'time strp))))
13829 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13830 (when timep (setq pv (org-matcher-time pv)))
13831 (cond ((and regexp (eq po 'org<>))
13832 `(not (string-match ,pv (or ,gv ""))))
13833 (regexp `(string-match ,pv (or ,gv "")))
13834 (strp `(,po (or ,gv "") ,pv))
13836 `(,po
13837 (string-to-number (or ,gv ""))
13838 ,(string-to-number pv))))))
13839 (t `(member ,tag tags-list)))))
13840 (push (if minus `(not ,mm) mm) tagsmatcher)
13841 (setq term rest)))
13842 (push `(and ,@tagsmatcher) orlist)
13843 (setq tagsmatcher nil))
13844 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13846 ;; Make the TODO matcher.
13847 (when (org-string-nw-p todomatch)
13848 (let ((orlist nil))
13849 (dolist (term (org-split-string todomatch "|"))
13850 (while (string-match re term)
13851 (let* ((minus (and (match-end 1)
13852 (equal (match-string 1 term) "-")))
13853 (kwd (match-string 2 term))
13854 (regexp (eq (string-to-char kwd) ?{))
13855 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13856 `(equal todo ,kwd))))
13857 (push (if minus `(not ,mm) mm) todomatcher))
13858 (setq term (substring term (match-end 0))))
13859 (push (if (> (length todomatcher) 1)
13860 (cons 'and todomatcher)
13861 (car todomatcher))
13862 orlist)
13863 (setq todomatcher nil))
13864 (setq todomatcher (cons 'or orlist))))
13866 ;; Return the string and function of the matcher. If no
13867 ;; tags-specific or todo-specific matcher exists, match
13868 ;; everything.
13869 (let ((matcher (if (and tagsmatcher todomatcher)
13870 `(and ,tagsmatcher ,todomatcher)
13871 (or tagsmatcher todomatcher t))))
13872 (when org--matcher-tags-todo-only
13873 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
13874 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
13876 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
13877 "Expand group tags in MATCH.
13879 This replaces every group tag in MATCH with a regexp tag search.
13880 For example, a group tag \"Work\" defined as { Work : Lab Conf }
13881 will be replaced like this:
13883 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13884 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13885 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13887 Replacing by a regexp preserves the structure of the match.
13888 E.g., this expansion
13890 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
13892 will match anything tagged with \"Lab\" and \"Home\", or tagged
13893 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
13895 A group tag in MATCH can contain regular expressions of its own.
13896 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
13897 will be replaced like this:
13899 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
13901 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
13902 assumed to be a single group tag, and the function will return
13903 the list of tags in this group.
13905 When DOWNCASE is non-nil, expand downcased TAGS."
13906 (if org-group-tags
13907 (let* ((case-fold-search t)
13908 (stable org-mode-syntax-table)
13909 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
13910 (taggroups (if downcased
13911 (mapcar (lambda (tg) (mapcar #'downcase tg))
13912 taggroups)
13913 taggroups))
13914 (taggroups-keys (mapcar #'car taggroups))
13915 (return-match (if downcased (downcase match) match))
13916 (count 0)
13917 (work-already-expanded tags-already-expanded)
13918 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
13919 ;; @ and _ are allowed as word-components in tags.
13920 (modify-syntax-entry ?@ "w" stable)
13921 (modify-syntax-entry ?_ "w" stable)
13922 ;; Temporarily replace regexp-expressions in the match-expression.
13923 (while (string-match "{.+?}" return-match)
13924 (cl-incf count)
13925 (push (match-string 0 return-match) regexps-in-match)
13926 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
13927 (while (and taggroups-keys
13928 (with-syntax-table stable
13929 (string-match
13930 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
13931 (regexp-opt taggroups-keys) "\\>\\)")
13932 return-match)))
13933 (let* ((dir (match-string 1 return-match))
13934 (tag (match-string 2 return-match))
13935 (tag (if downcased (downcase tag) tag)))
13936 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
13937 (member tag work-already-expanded))
13938 (setq tags-in-group (assoc tag taggroups))
13939 (push tag work-already-expanded)
13940 ;; Recursively expand each tag in the group, if the tag hasn't
13941 ;; already been expanded. Restore the match-data after all recursive calls.
13942 (save-match-data
13943 (let (tags-expanded)
13944 (dolist (x (cdr tags-in-group))
13945 (if (and (member x taggroups-keys)
13946 (not (member x work-already-expanded)))
13947 (setq tags-expanded
13948 (delete-dups
13949 (append
13950 (org-tags-expand x t downcased
13951 work-already-expanded)
13952 tags-expanded)))
13953 (setq tags-expanded
13954 (append (list x) tags-expanded)))
13955 (setq work-already-expanded
13956 (delete-dups
13957 (append tags-expanded
13958 work-already-expanded))))
13959 (setq tags-in-group
13960 (delete-dups (cons (car tags-in-group)
13961 tags-expanded)))))
13962 ;; Filter tag-regexps from tags.
13963 (setq regexp-in-group-escaped
13964 (delq nil (mapcar (lambda (x)
13965 (if (stringp x)
13966 (and (equal "{" (substring x 0 1))
13967 (equal "}" (substring x -1))
13970 tags-in-group))
13971 regexp-in-group
13972 (mapcar (lambda (x)
13973 (substring x 1 -1))
13974 regexp-in-group-escaped)
13975 tags-in-group
13976 (delq nil (mapcar (lambda (x)
13977 (if (stringp x)
13978 (and (not (equal "{" (substring x 0 1)))
13979 (not (equal "}" (substring x -1)))
13982 tags-in-group)))
13983 ;; If single-as-list, do no more in the while-loop.
13984 (if (not single-as-list)
13985 (progn
13986 (when regexp-in-group
13987 (setq regexp-in-group
13988 (concat "\\|"
13989 (mapconcat 'identity regexp-in-group
13990 "\\|"))))
13991 (setq tags-in-group
13992 (concat dir
13993 "{\\<"
13994 (regexp-opt tags-in-group)
13995 "\\>"
13996 regexp-in-group
13997 "}"))
13998 (when (stringp tags-in-group)
13999 (org-add-props tags-in-group '(grouptag t)))
14000 (setq return-match
14001 (replace-match tags-in-group t t return-match)))
14002 (setq tags-in-group
14003 (append regexp-in-group-escaped tags-in-group))))
14004 (setq taggroups-keys (delete tag taggroups-keys))))
14005 ;; Add the regular expressions back into the match-expression again.
14006 (while regexps-in-match
14007 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14008 (pop regexps-in-match)
14009 return-match t t))
14010 (cl-decf count))
14011 (if single-as-list
14012 (if tags-in-group tags-in-group (list return-match))
14013 return-match))
14014 (if single-as-list
14015 (list (if downcased (downcase match) match))
14016 match)))
14018 (defun org-op-to-function (op &optional stringp)
14019 "Turn an operator into the appropriate function."
14020 (setq op
14021 (cond
14022 ((equal op "<" ) '(< string< org-time<))
14023 ((equal op ">" ) '(> org-string> org-time>))
14024 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14025 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14026 ((member op '("=" "==")) '(= string= org-time=))
14027 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14028 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14030 (defun org<> (a b) (not (= a b)))
14031 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14032 (defun org-string>= (a b) (not (string< a b)))
14033 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14034 (defun org-string<> (a b) (not (string= a b)))
14035 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14036 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14037 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14038 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14039 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14040 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14041 (defun org-2ft (s)
14042 "Convert S to a floating point time.
14043 If S is already a number, just return it. If it is a string, parse
14044 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14045 (cond
14046 ((numberp s) s)
14047 ((stringp s)
14048 (condition-case nil
14049 (float-time (apply #'encode-time (org-parse-time-string s)))
14050 (error 0.)))
14051 (t 0.)))
14053 (defun org-time-today ()
14054 "Time in seconds today at 0:00.
14055 Returns the float number of seconds since the beginning of the
14056 epoch to the beginning of today (00:00)."
14057 (float-time (apply 'encode-time
14058 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14060 (defun org-matcher-time (s)
14061 "Interpret a time comparison value."
14062 (save-match-data
14063 (cond
14064 ((string= s "<now>") (float-time))
14065 ((string= s "<today>") (org-time-today))
14066 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14067 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14068 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14069 (+ (org-time-today)
14070 (* (string-to-number (match-string 1 s))
14071 (cdr (assoc (match-string 2 s)
14072 '(("d" . 86400.0) ("w" . 604800.0)
14073 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14074 (t (org-2ft s)))))
14076 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14077 (defvar org-tags-overlay (make-overlay 1 1))
14078 (delete-overlay org-tags-overlay)
14080 (defun org-get-local-tags-at (&optional pos)
14081 "Get a list of tags defined in the current headline."
14082 (org-get-tags-at pos 'local))
14084 (defun org-get-local-tags ()
14085 "Get a list of tags defined in the current headline."
14086 (org-get-tags-at nil 'local))
14088 (defun org-get-tags-at (&optional pos local)
14089 "Get a list of all headline tags applicable at POS.
14090 POS defaults to point. If tags are inherited, the list contains
14091 the targets in the same sequence as the headlines appear, i.e.
14092 the tags of the current headline come last.
14093 When LOCAL is non-nil, only return tags from the current headline,
14094 ignore inherited ones."
14095 (interactive)
14096 (if (and org-trust-scanner-tags
14097 (or (not pos) (equal pos (point)))
14098 (not local))
14099 org-scanner-tags
14100 (let (tags ltags lastpos parent)
14101 (save-excursion
14102 (save-restriction
14103 (widen)
14104 (goto-char (or pos (point)))
14105 (save-match-data
14106 (catch 'done
14107 (condition-case nil
14108 (progn
14109 (org-back-to-heading t)
14110 (while (not (equal lastpos (point)))
14111 (setq lastpos (point))
14112 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14113 (setq ltags (org-split-string
14114 (match-string-no-properties 1) ":"))
14115 (when parent
14116 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14117 (setq tags (append
14118 (if parent
14119 (org-remove-uninherited-tags ltags)
14120 ltags)
14121 tags)))
14122 (or org-use-tag-inheritance (throw 'done t))
14123 (when local (throw 'done t))
14124 (or (org-up-heading-safe) (error nil))
14125 (setq parent t)))
14126 (error nil)))))
14127 (if local
14128 tags
14129 (reverse (delete-dups
14130 (reverse (append
14131 (org-remove-uninherited-tags
14132 org-file-tags)
14133 tags)))))))))
14135 (defun org-add-prop-inherited (s)
14136 (add-text-properties 0 (length s) '(inherited t) s)
14139 (defun org-toggle-tag (tag &optional onoff)
14140 "Toggle the tag TAG for the current line.
14141 If ONOFF is `on' or `off', don't toggle but set to this state."
14142 (save-excursion
14143 (org-back-to-heading t)
14144 (let ((current
14145 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14146 (line-end-position) t)
14147 (let ((tags (match-string 1)))
14148 ;; Clear current tags.
14149 (replace-match "")
14150 ;; Reverse the tags list so any new tag is appended to
14151 ;; the current list of tags.
14152 (nreverse (org-split-string tags ":")))))
14153 res)
14154 (pcase onoff
14155 (`off (setq current (delete tag current)))
14156 ((or `on (guard (not (member tag current))))
14157 (setq res t)
14158 (cl-pushnew tag current :test #'equal))
14159 (_ (setq current (delete tag current))))
14160 (end-of-line)
14161 (if current
14162 (progn
14163 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14164 (org-set-tags nil t))
14165 (delete-horizontal-space))
14166 (run-hooks 'org-after-tags-change-hook)
14167 res)))
14169 (defun org--align-tags-here (to-col)
14170 "Align tags on the current headline to TO-COL.
14171 Assume point is on a headline."
14172 (let ((pos (point)))
14173 (beginning-of-line)
14174 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14175 (>= pos (match-beginning 2)))
14176 ;; No tags or point within tags: do not align.
14177 (goto-char pos)
14178 (goto-char (match-beginning 1))
14179 (let ((shift (max (- (if (>= to-col 0) to-col
14180 (- (abs to-col) (string-width (match-string 2))))
14181 (current-column))
14182 1)))
14183 (replace-match (make-string shift ?\s) nil nil nil 1)
14184 ;; Preserve initial position, if possible. In any case, stop
14185 ;; before tags.
14186 (when (< pos (point)) (goto-char pos))))))
14188 (defun org-set-tags-command (&optional arg just-align)
14189 "Call the set-tags command for the current entry."
14190 (interactive "P")
14191 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14192 (org-set-tags arg just-align)
14193 (save-excursion
14194 (unless (and (org-region-active-p)
14195 org-loop-over-headlines-in-active-region)
14196 (org-back-to-heading t))
14197 (org-set-tags arg just-align))))
14199 (defun org-set-tags-to (data)
14200 "Set the tags of the current entry to DATA, replacing the current tags.
14201 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14202 If DATA is nil or the empty string, any tags will be removed."
14203 (interactive "sTags: ")
14204 (setq data
14205 (cond
14206 ((eq data nil) "")
14207 ((equal data "") "")
14208 ((stringp data)
14209 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14210 ":"))
14211 ((listp data)
14212 (concat ":" (mapconcat 'identity data ":") ":"))))
14213 (when data
14214 (save-excursion
14215 (org-back-to-heading t)
14216 (when (let ((case-fold-search nil))
14217 (looking-at org-complex-heading-regexp))
14218 (if (match-end 5)
14219 (progn
14220 (goto-char (match-beginning 5))
14221 (insert data)
14222 (delete-region (point) (point-at-eol))
14223 (org-set-tags nil 'align))
14224 (goto-char (point-at-eol))
14225 (insert " " data)
14226 (org-set-tags nil 'align)))
14227 (beginning-of-line 1)
14228 (when (looking-at ".*?\\([ \t]+\\)$")
14229 (delete-region (match-beginning 1) (match-end 1))))))
14231 (defun org-align-all-tags ()
14232 "Align the tags in all headings."
14233 (interactive)
14234 (save-excursion
14235 (or (ignore-errors (org-back-to-heading t))
14236 (outline-next-heading))
14237 (if (org-at-heading-p)
14238 (org-set-tags t)
14239 (message "No headings"))))
14241 (defvar org-indent-indentation-per-level)
14242 (defun org-set-tags (&optional arg just-align)
14243 "Set the tags for the current headline.
14244 With prefix ARG, realign all tags in headings in the current buffer.
14245 When JUST-ALIGN is non-nil, only align tags."
14246 (interactive "P")
14247 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14248 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14249 'region-start-level
14250 'region))
14251 org-loop-over-headlines-in-active-region)
14252 (org-map-entries
14253 ;; We don't use ARG and JUST-ALIGN here because these args
14254 ;; are not useful when looping over headlines.
14255 #'org-set-tags
14256 org-loop-over-headlines-in-active-region
14258 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14259 (let ((org-setting-tags t))
14260 (if arg
14261 (save-excursion
14262 (goto-char (point-min))
14263 (while (re-search-forward org-outline-regexp-bol nil t)
14264 (org-set-tags nil t)
14265 (end-of-line))
14266 (message "All tags realigned to column %d" org-tags-column))
14267 (let* ((current (org-get-tags-string))
14268 (tags
14269 (if just-align current
14270 ;; Get a new set of tags from the user.
14271 (save-excursion
14272 (let* ((seen)
14273 (table
14274 (setq
14275 org-last-tags-completion-table
14276 ;; Uniquify tags in alists, yet preserve
14277 ;; structure (i.e., keywords).
14278 (delq nil
14279 (mapcar
14280 (lambda (pair)
14281 (let ((head (car pair)))
14282 (cond ((symbolp head) pair)
14283 ((member head seen) nil)
14284 (t (push head seen)
14285 pair))))
14286 (append
14287 (or org-current-tag-alist
14288 (org-get-buffer-tags))
14289 (and
14290 org-complete-tags-always-offer-all-agenda-tags
14291 (org-global-tags-completion-table
14292 (org-agenda-files))))))))
14293 (current-tags (org-split-string current ":"))
14294 (inherited-tags
14295 (nreverse (nthcdr (length current-tags)
14296 (nreverse (org-get-tags-at))))))
14297 (replace-regexp-in-string
14298 "\\([-+&]+\\|,\\)"
14300 (if (or (eq t org-use-fast-tag-selection)
14301 (and org-use-fast-tag-selection
14302 (delq nil (mapcar #'cdr table))))
14303 (org-fast-tag-selection
14304 current-tags inherited-tags table
14305 (and org-fast-tag-selection-include-todo
14306 org-todo-key-alist))
14307 (let ((org-add-colon-after-tag-completion
14308 (< 1 (length table))))
14309 (org-trim
14310 (completing-read
14311 "Tags: "
14312 #'org-tags-completion-function
14313 nil nil current 'org-tags-history))))))))))
14315 (when org-tags-sort-function
14316 (setq tags
14317 (mapconcat
14318 #'identity
14319 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14320 org-tags-sort-function)
14321 ":")))
14323 (if (or (string= ":" tags)
14324 (string= "::" tags))
14325 (setq tags ""))
14326 (if (not (org-string-nw-p tags)) (setq tags "")
14327 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14328 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14330 ;; Insert new tags at the correct column.
14331 (unless (equal current tags)
14332 (save-excursion
14333 (beginning-of-line)
14334 (let ((case-fold-search nil))
14335 (looking-at org-complex-heading-regexp))
14336 ;; Remove current tags, if any.
14337 (when (match-end 5) (replace-match "" nil nil nil 5))
14338 ;; Insert new tags, if any. Otherwise, remove trailing
14339 ;; white spaces.
14340 (end-of-line)
14341 (if (not (equal tags ""))
14342 ;; When text is being inserted on an invisible
14343 ;; region boundary, it can be inadvertently sucked
14344 ;; into invisibility.
14345 (org-flag-region (point) (progn (insert " " tags) (point))
14347 'outline)
14348 (skip-chars-backward " \t")
14349 (delete-region (point) (line-end-position)))))
14350 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14351 ;; is on.
14352 (unless (equal tags "")
14353 (let* ((level (save-excursion
14354 (beginning-of-line)
14355 (skip-chars-forward "\\*")))
14356 (offset (if (bound-and-true-p org-indent-mode)
14357 (* (1- org-indent-indentation-per-level)
14358 (1- level))
14360 (tags-column
14361 (+ org-tags-column
14362 (if (> org-tags-column 0) (- offset) offset))))
14363 (org--align-tags-here tags-column))))
14364 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14366 (defun org-change-tag-in-region (beg end tag off)
14367 "Add or remove TAG for each entry in the region.
14368 This works in the agenda, and also in an Org buffer."
14369 (interactive
14370 (list (region-beginning) (region-end)
14371 (let ((org-last-tags-completion-table
14372 (if (derived-mode-p 'org-mode)
14373 (org-uniquify
14374 (delq nil (append (org-get-buffer-tags)
14375 (org-global-tags-completion-table))))
14376 (org-global-tags-completion-table))))
14377 (completing-read
14378 "Tag: " 'org-tags-completion-function nil nil nil
14379 'org-tags-history))
14380 (progn
14381 (message "[s]et or [r]emove? ")
14382 (equal (read-char-exclusive) ?r))))
14383 (when (fboundp 'deactivate-mark) (deactivate-mark))
14384 (let ((agendap (equal major-mode 'org-agenda-mode))
14385 l1 l2 m buf pos newhead (cnt 0))
14386 (goto-char end)
14387 (setq l2 (1- (org-current-line)))
14388 (goto-char beg)
14389 (setq l1 (org-current-line))
14390 (cl-loop for l from l1 to l2 do
14391 (org-goto-line l)
14392 (setq m (get-text-property (point) 'org-hd-marker))
14393 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14394 (and agendap m))
14395 (setq buf (if agendap (marker-buffer m) (current-buffer))
14396 pos (if agendap m (point)))
14397 (with-current-buffer buf
14398 (save-excursion
14399 (save-restriction
14400 (goto-char pos)
14401 (setq cnt (1+ cnt))
14402 (org-toggle-tag tag (if off 'off 'on))
14403 (setq newhead (org-get-heading)))))
14404 (and agendap (org-agenda-change-all-lines newhead m))))
14405 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14407 (defun org-tags-completion-function (string _predicate &optional flag)
14408 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14409 (confirm (lambda (x) (stringp (car x)))))
14410 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14411 (setq s1 (match-string 1 string)
14412 s2 (match-string 2 string))
14413 (setq s1 "" s2 string))
14414 (cond
14415 ((eq flag nil)
14416 ;; try completion
14417 (setq rtn (try-completion s2 ctable confirm))
14418 (when (stringp rtn)
14419 (setq rtn
14420 (concat s1 s2 (substring rtn (length s2))
14421 (if (and org-add-colon-after-tag-completion
14422 (assoc rtn ctable))
14423 ":" ""))))
14424 rtn)
14425 ((eq flag t)
14426 ;; all-completions
14427 (all-completions s2 ctable confirm))
14428 ((eq flag 'lambda)
14429 ;; exact match?
14430 (assoc s2 ctable)))))
14432 (defun org-fast-tag-insert (kwd tags face &optional end)
14433 "Insert KDW, and the TAGS, the latter with face FACE.
14434 Also insert END."
14435 (insert (format "%-12s" (concat kwd ":"))
14436 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14437 (or end "")))
14439 (defun org-fast-tag-show-exit (flag)
14440 (save-excursion
14441 (org-goto-line 3)
14442 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14443 (replace-match ""))
14444 (when flag
14445 (end-of-line 1)
14446 (org-move-to-column (- (window-width) 19) t)
14447 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14449 (defun org-set-current-tags-overlay (current prefix)
14450 "Add an overlay to CURRENT tag with PREFIX."
14451 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14452 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14453 (org-overlay-display org-tags-overlay (concat prefix s))))
14455 (defvar org-last-tag-selection-key nil)
14456 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14457 "Fast tag selection with single keys.
14458 CURRENT is the current list of tags in the headline, INHERITED is the
14459 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14460 possibly with grouping information. TODO-TABLE is a similar table with
14461 TODO keywords, should these have keys assigned to them.
14462 If the keys are nil, a-z are automatically assigned.
14463 Returns the new tags string, or nil to not change the current settings."
14464 (let* ((fulltable (append table todo-table))
14465 (maxlen (apply 'max (mapcar
14466 (lambda (x)
14467 (if (stringp (car x)) (string-width (car x)) 0))
14468 fulltable)))
14469 (buf (current-buffer))
14470 (expert (eq org-fast-tag-selection-single-key 'expert))
14471 (buffer-tags nil)
14472 (fwidth (+ maxlen 3 1 3))
14473 (ncol (/ (- (window-width) 4) fwidth))
14474 (i-face 'org-done)
14475 (c-face 'org-todo)
14476 tg cnt e c char c1 c2 ntable tbl rtn
14477 ov-start ov-end ov-prefix
14478 (exit-after-next org-fast-tag-selection-single-key)
14479 (done-keywords org-done-keywords)
14480 groups ingroup intaggroup)
14481 (save-excursion
14482 (beginning-of-line 1)
14483 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14484 (setq ov-start (match-beginning 1)
14485 ov-end (match-end 1)
14486 ov-prefix "")
14487 (setq ov-start (1- (point-at-eol))
14488 ov-end (1+ ov-start))
14489 (skip-chars-forward "^\n\r")
14490 (setq ov-prefix
14491 (concat
14492 (buffer-substring (1- (point)) (point))
14493 (if (> (current-column) org-tags-column)
14495 (make-string (- org-tags-column (current-column)) ?\ ))))))
14496 (move-overlay org-tags-overlay ov-start ov-end)
14497 (save-window-excursion
14498 (if expert
14499 (set-buffer (get-buffer-create " *Org tags*"))
14500 (delete-other-windows)
14501 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14502 (org-switch-to-buffer-other-window " *Org tags*"))
14503 (erase-buffer)
14504 (setq-local org-done-keywords done-keywords)
14505 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14506 (org-fast-tag-insert "Current" current c-face "\n\n")
14507 (org-fast-tag-show-exit exit-after-next)
14508 (org-set-current-tags-overlay current ov-prefix)
14509 (setq tbl fulltable char ?a cnt 0)
14510 (while (setq e (pop tbl))
14511 (cond
14512 ((eq (car e) :startgroup)
14513 (push '() groups) (setq ingroup t)
14514 (unless (zerop cnt)
14515 (setq cnt 0)
14516 (insert "\n"))
14517 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14518 ((eq (car e) :endgroup)
14519 (setq ingroup nil cnt 0)
14520 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14521 ((eq (car e) :startgrouptag)
14522 (setq intaggroup t)
14523 (unless (zerop cnt)
14524 (setq cnt 0)
14525 (insert "\n"))
14526 (insert "[ "))
14527 ((eq (car e) :endgrouptag)
14528 (setq intaggroup nil cnt 0)
14529 (insert "]\n"))
14530 ((equal e '(:newline))
14531 (unless (zerop cnt)
14532 (setq cnt 0)
14533 (insert "\n")
14534 (setq e (car tbl))
14535 (while (equal (car tbl) '(:newline))
14536 (insert "\n")
14537 (setq tbl (cdr tbl)))))
14538 ((equal e '(:grouptags)) (insert " : "))
14540 (setq tg (copy-sequence (car e)) c2 nil)
14541 (if (cdr e)
14542 (setq c (cdr e))
14543 ;; automatically assign a character.
14544 (setq c1 (string-to-char
14545 (downcase (substring
14546 tg (if (= (string-to-char tg) ?@) 1 0)))))
14547 (if (or (rassoc c1 ntable) (rassoc c1 table))
14548 (while (or (rassoc char ntable) (rassoc char table))
14549 (setq char (1+ char)))
14550 (setq c2 c1))
14551 (setq c (or c2 char)))
14552 (when ingroup (push tg (car groups)))
14553 (setq tg (org-add-props tg nil 'face
14554 (cond
14555 ((not (assoc tg table))
14556 (org-get-todo-face tg))
14557 ((member tg current) c-face)
14558 ((member tg inherited) i-face))))
14559 (when (equal (caar tbl) :grouptags)
14560 (org-add-props tg nil 'face 'org-tag-group))
14561 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14562 (insert "[" c "] " tg (make-string
14563 (- fwidth 4 (length tg)) ?\ ))
14564 (push (cons tg c) ntable)
14565 (when (= (cl-incf cnt) ncol)
14566 (insert "\n")
14567 (when (or ingroup intaggroup) (insert " "))
14568 (setq cnt 0)))))
14569 (setq ntable (nreverse ntable))
14570 (insert "\n")
14571 (goto-char (point-min))
14572 (unless expert (org-fit-window-to-buffer))
14573 (setq rtn
14574 (catch 'exit
14575 (while t
14576 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14577 (if (not groups) "no " "")
14578 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14579 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14580 (setq org-last-tag-selection-key c)
14581 (cond
14582 ((= c ?\r) (throw 'exit t))
14583 ((= c ?!)
14584 (setq groups (not groups))
14585 (goto-char (point-min))
14586 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14587 ((= c ?\C-c)
14588 (if (not expert)
14589 (org-fast-tag-show-exit
14590 (setq exit-after-next (not exit-after-next)))
14591 (setq expert nil)
14592 (delete-other-windows)
14593 (set-window-buffer (split-window-vertically) " *Org tags*")
14594 (org-switch-to-buffer-other-window " *Org tags*")
14595 (org-fit-window-to-buffer)))
14596 ((or (= c ?\C-g)
14597 (and (= c ?q) (not (rassoc c ntable))))
14598 (delete-overlay org-tags-overlay)
14599 (setq quit-flag t))
14600 ((= c ?\ )
14601 (setq current nil)
14602 (when exit-after-next (setq exit-after-next 'now)))
14603 ((= c ?\t)
14604 (condition-case nil
14605 (setq tg (completing-read
14606 "Tag: "
14607 (or buffer-tags
14608 (with-current-buffer buf
14609 (setq buffer-tags
14610 (org-get-buffer-tags))))))
14611 (quit (setq tg "")))
14612 (when (string-match "\\S-" tg)
14613 (cl-pushnew (list tg) buffer-tags :test #'equal)
14614 (if (member tg current)
14615 (setq current (delete tg current))
14616 (push tg current)))
14617 (when exit-after-next (setq exit-after-next 'now)))
14618 ((setq e (rassoc c todo-table) tg (car e))
14619 (with-current-buffer buf
14620 (save-excursion (org-todo tg)))
14621 (when exit-after-next (setq exit-after-next 'now)))
14622 ((setq e (rassoc c ntable) tg (car e))
14623 (if (member tg current)
14624 (setq current (delete tg current))
14625 (cl-loop for g in groups do
14626 (when (member tg g)
14627 (dolist (x g) (setq current (delete x current)))))
14628 (push tg current))
14629 (when exit-after-next (setq exit-after-next 'now))))
14631 ;; Create a sorted list
14632 (setq current
14633 (sort current
14634 (lambda (a b)
14635 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14636 (when (eq exit-after-next 'now) (throw 'exit t))
14637 (goto-char (point-min))
14638 (beginning-of-line 2)
14639 (delete-region (point) (point-at-eol))
14640 (org-fast-tag-insert "Current" current c-face)
14641 (org-set-current-tags-overlay current ov-prefix)
14642 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14643 (setq tg (match-string 1))
14644 (add-text-properties
14645 (match-beginning 1) (match-end 1)
14646 (list 'face
14647 (cond
14648 ((member tg current) c-face)
14649 ((member tg inherited) i-face)
14650 (t (get-text-property (match-beginning 1) 'face))))))
14651 (goto-char (point-min)))))
14652 (delete-overlay org-tags-overlay)
14653 (if rtn
14654 (mapconcat 'identity current ":")
14655 nil))))
14657 (defun org-get-tags-string ()
14658 "Get the TAGS string in the current headline."
14659 (unless (org-at-heading-p t)
14660 (user-error "Not on a heading"))
14661 (save-excursion
14662 (beginning-of-line 1)
14663 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14664 (match-string-no-properties 1)
14665 "")))
14667 (defun org-get-tags ()
14668 "Get the list of tags specified in the current headline."
14669 (org-split-string (org-get-tags-string) ":"))
14671 (defun org-get-buffer-tags ()
14672 "Get a table of all tags used in the buffer, for completion."
14673 (org-with-wide-buffer
14674 (goto-char (point-min))
14675 (let ((tag-re (concat org-outline-regexp-bol
14676 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14677 tags)
14678 (while (re-search-forward tag-re nil t)
14679 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14680 (push tag tags)))
14681 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14683 ;;;; The mapping API
14685 (defvar org-agenda-skip-comment-trees)
14686 (defvar org-agenda-skip-function)
14687 (defun org-map-entries (func &optional match scope &rest skip)
14688 "Call FUNC at each headline selected by MATCH in SCOPE.
14690 FUNC is a function or a lisp form. The function will be called without
14691 arguments, with the cursor positioned at the beginning of the headline.
14692 The return values of all calls to the function will be collected and
14693 returned as a list.
14695 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14696 does not need to preserve point. After evaluation, the cursor will be
14697 moved to the end of the line (presumably of the headline of the
14698 processed entry) and search continues from there. Under some
14699 circumstances, this may not produce the wanted results. For example,
14700 if you have removed (e.g. archived) the current (sub)tree it could
14701 mean that the next entry will be skipped entirely. In such cases, you
14702 can specify the position from where search should continue by making
14703 FUNC set the variable `org-map-continue-from' to the desired buffer
14704 position.
14706 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14707 Only headlines that are matched by this query will be considered during
14708 the iteration. When MATCH is nil or t, all headlines will be
14709 visited by the iteration.
14711 SCOPE determines the scope of this command. It can be any of:
14713 nil The current buffer, respecting the restriction if any
14714 tree The subtree started with the entry at point
14715 region The entries within the active region, if any
14716 region-start-level
14717 The entries within the active region, but only those at
14718 the same level than the first one.
14719 file The current buffer, without restriction
14720 file-with-archives
14721 The current buffer, and any archives associated with it
14722 agenda All agenda files
14723 agenda-with-archives
14724 All agenda files with any archive files associated with them
14725 \(file1 file2 ...)
14726 If this is a list, all files in the list will be scanned
14728 The remaining args are treated as settings for the skipping facilities of
14729 the scanner. The following items can be given here:
14731 archive skip trees with the archive tag
14732 comment skip trees with the COMMENT keyword
14733 function or Emacs Lisp form:
14734 will be used as value for `org-agenda-skip-function', so
14735 whenever the function returns a position, FUNC will not be
14736 called for that entry and search will continue from the
14737 position returned
14739 If your function needs to retrieve the tags including inherited tags
14740 at the *current* entry, you can use the value of the variable
14741 `org-scanner-tags' which will be much faster than getting the value
14742 with `org-get-tags-at'. If your function gets properties with
14743 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14744 to t around the call to `org-entry-properties' to get the same speedup.
14745 Note that if your function moves around to retrieve tags and properties at
14746 a *different* entry, you cannot use these techniques."
14747 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14748 (not (org-region-active-p)))
14749 (let* ((org-agenda-archives-mode nil) ; just to make sure
14750 (org-agenda-skip-archived-trees (memq 'archive skip))
14751 (org-agenda-skip-comment-trees (memq 'comment skip))
14752 (org-agenda-skip-function
14753 (car (org-delete-all '(comment archive) skip)))
14754 (org-tags-match-list-sublevels t)
14755 (start-level (eq scope 'region-start-level))
14756 matcher res
14757 org-todo-keywords-for-agenda
14758 org-done-keywords-for-agenda
14759 org-todo-keyword-alist-for-agenda
14760 org-tag-alist-for-agenda
14761 org--matcher-tags-todo-only)
14763 (cond
14764 ((eq match t) (setq matcher t))
14765 ((eq match nil) (setq matcher t))
14766 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14768 (save-excursion
14769 (save-restriction
14770 (cond ((eq scope 'tree)
14771 (org-back-to-heading t)
14772 (org-narrow-to-subtree)
14773 (setq scope nil))
14774 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14775 (org-region-active-p))
14776 ;; If needed, set start-level to a string like "2"
14777 (when start-level
14778 (save-excursion
14779 (goto-char (region-beginning))
14780 (unless (org-at-heading-p) (outline-next-heading))
14781 (setq start-level (org-current-level))))
14782 (narrow-to-region (region-beginning)
14783 (save-excursion
14784 (goto-char (region-end))
14785 (unless (and (bolp) (org-at-heading-p))
14786 (outline-next-heading))
14787 (point)))
14788 (setq scope nil)))
14790 (if (not scope)
14791 (progn
14792 (org-agenda-prepare-buffers
14793 (and buffer-file-name (list buffer-file-name)))
14794 (setq res
14795 (org-scan-tags
14796 func matcher org--matcher-tags-todo-only start-level)))
14797 ;; Get the right scope
14798 (cond
14799 ((and scope (listp scope) (symbolp (car scope)))
14800 (setq scope (eval scope)))
14801 ((eq scope 'agenda)
14802 (setq scope (org-agenda-files t)))
14803 ((eq scope 'agenda-with-archives)
14804 (setq scope (org-agenda-files t))
14805 (setq scope (org-add-archive-files scope)))
14806 ((eq scope 'file)
14807 (setq scope (and buffer-file-name (list buffer-file-name))))
14808 ((eq scope 'file-with-archives)
14809 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14810 (org-agenda-prepare-buffers scope)
14811 (dolist (file scope)
14812 (with-current-buffer (org-find-base-buffer-visiting file)
14813 (org-with-wide-buffer
14814 (goto-char (point-min))
14815 (setq res
14816 (append
14818 (org-scan-tags
14819 func matcher org--matcher-tags-todo-only)))))))))
14820 res)))
14822 ;;; Properties API
14824 (defconst org-special-properties
14825 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14826 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14827 "The special properties valid in Org mode.
14828 These are properties that are not defined in the property drawer,
14829 but in some other way.")
14831 (defconst org-default-properties
14832 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14833 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14834 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14835 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14836 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14837 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14838 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14839 "Some properties that are used by Org mode for various purposes.
14840 Being in this list makes sure that they are offered for completion.")
14842 (defun org--valid-property-p (property)
14843 "Non nil when string PROPERTY is a valid property name."
14844 (not
14845 (or (equal property "")
14846 (string-match-p "\\s-" property))))
14848 (defun org--update-property-plist (key val props)
14849 "Associate KEY to VAL in alist PROPS.
14850 Modifications are made by side-effect. Return new alist."
14851 (let* ((appending (string= (substring key -1) "+"))
14852 (key (if appending (substring key 0 -1) key))
14853 (old (assoc-string key props t)))
14854 (if (not old) (cons (cons key val) props)
14855 (setcdr old (if appending (concat (cdr old) " " val) val))
14856 props)))
14858 (defun org-get-property-block (&optional beg force)
14859 "Return the (beg . end) range of the body of the property drawer.
14860 BEG is the beginning of the current subtree, or of the part
14861 before the first headline. If it is not given, it will be found.
14862 If the drawer does not exist, create it if FORCE is non-nil, or
14863 return nil."
14864 (org-with-wide-buffer
14865 (when beg (goto-char beg))
14866 (unless (org-before-first-heading-p)
14867 (let ((beg (cond (beg)
14868 ((or (not (featurep 'org-inlinetask))
14869 (org-inlinetask-in-task-p))
14870 (org-back-to-heading t))
14871 (t (org-with-limited-levels (org-back-to-heading t))))))
14872 (forward-line)
14873 (when (looking-at-p org-planning-line-re) (forward-line))
14874 (cond ((looking-at org-property-drawer-re)
14875 (forward-line)
14876 (cons (point) (progn (goto-char (match-end 0))
14877 (line-beginning-position))))
14878 (force
14879 (goto-char beg)
14880 (org-insert-property-drawer)
14881 (let ((pos (save-excursion (search-forward ":END:")
14882 (line-beginning-position))))
14883 (cons pos pos))))))))
14885 (defun org-at-property-p ()
14886 "Non-nil when point is inside a property drawer.
14887 See `org-property-re' for match data, if applicable."
14888 (save-excursion
14889 (beginning-of-line)
14890 (and (looking-at org-property-re)
14891 (let ((property-drawer (save-match-data (org-get-property-block))))
14892 (and property-drawer
14893 (>= (point) (car property-drawer))
14894 (< (point) (cdr property-drawer)))))))
14896 (defun org-property-action ()
14897 "Do an action on properties."
14898 (interactive)
14899 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14900 (let ((c (read-char-exclusive)))
14901 (cl-case c
14902 (?s (call-interactively #'org-set-property))
14903 (?d (call-interactively #'org-delete-property))
14904 (?D (call-interactively #'org-delete-property-globally))
14905 (?c (call-interactively #'org-compute-property-at-point))
14906 (otherwise (user-error "No such property action %c" c)))))
14908 (defun org-inc-effort ()
14909 "Increment the value of the effort property in the current entry."
14910 (interactive)
14911 (org-set-effort t))
14913 (defvar org-clock-effort) ; Defined in org-clock.el.
14914 (defvar org-clock-current-task) ; Defined in org-clock.el.
14915 (defun org-set-effort (&optional increment value)
14916 "Set the effort property of the current entry.
14917 If INCREMENT is non-nil, set the property to the next allowed
14918 value. Otherwise, if optional argument VALUE is provided, use
14919 it. Eventually, prompt for the new value if none of the previous
14920 variables is set."
14921 (interactive "P")
14922 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14923 (current (org-entry-get nil org-effort-property))
14924 (value
14925 (cond
14926 (increment
14927 (unless allowed (user-error "Allowed effort values are not set"))
14928 (or (cl-caadr (member (list current) allowed))
14929 (user-error "Unknown value %S among allowed values" current)))
14930 (value
14931 (if (stringp value) value
14932 (error "Invalid effort value: %S" value)))
14934 (let ((must-match
14935 (and allowed
14936 (not (get-text-property 0 'org-unrestricted
14937 (caar allowed))))))
14938 (completing-read "Effort: " allowed nil must-match))))))
14939 (unless (equal current value)
14940 (org-entry-put nil org-effort-property value))
14941 (org-refresh-property '((effort . identity)
14942 (effort-minutes . org-duration-to-minutes))
14943 value)
14944 (when (equal (org-get-heading t t t t)
14945 (bound-and-true-p org-clock-current-task))
14946 (setq org-clock-effort (org-get-at-bol 'effort))
14947 (org-clock-update-mode-line))
14948 (message "%s is now %s" org-effort-property value)))
14950 (defun org-entry-properties (&optional pom which)
14951 "Get all properties of the current entry.
14953 When POM is a buffer position, get all properties from the entry
14954 there instead.
14956 This includes the TODO keyword, the tags, time strings for
14957 deadline, scheduled, and clocking, and any additional properties
14958 defined in the entry.
14960 If WHICH is nil or `all', get all properties. If WHICH is
14961 `special' or `standard', only get that subclass. If WHICH is
14962 a string, only get that property.
14964 Return value is an alist. Keys are properties, as upcased
14965 strings."
14966 (org-with-point-at pom
14967 (when (and (derived-mode-p 'org-mode)
14968 (ignore-errors (org-back-to-heading t)))
14969 (catch 'exit
14970 (let* ((beg (point))
14971 (specific (and (stringp which) (upcase which)))
14972 (which (cond ((not specific) which)
14973 ((member specific org-special-properties) 'special)
14974 (t 'standard)))
14975 props)
14976 ;; Get the special properties, like TODO and TAGS.
14977 (when (memq which '(nil all special))
14978 (when (or (not specific) (string= specific "CLOCKSUM"))
14979 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
14980 (when clocksum
14981 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
14982 props)))
14983 (when specific (throw 'exit props)))
14984 (when (or (not specific) (string= specific "CLOCKSUM_T"))
14985 (let ((clocksumt (get-text-property (point)
14986 :org-clock-minutes-today)))
14987 (when clocksumt
14988 (push (cons "CLOCKSUM_T"
14989 (org-duration-from-minutes clocksumt))
14990 props)))
14991 (when specific (throw 'exit props)))
14992 (when (or (not specific) (string= specific "ITEM"))
14993 (let ((case-fold-search nil))
14994 (when (looking-at org-complex-heading-regexp)
14995 (push (cons "ITEM"
14996 (let ((title (match-string-no-properties 4)))
14997 (if (org-string-nw-p title)
14998 (org-remove-tabs title)
14999 "")))
15000 props)))
15001 (when specific (throw 'exit props)))
15002 (when (or (not specific) (string= specific "TODO"))
15003 (let ((case-fold-search nil))
15004 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15005 (push (cons "TODO" (match-string-no-properties 2)) props)))
15006 (when specific (throw 'exit props)))
15007 (when (or (not specific) (string= specific "PRIORITY"))
15008 (push (cons "PRIORITY"
15009 (if (looking-at org-priority-regexp)
15010 (match-string-no-properties 2)
15011 (char-to-string org-default-priority)))
15012 props)
15013 (when specific (throw 'exit props)))
15014 (when (or (not specific) (string= specific "FILE"))
15015 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15016 props)
15017 (when specific (throw 'exit props)))
15018 (when (or (not specific) (string= specific "TAGS"))
15019 (let ((value (org-string-nw-p (org-get-tags-string))))
15020 (when value (push (cons "TAGS" value) props)))
15021 (when specific (throw 'exit props)))
15022 (when (or (not specific) (string= specific "ALLTAGS"))
15023 (let ((value (org-get-tags-at)))
15024 (when value
15025 (push (cons "ALLTAGS"
15026 (format ":%s:" (mapconcat #'identity value ":")))
15027 props)))
15028 (when specific (throw 'exit props)))
15029 (when (or (not specific) (string= specific "BLOCKED"))
15030 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15031 (when specific (throw 'exit props)))
15032 (when (or (not specific)
15033 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15034 (forward-line)
15035 (when (looking-at-p org-planning-line-re)
15036 (end-of-line)
15037 (let ((bol (line-beginning-position))
15038 ;; Backward compatibility: time keywords used to
15039 ;; be configurable (before 8.3). Make sure we
15040 ;; get the correct keyword.
15041 (key-assoc `(("CLOSED" . ,org-closed-string)
15042 ("DEADLINE" . ,org-deadline-string)
15043 ("SCHEDULED" . ,org-scheduled-string))))
15044 (dolist (pair (if specific (list (assoc specific key-assoc))
15045 key-assoc))
15046 (save-excursion
15047 (when (search-backward (cdr pair) bol t)
15048 (goto-char (match-end 0))
15049 (skip-chars-forward " \t")
15050 (and (looking-at org-ts-regexp-both)
15051 (push (cons (car pair)
15052 (match-string-no-properties 0))
15053 props)))))))
15054 (when specific (throw 'exit props)))
15055 (when (or (not specific)
15056 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15057 (let ((find-ts
15058 (lambda (end ts)
15059 ;; Fix next time-stamp before END. TS is the
15060 ;; list of time-stamps found so far.
15061 (let ((ts ts)
15062 (regexp (cond
15063 ((string= specific "TIMESTAMP")
15064 org-ts-regexp)
15065 ((string= specific "TIMESTAMP_IA")
15066 org-ts-regexp-inactive)
15067 ((assoc "TIMESTAMP_IA" ts)
15068 org-ts-regexp)
15069 ((assoc "TIMESTAMP" ts)
15070 org-ts-regexp-inactive)
15071 (t org-ts-regexp-both))))
15072 (catch 'next
15073 (while (re-search-forward regexp end t)
15074 (backward-char)
15075 (let ((object (org-element-context)))
15076 ;; Accept to match timestamps in node
15077 ;; properties, too.
15078 (when (memq (org-element-type object)
15079 '(node-property timestamp))
15080 (let ((type
15081 (org-element-property :type object)))
15082 (cond
15083 ((and (memq type '(active active-range))
15084 (not (equal specific "TIMESTAMP_IA")))
15085 (unless (assoc "TIMESTAMP" ts)
15086 (push (cons "TIMESTAMP"
15087 (org-element-property
15088 :raw-value object))
15090 (when specific (throw 'exit ts))))
15091 ((and (memq type '(inactive inactive-range))
15092 (not (string= specific "TIMESTAMP")))
15093 (unless (assoc "TIMESTAMP_IA" ts)
15094 (push (cons "TIMESTAMP_IA"
15095 (org-element-property
15096 :raw-value object))
15098 (when specific (throw 'exit ts))))))
15099 ;; Both timestamp types are found,
15100 ;; move to next part.
15101 (when (= (length ts) 2) (throw 'next ts)))))
15102 ts)))))
15103 (goto-char beg)
15104 ;; First look for timestamps within headline.
15105 (let ((ts (funcall find-ts (line-end-position) nil)))
15106 (if (= (length ts) 2) (setq props (nconc ts props))
15107 ;; Then find timestamps in the section, skipping
15108 ;; planning line.
15109 (let ((end (save-excursion (outline-next-heading))))
15110 (forward-line)
15111 (when (looking-at-p org-planning-line-re) (forward-line))
15112 (setq props (nconc (funcall find-ts end ts) props))))))))
15113 ;; Get the standard properties, like :PROP:.
15114 (when (memq which '(nil all standard))
15115 ;; If we are looking after a specific property, delegate
15116 ;; to `org-entry-get', which is faster. However, make an
15117 ;; exception for "CATEGORY", since it can be also set
15118 ;; through keywords (i.e. #+CATEGORY).
15119 (if (and specific (not (equal specific "CATEGORY")))
15120 (let ((value (org-entry-get beg specific nil t)))
15121 (throw 'exit (and value (list (cons specific value)))))
15122 (let ((range (org-get-property-block beg)))
15123 (when range
15124 (let ((end (cdr range)) seen-base)
15125 (goto-char (car range))
15126 ;; Unlike to `org--update-property-plist', we
15127 ;; handle the case where base values is found
15128 ;; after its extension. We also forbid standard
15129 ;; properties to be named as special properties.
15130 (while (re-search-forward org-property-re end t)
15131 (let* ((key (upcase (match-string-no-properties 2)))
15132 (extendp (string-match-p "\\+\\'" key))
15133 (key-base (if extendp (substring key 0 -1) key))
15134 (value (match-string-no-properties 3)))
15135 (cond
15136 ((member-ignore-case key-base org-special-properties))
15137 (extendp
15138 (setq props
15139 (org--update-property-plist key value props)))
15140 ((member key seen-base))
15141 (t (push key seen-base)
15142 (let ((p (assoc-string key props t)))
15143 (if p (setcdr p (concat value " " (cdr p)))
15144 (push (cons key value) props))))))))))))
15145 (unless (assoc "CATEGORY" props)
15146 (push (cons "CATEGORY" (org-get-category beg)) props)
15147 (when (string= specific "CATEGORY") (throw 'exit props)))
15148 ;; Return value.
15149 props)))))
15151 (defun org--property-local-values (property literal-nil)
15152 "Return value for PROPERTY in current entry.
15153 Value is a list whose car is the base value for PROPERTY and cdr
15154 a list of accumulated values. Return nil if neither is found in
15155 the entry. Also return nil when PROPERTY is set to \"nil\",
15156 unless LITERAL-NIL is non-nil."
15157 (let ((range (org-get-property-block)))
15158 (when range
15159 (goto-char (car range))
15160 (let* ((case-fold-search t)
15161 (end (cdr range))
15162 (value
15163 ;; Base value.
15164 (save-excursion
15165 (let ((v (and (re-search-forward
15166 (org-re-property property nil t) end t)
15167 (match-string-no-properties 3))))
15168 (list (if literal-nil v (org-not-nil v)))))))
15169 ;; Find additional values.
15170 (let* ((property+ (org-re-property (concat property "+") nil t)))
15171 (while (re-search-forward property+ end t)
15172 (push (match-string-no-properties 3) value)))
15173 ;; Return final values.
15174 (and (not (equal value '(nil))) (nreverse value))))))
15176 (defun org--property-global-value (property literal-nil)
15177 "Return value for PROPERTY in current buffer.
15178 Return value is a string. Return nil if property is not set
15179 globally. Also return nil when PROPERTY is set to \"nil\",
15180 unless LITERAL-NIL is non-nil."
15181 (let ((global
15182 (cdr (or (assoc-string property org-file-properties t)
15183 (assoc-string property org-global-properties t)
15184 (assoc-string property org-global-properties-fixed t)))))
15185 (if literal-nil global (org-not-nil global))))
15187 (defun org-entry-get (pom property &optional inherit literal-nil)
15188 "Get value of PROPERTY for entry or content at point-or-marker POM.
15190 If INHERIT is non-nil and the entry does not have the property,
15191 then also check higher levels of the hierarchy. If INHERIT is
15192 the symbol `selective', use inheritance only if the setting in
15193 `org-use-property-inheritance' selects PROPERTY for inheritance.
15195 If the property is present but empty, the return value is the
15196 empty string. If the property is not present at all, nil is
15197 returned. In any other case, return the value as a string.
15198 Search is case-insensitive.
15200 If LITERAL-NIL is set, return the string value \"nil\" as
15201 a string, do not interpret it as the list atom nil. This is used
15202 for inheritance when a \"nil\" value can supersede a non-nil
15203 value higher up the hierarchy."
15204 (org-with-point-at pom
15205 (cond
15206 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15207 ;; We need a special property. Use `org-entry-properties' to
15208 ;; retrieve it, but specify the wanted property.
15209 (cdr (assoc-string property (org-entry-properties nil property))))
15210 ((and inherit
15211 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15212 (org-entry-get-with-inheritance property literal-nil))
15214 (let* ((local (org--property-local-values property literal-nil))
15215 (value (and local (mapconcat #'identity (delq nil local) " "))))
15216 (if literal-nil value (org-not-nil value)))))))
15218 (defun org-property-or-variable-value (var &optional inherit)
15219 "Check if there is a property fixing the value of VAR.
15220 If yes, return this value. If not, return the current value of the variable."
15221 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15222 (if (and prop (stringp prop) (string-match "\\S-" prop))
15223 (read prop)
15224 (symbol-value var))))
15226 (defun org-entry-delete (pom property)
15227 "Delete PROPERTY from entry at point-or-marker POM.
15228 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15229 non-nil when a property was removed."
15230 (org-with-point-at pom
15231 (pcase (org-get-property-block)
15232 (`(,begin . ,origin)
15233 (let* ((end (copy-marker origin))
15234 (re (org-re-property
15235 (concat (regexp-quote property) "\\+?") t t)))
15236 (goto-char begin)
15237 (while (re-search-forward re end t)
15238 (delete-region (match-beginning 0) (line-beginning-position 2)))
15239 ;; If drawer is empty, remove it altogether.
15240 (when (= begin end)
15241 (delete-region (line-beginning-position 0)
15242 (line-beginning-position 2)))
15243 ;; Return non-nil if some property was removed.
15244 (prog1 (/= end origin) (set-marker end nil))))
15245 (_ nil))))
15247 ;; Multi-values properties are properties that contain multiple values
15248 ;; These values are assumed to be single words, separated by whitespace.
15249 (defun org-entry-add-to-multivalued-property (pom property value)
15250 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15251 (let* ((old (org-entry-get pom property))
15252 (values (and old (split-string old))))
15253 (setq value (org-entry-protect-space value))
15254 (unless (member value values)
15255 (setq values (append values (list value)))
15256 (org-entry-put pom property (mapconcat #'identity values " ")))))
15258 (defun org-entry-remove-from-multivalued-property (pom property value)
15259 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15260 (let* ((old (org-entry-get pom property))
15261 (values (and old (split-string old))))
15262 (setq value (org-entry-protect-space value))
15263 (when (member value values)
15264 (setq values (delete value values))
15265 (org-entry-put pom property (mapconcat #'identity values " ")))))
15267 (defun org-entry-member-in-multivalued-property (pom property value)
15268 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15269 (let* ((old (org-entry-get pom property))
15270 (values (and old (split-string old))))
15271 (setq value (org-entry-protect-space value))
15272 (member value values)))
15274 (defun org-entry-get-multivalued-property (pom property)
15275 "Return a list of values in a multivalued property."
15276 (let* ((value (org-entry-get pom property))
15277 (values (and value (split-string value))))
15278 (mapcar #'org-entry-restore-space values)))
15280 (defun org-entry-put-multivalued-property (pom property &rest values)
15281 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15282 VALUES should be a list of strings. Spaces will be protected."
15283 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15284 (let* ((value (org-entry-get pom property))
15285 (values (and value (split-string value))))
15286 (mapcar #'org-entry-restore-space values)))
15288 (defun org-entry-protect-space (s)
15289 "Protect spaces and newline in string S."
15290 (while (string-match " " s)
15291 (setq s (replace-match "%20" t t s)))
15292 (while (string-match "\n" s)
15293 (setq s (replace-match "%0A" t t s)))
15296 (defun org-entry-restore-space (s)
15297 "Restore spaces and newline in string S."
15298 (while (string-match "%20" s)
15299 (setq s (replace-match " " t t s)))
15300 (while (string-match "%0A" s)
15301 (setq s (replace-match "\n" t t s)))
15304 (defvar org-entry-property-inherited-from (make-marker)
15305 "Marker pointing to the entry from where a property was inherited.
15306 Each call to `org-entry-get-with-inheritance' will set this marker to the
15307 location of the entry where the inheritance search matched. If there was
15308 no match, the marker will point nowhere.
15309 Note that also `org-entry-get' calls this function, if the INHERIT flag
15310 is set.")
15312 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15313 "Get PROPERTY of entry or content at point, search higher levels if needed.
15314 The search will stop at the first ancestor which has the property defined.
15315 If the value found is \"nil\", return nil to show that the property
15316 should be considered as undefined (this is the meaning of nil here).
15317 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15318 (move-marker org-entry-property-inherited-from nil)
15319 (org-with-wide-buffer
15320 (let (value)
15321 (catch 'exit
15322 (while t
15323 (let ((v (org--property-local-values property literal-nil)))
15324 (when v
15325 (setq value
15326 (concat (mapconcat #'identity (delq nil v) " ")
15327 (and value " ")
15328 value)))
15329 (cond
15330 ((car v)
15331 (org-back-to-heading t)
15332 (move-marker org-entry-property-inherited-from (point))
15333 (throw 'exit nil))
15334 ((org-up-heading-safe))
15336 (let ((global (org--property-global-value property literal-nil)))
15337 (cond ((not global))
15338 (value (setq value (concat global " " value)))
15339 (t (setq value global))))
15340 (throw 'exit nil))))))
15341 (if literal-nil value (org-not-nil value)))))
15343 (defvar org-property-changed-functions nil
15344 "Hook called when the value of a property has changed.
15345 Each hook function should accept two arguments, the name of the property
15346 and the new value.")
15348 (defun org-entry-put (pom property value)
15349 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15351 If the value is nil, it is converted to the empty string. If it
15352 is not a string, an error is raised. Also raise an error on
15353 invalid property names.
15355 PROPERTY can be any regular property (see
15356 `org-special-properties'). It can also be \"TODO\",
15357 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15359 For the last two properties, VALUE may have any of the special
15360 values \"earlier\" and \"later\". The function then increases or
15361 decreases scheduled or deadline date by one day."
15362 (cond ((null value) (setq value ""))
15363 ((not (stringp value)) (error "Properties values should be strings"))
15364 ((not (org--valid-property-p property))
15365 (user-error "Invalid property name: \"%s\"" property)))
15366 (org-with-point-at pom
15367 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15368 (org-back-to-heading t)
15369 (org-with-limited-levels (org-back-to-heading t)))
15370 (let ((beg (point)))
15371 (cond
15372 ((equal property "TODO")
15373 (cond ((not (org-string-nw-p value)) (setq value 'none))
15374 ((not (member value org-todo-keywords-1))
15375 (user-error "\"%s\" is not a valid TODO state" value)))
15376 (org-todo value)
15377 (org-set-tags nil 'align))
15378 ((equal property "PRIORITY")
15379 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15380 (org-set-tags nil 'align))
15381 ((equal property "SCHEDULED")
15382 (forward-line)
15383 (if (and (looking-at-p org-planning-line-re)
15384 (re-search-forward
15385 org-scheduled-time-regexp (line-end-position) t))
15386 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15387 ((string= value "later") (org-timestamp-change 1 'day))
15388 ((string= value "") (org-schedule '(4)))
15389 (t (org-schedule nil value)))
15390 (if (member value '("earlier" "later" ""))
15391 (call-interactively #'org-schedule)
15392 (org-schedule nil value))))
15393 ((equal property "DEADLINE")
15394 (forward-line)
15395 (if (and (looking-at-p org-planning-line-re)
15396 (re-search-forward
15397 org-deadline-time-regexp (line-end-position) t))
15398 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15399 ((string= value "later") (org-timestamp-change 1 'day))
15400 ((string= value "") (org-deadline '(4)))
15401 (t (org-deadline nil value)))
15402 (if (member value '("earlier" "later" ""))
15403 (call-interactively #'org-deadline)
15404 (org-deadline nil value))))
15405 ((member property org-special-properties)
15406 (error "The %s property cannot be set with `org-entry-put'" property))
15408 (let* ((range (org-get-property-block beg 'force))
15409 (end (cdr range))
15410 (case-fold-search t))
15411 (goto-char (car range))
15412 (if (re-search-forward (org-re-property property nil t) end t)
15413 (progn (delete-region (match-beginning 0) (match-end 0))
15414 (goto-char (match-beginning 0)))
15415 (goto-char end)
15416 (insert "\n")
15417 (backward-char))
15418 (insert ":" property ":")
15419 (when value (insert " " value))
15420 (org-indent-line)))))
15421 (run-hook-with-args 'org-property-changed-functions property value)))
15423 (defun org-buffer-property-keys (&optional specials defaults columns)
15424 "Get all property keys in the current buffer.
15426 When SPECIALS is non-nil, also list the special properties that
15427 reflect things like tags and TODO state.
15429 When DEFAULTS is non-nil, also include properties that has
15430 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15431 DESCRIPTION, LOCATION, and LOGGING and others.
15433 When COLUMNS in non-nil, also include property names given in
15434 COLUMN formats in the current buffer."
15435 (let ((case-fold-search t)
15436 (props (append
15437 (and specials org-special-properties)
15438 (and defaults (cons org-effort-property org-default-properties))
15439 nil)))
15440 (org-with-wide-buffer
15441 (goto-char (point-min))
15442 (while (re-search-forward org-property-start-re nil t)
15443 (catch :skip
15444 (let ((range (org-get-property-block)))
15445 (unless range (throw :skip nil))
15446 (goto-char (car range))
15447 (let ((begin (car range))
15448 (end (cdr range)))
15449 ;; Make sure that found property block is not located
15450 ;; before current point, as it would generate an infloop.
15451 ;; It can happen, for example, in the following
15452 ;; situation:
15454 ;; * Headline
15455 ;; :PROPERTIES:
15456 ;; ...
15457 ;; :END:
15458 ;; *************** Inlinetask
15459 ;; #+BEGIN_EXAMPLE
15460 ;; :PROPERTIES:
15461 ;; #+END_EXAMPLE
15463 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15464 (while (< (point) end)
15465 (let ((p (progn (looking-at org-property-re)
15466 (match-string-no-properties 2))))
15467 ;; Only add true property name, not extension symbol.
15468 (push (if (not (string-match-p "\\+\\'" p)) p
15469 (substring p 0 -1))
15470 props))
15471 (forward-line))))
15472 (outline-next-heading)))
15473 (when columns
15474 (goto-char (point-min))
15475 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15476 (let ((element (org-element-at-point)))
15477 (when (memq (org-element-type element) '(keyword node-property))
15478 (let ((value (org-element-property :value element))
15479 (start 0))
15480 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15481 \\(?:{[^}]+}\\)?"
15482 value start)
15483 (setq start (match-end 0))
15484 (let ((p (match-string-no-properties 1 value)))
15485 (unless (member-ignore-case p org-special-properties)
15486 (push p props))))))))))
15487 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15489 (defun org-property-values (key)
15490 "List all non-nil values of property KEY in current buffer."
15491 (org-with-wide-buffer
15492 (goto-char (point-min))
15493 (let ((case-fold-search t)
15494 (re (org-re-property key))
15495 values)
15496 (while (re-search-forward re nil t)
15497 (push (org-entry-get (point) key) values))
15498 (delete-dups values))))
15500 (defun org-insert-property-drawer ()
15501 "Insert a property drawer into the current entry."
15502 (org-with-wide-buffer
15503 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15504 (org-back-to-heading t)
15505 (org-with-limited-levels (org-back-to-heading t)))
15506 (forward-line)
15507 (when (looking-at-p org-planning-line-re) (forward-line))
15508 (unless (looking-at-p org-property-drawer-re)
15509 ;; Make sure we start editing a line from current entry, not from
15510 ;; next one. It prevents extending text properties or overlays
15511 ;; belonging to the latter.
15512 (when (bolp) (backward-char))
15513 (let ((begin (1+ (point)))
15514 (inhibit-read-only t))
15515 (insert "\n:PROPERTIES:\n:END:")
15516 (when (eobp) (insert "\n"))
15517 (org-indent-region begin (point))))))
15519 (defun org-insert-drawer (&optional arg drawer)
15520 "Insert a drawer at point.
15522 When optional argument ARG is non-nil, insert a property drawer.
15524 Optional argument DRAWER, when non-nil, is a string representing
15525 drawer's name. Otherwise, the user is prompted for a name.
15527 If a region is active, insert the drawer around that region
15528 instead.
15530 Point is left between drawer's boundaries."
15531 (interactive "P")
15532 (let* ((drawer (if arg "PROPERTIES"
15533 (or drawer (read-from-minibuffer "Drawer: ")))))
15534 (cond
15535 ;; With C-u, fall back on `org-insert-property-drawer'
15536 (arg (org-insert-property-drawer))
15537 ;; Check validity of suggested drawer's name.
15538 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15539 (user-error "Invalid drawer name"))
15540 ;; With an active region, insert a drawer at point.
15541 ((not (org-region-active-p))
15542 (progn
15543 (unless (bolp) (insert "\n"))
15544 (insert (format ":%s:\n\n:END:\n" drawer))
15545 (forward-line -2)))
15546 ;; Otherwise, insert the drawer at point
15548 (let ((rbeg (region-beginning))
15549 (rend (copy-marker (region-end))))
15550 (unwind-protect
15551 (progn
15552 (goto-char rbeg)
15553 (beginning-of-line)
15554 (when (save-excursion
15555 (re-search-forward org-outline-regexp-bol rend t))
15556 (user-error "Drawers cannot contain headlines"))
15557 ;; Position point at the beginning of the first
15558 ;; non-blank line in region. Insert drawer's opening
15559 ;; there, then indent it.
15560 (org-skip-whitespace)
15561 (beginning-of-line)
15562 (insert ":" drawer ":\n")
15563 (forward-line -1)
15564 (indent-for-tab-command)
15565 ;; Move point to the beginning of the first blank line
15566 ;; after the last non-blank line in region. Insert
15567 ;; drawer's closing, then indent it.
15568 (goto-char rend)
15569 (skip-chars-backward " \r\t\n")
15570 (insert "\n:END:")
15571 (deactivate-mark t)
15572 (indent-for-tab-command)
15573 (unless (eolp) (insert "\n")))
15574 ;; Clear marker, whatever the outcome of insertion is.
15575 (set-marker rend nil)))))))
15577 (defvar org-property-set-functions-alist nil
15578 "Property set function alist.
15579 Each entry should have the following format:
15581 (PROPERTY . READ-FUNCTION)
15583 The read function will be called with the same argument as
15584 `org-completing-read'.")
15586 (defun org-set-property-function (property)
15587 "Get the function that should be used to set PROPERTY.
15588 This is computed according to `org-property-set-functions-alist'."
15589 (or (cdr (assoc property org-property-set-functions-alist))
15590 'org-completing-read))
15592 (defun org-read-property-value (property)
15593 "Read PROPERTY value from user."
15594 (let* ((completion-ignore-case t)
15595 (allowed (org-property-get-allowed-values nil property 'table))
15596 (cur (org-entry-get nil property))
15597 (prompt (concat property " value"
15598 (if (and cur (string-match "\\S-" cur))
15599 (concat " [" cur "]") "") ": "))
15600 (set-function (org-set-property-function property))
15601 (val (if allowed
15602 (funcall set-function prompt allowed nil
15603 (not (get-text-property 0 'org-unrestricted
15604 (caar allowed))))
15605 (funcall set-function prompt
15606 (mapcar 'list (org-property-values property))
15607 nil nil "" nil cur))))
15608 (org-trim val)))
15610 (defvar org-last-set-property nil)
15611 (defvar org-last-set-property-value nil)
15612 (defun org-read-property-name ()
15613 "Read a property name."
15614 (let ((completion-ignore-case t)
15615 (default-prop (or (and (org-at-property-p)
15616 (match-string-no-properties 2))
15617 org-last-set-property)))
15618 (org-completing-read
15619 (concat "Property"
15620 (if default-prop (concat " [" default-prop "]") "")
15621 ": ")
15622 (mapcar #'list (org-buffer-property-keys nil t t))
15623 nil nil nil nil default-prop)))
15625 (defun org-set-property-and-value (use-last)
15626 "Allow to set [PROPERTY]: [value] direction from prompt.
15627 When use-default, don't even ask, just use the last
15628 \"[PROPERTY]: [value]\" string from the history."
15629 (interactive "P")
15630 (let* ((completion-ignore-case t)
15631 (pv (or (and use-last org-last-set-property-value)
15632 (org-completing-read
15633 "Enter a \"[Property]: [value]\" pair: "
15634 nil nil nil nil nil
15635 org-last-set-property-value)))
15636 prop val)
15637 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15638 (setq prop (match-string 1 pv)
15639 val (match-string 2 pv))
15640 (org-set-property prop val))))
15642 (defun org-set-property (property value)
15643 "In the current entry, set PROPERTY to VALUE.
15645 When called interactively, this will prompt for a property name, offering
15646 completion on existing and default properties. And then it will prompt
15647 for a value, offering completion either on allowed values (via an inherited
15648 xxx_ALL property) or on existing values in other instances of this property
15649 in the current file.
15651 Throw an error when trying to set a property with an invalid name."
15652 (interactive (list nil nil))
15653 (let ((property (or property (org-read-property-name))))
15654 ;; `org-entry-put' also makes the following check, but this one
15655 ;; avoids polluting `org-last-set-property' and
15656 ;; `org-last-set-property-value' needlessly.
15657 (unless (org--valid-property-p property)
15658 (user-error "Invalid property name: \"%s\"" property))
15659 (let ((value (or value (org-read-property-value property)))
15660 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15661 (setq org-last-set-property property)
15662 (setq org-last-set-property-value (concat property ": " value))
15663 ;; Possibly postprocess the inserted value:
15664 (when fn (setq value (funcall fn value)))
15665 (unless (equal (org-entry-get nil property) value)
15666 (org-entry-put nil property value)))))
15668 (defun org-find-property (property &optional value)
15669 "Find first entry in buffer that sets PROPERTY.
15671 When optional argument VALUE is non-nil, only consider an entry
15672 if it contains PROPERTY set to this value. If PROPERTY should be
15673 explicitly set to nil, use string \"nil\" for VALUE.
15675 Return position where the entry begins, or nil if there is no
15676 such entry. If narrowing is in effect, only search the visible
15677 part of the buffer."
15678 (save-excursion
15679 (goto-char (point-min))
15680 (let ((case-fold-search t)
15681 (re (org-re-property property nil (not value) value)))
15682 (catch 'exit
15683 (while (re-search-forward re nil t)
15684 (when (if value (org-at-property-p)
15685 (org-entry-get (point) property nil t))
15686 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15688 (defun org-delete-property (property)
15689 "In the current entry, delete PROPERTY."
15690 (interactive
15691 (let* ((completion-ignore-case t)
15692 (cat (org-entry-get (point) "CATEGORY"))
15693 (props0 (org-entry-properties nil 'standard))
15694 (props (if cat props0
15695 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15696 (prop (if (< 1 (length props))
15697 (completing-read "Property: " props nil t)
15698 (caar props))))
15699 (list prop)))
15700 (if (not property)
15701 (message "No property to delete in this entry")
15702 (org-entry-delete nil property)
15703 (message "Property \"%s\" deleted" property)))
15705 (defun org-delete-property-globally (property)
15706 "Remove PROPERTY globally, from all entries.
15707 This function ignores narrowing, if any."
15708 (interactive
15709 (let* ((completion-ignore-case t)
15710 (prop (completing-read
15711 "Globally remove property: "
15712 (mapcar #'list (org-buffer-property-keys)))))
15713 (list prop)))
15714 (org-with-wide-buffer
15715 (goto-char (point-min))
15716 (let ((count 0)
15717 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15718 (while (re-search-forward re nil t)
15719 (when (org-entry-delete (point) property) (cl-incf count)))
15720 (message "Property \"%s\" removed from %d entries" property count))))
15722 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15724 (defun org-compute-property-at-point ()
15725 "Compute the property at point.
15726 This looks for an enclosing column format, extracts the operator and
15727 then applies it to the property in the column format's scope."
15728 (interactive)
15729 (unless (org-at-property-p)
15730 (user-error "Not at a property"))
15731 (let ((prop (match-string-no-properties 2)))
15732 (org-columns-get-format-and-top-level)
15733 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15734 (user-error "No operator defined for property %s" prop))
15735 (org-columns-compute prop)))
15737 (defvar org-property-allowed-value-functions nil
15738 "Hook for functions supplying allowed values for a specific property.
15739 The functions must take a single argument, the name of the property, and
15740 return a flat list of allowed values. If \":ETC\" is one of
15741 the values, this means that these values are intended as defaults for
15742 completion, but that other values should be allowed too.
15743 The functions must return nil if they are not responsible for this
15744 property.")
15746 (defun org-property-get-allowed-values (pom property &optional table)
15747 "Get allowed values for the property PROPERTY.
15748 When TABLE is non-nil, return an alist that can directly be used for
15749 completion."
15750 (let (vals)
15751 (cond
15752 ((equal property "TODO")
15753 (setq vals (org-with-point-at pom
15754 (append org-todo-keywords-1 '("")))))
15755 ((equal property "PRIORITY")
15756 (let ((n org-lowest-priority))
15757 (while (>= n org-highest-priority)
15758 (push (char-to-string n) vals)
15759 (setq n (1- n)))))
15760 ((equal property "CATEGORY"))
15761 ((member property org-special-properties))
15762 ((setq vals (run-hook-with-args-until-success
15763 'org-property-allowed-value-functions property)))
15765 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15766 (when (and vals (string-match "\\S-" vals))
15767 (setq vals (car (read-from-string (concat "(" vals ")"))))
15768 (setq vals (mapcar (lambda (x)
15769 (cond ((stringp x) x)
15770 ((numberp x) (number-to-string x))
15771 ((symbolp x) (symbol-name x))
15772 (t "???")))
15773 vals)))))
15774 (when (member ":ETC" vals)
15775 (setq vals (remove ":ETC" vals))
15776 (org-add-props (car vals) '(org-unrestricted t)))
15777 (if table (mapcar 'list vals) vals)))
15779 (defun org-property-previous-allowed-value (&optional _previous)
15780 "Switch to the next allowed value for this property."
15781 (interactive)
15782 (org-property-next-allowed-value t))
15784 (defun org-property-next-allowed-value (&optional previous)
15785 "Switch to the next allowed value for this property."
15786 (interactive)
15787 (unless (org-at-property-p)
15788 (user-error "Not at a property"))
15789 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15790 (key (match-string 2))
15791 (value (match-string 3))
15792 (allowed (or (org-property-get-allowed-values (point) key)
15793 (and (member value '("[ ]" "[-]" "[X]"))
15794 '("[ ]" "[X]"))))
15795 (heading (save-match-data (nth 4 (org-heading-components))))
15796 nval)
15797 (unless allowed
15798 (user-error "Allowed values for this property have not been defined"))
15799 (when previous (setq allowed (reverse allowed)))
15800 (when (member value allowed)
15801 (setq nval (car (cdr (member value allowed)))))
15802 (setq nval (or nval (car allowed)))
15803 (when (equal nval value)
15804 (user-error "Only one allowed value for this property"))
15805 (org-at-property-p)
15806 (replace-match (concat " :" key ": " nval) t t)
15807 (org-indent-line)
15808 (beginning-of-line 1)
15809 (skip-chars-forward " \t")
15810 (when (equal prop org-effort-property)
15811 (org-refresh-property
15812 '((effort . identity)
15813 (effort-minutes . org-duration-to-minutes))
15814 nval)
15815 (when (string= org-clock-current-task heading)
15816 (setq org-clock-effort nval)
15817 (org-clock-update-mode-line)))
15818 (run-hook-with-args 'org-property-changed-functions key nval)))
15820 (defun org-find-olp (path &optional this-buffer)
15821 "Return a marker pointing to the entry at outline path OLP.
15822 If anything goes wrong, throw an error.
15823 You can wrap this call to catch the error like this:
15825 (condition-case msg
15826 (org-mobile-locate-entry (match-string 4))
15827 (error (nth 1 msg)))
15829 The return value will then be either a string with the error message,
15830 or a marker if everything is OK.
15832 If THIS-BUFFER is set, the outline path does not contain a file,
15833 only headings."
15834 (let* ((file (if this-buffer buffer-file-name (pop path)))
15835 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15836 (level 1)
15837 (lmin 1)
15838 (lmax 1)
15839 end found flevel)
15840 (unless buffer (error "File not found :%s" file))
15841 (with-current-buffer buffer
15842 (unless (derived-mode-p 'org-mode)
15843 (error "Buffer %s needs to be in Org mode" buffer))
15844 (org-with-wide-buffer
15845 (goto-char (point-min))
15846 (dolist (heading path)
15847 (let ((re (format org-complex-heading-regexp-format
15848 (regexp-quote heading)))
15849 (cnt 0))
15850 (while (re-search-forward re end t)
15851 (setq level (- (match-end 1) (match-beginning 1)))
15852 (when (and (>= level lmin) (<= level lmax))
15853 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15854 (when (= cnt 0)
15855 (error "Heading not found on level %d: %s" lmax heading))
15856 (when (> cnt 1)
15857 (error "Heading not unique on level %d: %s" lmax heading))
15858 (goto-char found)
15859 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15860 (setq end (save-excursion (org-end-of-subtree t t)))))
15861 (when (org-at-heading-p)
15862 (point-marker))))))
15864 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15865 "Find node HEADING in BUFFER.
15866 Return a marker to the heading if it was found, or nil if not.
15867 If POS-ONLY is set, return just the position instead of a marker.
15869 The heading text must match exact, but it may have a TODO keyword,
15870 a priority cookie and tags in the standard locations."
15871 (with-current-buffer (or buffer (current-buffer))
15872 (org-with-wide-buffer
15873 (goto-char (point-min))
15874 (let (case-fold-search)
15875 (when (re-search-forward
15876 (format org-complex-heading-regexp-format
15877 (regexp-quote heading)) nil t)
15878 (if pos-only
15879 (match-beginning 0)
15880 (move-marker (make-marker) (match-beginning 0))))))))
15882 (defun org-find-exact-heading-in-directory (heading &optional dir)
15883 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15884 When the target headline is found, return a marker to this location."
15885 (let ((files (directory-files (or dir default-directory)
15886 t "\\`[^.#].*\\.org\\'"))
15887 visiting m buffer)
15888 (catch 'found
15889 (dolist (file files)
15890 (message "trying %s" file)
15891 (setq visiting (org-find-base-buffer-visiting file))
15892 (setq buffer (or visiting (find-file-noselect file)))
15893 (setq m (org-find-exact-headline-in-buffer
15894 heading buffer))
15895 (when (and (not m) (not visiting)) (kill-buffer buffer))
15896 (and m (throw 'found m))))))
15898 (defun org-find-entry-with-id (ident)
15899 "Locate the entry that contains the ID property with exact value IDENT.
15900 IDENT can be a string, a symbol or a number, this function will search for
15901 the string representation of it.
15902 Return the position where this entry starts, or nil if there is no such entry."
15903 (interactive "sID: ")
15904 (let ((id (cond
15905 ((stringp ident) ident)
15906 ((symbolp ident) (symbol-name ident))
15907 ((numberp ident) (number-to-string ident))
15908 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15909 (org-with-wide-buffer (org-find-property "ID" id))))
15911 ;;;; Timestamps
15913 (defvar org-last-changed-timestamp nil)
15914 (defvar org-last-inserted-timestamp nil
15915 "The last time stamp inserted with `org-insert-time-stamp'.")
15917 (defun org-time-stamp (arg &optional inactive)
15918 "Prompt for a date/time and insert a time stamp.
15920 If the user specifies a time like HH:MM or if this command is
15921 called with at least one prefix argument, the time stamp contains
15922 the date and the time. Otherwise, only the date is included.
15924 All parts of a date not specified by the user are filled in from
15925 the timestamp at point, if any, or the current date/time
15926 otherwise.
15928 If there is already a timestamp at the cursor, it is replaced.
15930 With two universal prefix arguments, insert an active timestamp
15931 with the current time without prompting the user.
15933 When called from lisp, the timestamp is inactive if INACTIVE is
15934 non-nil."
15935 (interactive "P")
15936 (let* ((ts (cond
15937 ((org-at-date-range-p t)
15938 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15939 ((org-at-timestamp-p 'lax) (match-string 0))))
15940 ;; Default time is either the timestamp at point or today.
15941 ;; When entering a range, only the range start is considered.
15942 (default-time (if (not ts) (current-time)
15943 (apply #'encode-time (org-parse-time-string ts))))
15944 (default-input (and ts (org-get-compact-tod ts)))
15945 (repeater (and ts
15946 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15947 (match-string 0 ts)))
15948 org-time-was-given
15949 org-end-time-was-given
15950 (time
15951 (and (if (equal arg '(16)) (current-time)
15952 ;; Preserve `this-command' and `last-command'.
15953 (let ((this-command this-command)
15954 (last-command last-command))
15955 (org-read-date
15956 arg 'totime nil nil default-time default-input
15957 inactive))))))
15958 (cond
15959 ((and ts
15960 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15961 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15962 (insert "--")
15963 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15965 ;; Make sure we're on a timestamp. When in the middle of a date
15966 ;; range, move arbitrarily to range end.
15967 (unless (org-at-timestamp-p 'lax)
15968 (skip-chars-forward "-")
15969 (org-at-timestamp-p 'lax))
15970 (replace-match "")
15971 (setq org-last-changed-timestamp
15972 (org-insert-time-stamp
15973 time (or org-time-was-given arg)
15974 inactive nil nil (list org-end-time-was-given)))
15975 (when repeater
15976 (backward-char)
15977 (insert " " repeater)
15978 (setq org-last-changed-timestamp
15979 (concat (substring org-last-inserted-timestamp 0 -1)
15980 " " repeater ">")))
15981 (message "Timestamp updated"))
15982 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
15983 (t (org-insert-time-stamp
15984 time (or org-time-was-given arg) inactive nil nil
15985 (list org-end-time-was-given))))))
15987 ;; FIXME: can we use this for something else, like computing time differences?
15988 (defun org-get-compact-tod (s)
15989 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15990 (let* ((t1 (match-string 1 s))
15991 (h1 (string-to-number (match-string 2 s)))
15992 (m1 (string-to-number (match-string 3 s)))
15993 (t2 (and (match-end 4) (match-string 5 s)))
15994 (h2 (and t2 (string-to-number (match-string 6 s))))
15995 (m2 (and t2 (string-to-number (match-string 7 s))))
15996 dh dm)
15997 (if (not t2)
15999 (setq dh (- h2 h1) dm (- m2 m1))
16000 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16001 (concat t1 "+" (number-to-string dh)
16002 (and (/= 0 dm) (format ":%02d" dm)))))))
16004 (defun org-time-stamp-inactive (&optional arg)
16005 "Insert an inactive time stamp.
16006 An inactive time stamp is enclosed in square brackets instead of angle
16007 brackets. It is inactive in the sense that it does not trigger agenda entries,
16008 does not link to the calendar and cannot be changed with the S-cursor keys.
16009 So these are more for recording a certain time/date."
16010 (interactive "P")
16011 (org-time-stamp arg 'inactive))
16013 (defvar org-date-ovl (make-overlay 1 1))
16014 (overlay-put org-date-ovl 'face 'org-date-selected)
16015 (delete-overlay org-date-ovl)
16017 (defvar org-ans1) ; dynamically scoped parameter
16018 (defvar org-ans2) ; dynamically scoped parameter
16020 (defvar org-plain-time-of-day-regexp) ; defined below
16022 (defvar org-overriding-default-time nil) ; dynamically scoped
16023 (defvar org-read-date-overlay nil)
16024 (defvar org-dcst nil) ; dynamically scoped
16025 (defvar org-read-date-history nil)
16026 (defvar org-read-date-final-answer nil)
16027 (defvar org-read-date-analyze-futurep nil)
16028 (defvar org-read-date-analyze-forced-year nil)
16029 (defvar org-read-date-inactive)
16031 (defvar org-read-date-minibuffer-local-map
16032 (let* ((map (make-sparse-keymap)))
16033 (set-keymap-parent map minibuffer-local-map)
16034 (org-defkey map (kbd ".")
16035 (lambda () (interactive)
16036 ;; Are we at the beginning of the prompt?
16037 (if (looking-back "^[^:]+: "
16038 (let ((inhibit-field-text-motion t))
16039 (line-beginning-position)))
16040 (org-eval-in-calendar '(calendar-goto-today))
16041 (insert "."))))
16042 (org-defkey map (kbd "C-.")
16043 (lambda () (interactive)
16044 (org-eval-in-calendar '(calendar-goto-today))))
16045 (org-defkey map (kbd "M-S-<left>")
16046 (lambda () (interactive)
16047 (org-eval-in-calendar '(calendar-backward-month 1))))
16048 (org-defkey map (kbd "ESC S-<left>")
16049 (lambda () (interactive)
16050 (org-eval-in-calendar '(calendar-backward-month 1))))
16051 (org-defkey map (kbd "M-S-<right>")
16052 (lambda () (interactive)
16053 (org-eval-in-calendar '(calendar-forward-month 1))))
16054 (org-defkey map (kbd "ESC S-<right>")
16055 (lambda () (interactive)
16056 (org-eval-in-calendar '(calendar-forward-month 1))))
16057 (org-defkey map (kbd "M-S-<up>")
16058 (lambda () (interactive)
16059 (org-eval-in-calendar '(calendar-backward-year 1))))
16060 (org-defkey map (kbd "ESC S-<up>")
16061 (lambda () (interactive)
16062 (org-eval-in-calendar '(calendar-backward-year 1))))
16063 (org-defkey map (kbd "M-S-<down>")
16064 (lambda () (interactive)
16065 (org-eval-in-calendar '(calendar-forward-year 1))))
16066 (org-defkey map (kbd "ESC S-<down>")
16067 (lambda () (interactive)
16068 (org-eval-in-calendar '(calendar-forward-year 1))))
16069 (org-defkey map (kbd "S-<up>")
16070 (lambda () (interactive)
16071 (org-eval-in-calendar '(calendar-backward-week 1))))
16072 (org-defkey map (kbd "S-<down>")
16073 (lambda () (interactive)
16074 (org-eval-in-calendar '(calendar-forward-week 1))))
16075 (org-defkey map (kbd "S-<left>")
16076 (lambda () (interactive)
16077 (org-eval-in-calendar '(calendar-backward-day 1))))
16078 (org-defkey map (kbd "S-<right>")
16079 (lambda () (interactive)
16080 (org-eval-in-calendar '(calendar-forward-day 1))))
16081 (org-defkey map (kbd "!")
16082 (lambda () (interactive)
16083 (org-eval-in-calendar '(diary-view-entries))
16084 (message "")))
16085 (org-defkey map (kbd ">")
16086 (lambda () (interactive)
16087 (org-eval-in-calendar '(calendar-scroll-left 1))))
16088 (org-defkey map (kbd "<")
16089 (lambda () (interactive)
16090 (org-eval-in-calendar '(calendar-scroll-right 1))))
16091 (org-defkey map (kbd "C-v")
16092 (lambda () (interactive)
16093 (org-eval-in-calendar
16094 '(calendar-scroll-left-three-months 1))))
16095 (org-defkey map (kbd "M-v")
16096 (lambda () (interactive)
16097 (org-eval-in-calendar
16098 '(calendar-scroll-right-three-months 1))))
16099 map)
16100 "Keymap for minibuffer commands when using `org-read-date'.")
16102 (defvar org-def)
16103 (defvar org-defdecode)
16104 (defvar org-with-time)
16106 (defvar calendar-setup) ; Dynamically scoped.
16107 (defun org-read-date (&optional with-time to-time from-string prompt
16108 default-time default-input inactive)
16109 "Read a date, possibly a time, and make things smooth for the user.
16110 The prompt will suggest to enter an ISO date, but you can also enter anything
16111 which will at least partially be understood by `parse-time-string'.
16112 Unrecognized parts of the date will default to the current day, month, year,
16113 hour and minute. If this command is called to replace a timestamp at point,
16114 or to enter the second timestamp of a range, the default time is taken
16115 from the existing stamp. Furthermore, the command prefers the future,
16116 so if you are giving a date where the year is not given, and the day-month
16117 combination is already past in the current year, it will assume you
16118 mean next year. For details, see the manual. A few examples:
16120 3-2-5 --> 2003-02-05
16121 feb 15 --> currentyear-02-15
16122 2/15 --> currentyear-02-15
16123 sep 12 9 --> 2009-09-12
16124 12:45 --> today 12:45
16125 22 sept 0:34 --> currentyear-09-22 0:34
16126 12 --> currentyear-currentmonth-12
16127 Fri --> nearest Friday after today
16128 -Tue --> last Tuesday
16129 etc.
16131 Furthermore you can specify a relative date by giving, as the *first* thing
16132 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16133 change in days weeks, months, years.
16134 With a single plus or minus, the date is relative to today. With a double
16135 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16136 +4d --> four days from today
16137 +4 --> same as above
16138 +2w --> two weeks from today
16139 ++5 --> five days from default date
16141 The function understands only English month and weekday abbreviations.
16143 While prompting, a calendar is popped up - you can also select the
16144 date with the mouse (button 1). The calendar shows a period of three
16145 months. To scroll it to other months, use the keys `>' and `<'.
16146 If you don't like the calendar, turn it off with
16147 (setq org-read-date-popup-calendar nil)
16149 With optional argument TO-TIME, the date will immediately be converted
16150 to an internal time.
16151 With an optional argument WITH-TIME, the prompt will suggest to
16152 also insert a time. Note that when WITH-TIME is not set, you can
16153 still enter a time, and this function will inform the calling routine
16154 about this change. The calling routine may then choose to change the
16155 format used to insert the time stamp into the buffer to include the time.
16156 With optional argument FROM-STRING, read from this string instead from
16157 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16158 the time/date that is used for everything that is not specified by the
16159 user."
16160 (require 'parse-time)
16161 (let* ((org-with-time with-time)
16162 (org-time-stamp-rounding-minutes
16163 (if (equal org-with-time '(16))
16164 '(0 0)
16165 org-time-stamp-rounding-minutes))
16166 (org-dcst org-display-custom-times)
16167 (ct (org-current-time))
16168 (org-def (or org-overriding-default-time default-time ct))
16169 (org-defdecode (decode-time org-def))
16170 (cur-frame (selected-frame))
16171 (mouse-autoselect-window nil) ; Don't let the mouse jump
16172 (calendar-setup
16173 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16174 (calendar-move-hook nil)
16175 (calendar-view-diary-initially-flag nil)
16176 (calendar-view-holidays-initially-flag nil)
16177 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16178 ;; Rationalize `org-def' and `org-defdecode', if required.
16179 (when (< (nth 2 org-defdecode) org-extend-today-until)
16180 (setf (nth 2 org-defdecode) -1)
16181 (setf (nth 1 org-defdecode) 59)
16182 (setq org-def (apply #'encode-time org-defdecode))
16183 (setq org-defdecode (decode-time org-def)))
16184 (let* ((timestr (format-time-string
16185 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16186 org-def))
16187 (prompt (concat (if prompt (concat prompt " ") "")
16188 (format "Date+time [%s]: " timestr))))
16189 (cond
16190 (from-string (setq ans from-string))
16191 (org-read-date-popup-calendar
16192 (save-excursion
16193 (save-window-excursion
16194 (calendar)
16195 (when (eq calendar-setup 'calendar-only)
16196 (setq cal-frame
16197 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16198 (select-frame cal-frame))
16199 (org-eval-in-calendar '(setq cursor-type nil) t)
16200 (unwind-protect
16201 (progn
16202 (calendar-forward-day (- (time-to-days org-def)
16203 (calendar-absolute-from-gregorian
16204 (calendar-current-date))))
16205 (org-eval-in-calendar nil t)
16206 (let* ((old-map (current-local-map))
16207 (map (copy-keymap calendar-mode-map))
16208 (minibuffer-local-map
16209 (copy-keymap org-read-date-minibuffer-local-map)))
16210 (org-defkey map (kbd "RET") 'org-calendar-select)
16211 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16212 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16213 (unwind-protect
16214 (progn
16215 (use-local-map map)
16216 (setq org-read-date-inactive inactive)
16217 (add-hook 'post-command-hook 'org-read-date-display)
16218 (setq org-ans0
16219 (read-string prompt
16220 default-input
16221 'org-read-date-history
16222 nil))
16223 ;; org-ans0: from prompt
16224 ;; org-ans1: from mouse click
16225 ;; org-ans2: from calendar motion
16226 (setq ans
16227 (concat org-ans0 " " (or org-ans1 org-ans2))))
16228 (remove-hook 'post-command-hook 'org-read-date-display)
16229 (use-local-map old-map)
16230 (when org-read-date-overlay
16231 (delete-overlay org-read-date-overlay)
16232 (setq org-read-date-overlay nil)))))
16233 (bury-buffer "*Calendar*")
16234 (when cal-frame
16235 (delete-frame cal-frame)
16236 (select-frame-set-input-focus cur-frame))))))
16238 (t ; Naked prompt only
16239 (unwind-protect
16240 (setq ans (read-string prompt default-input
16241 'org-read-date-history timestr))
16242 (when org-read-date-overlay
16243 (delete-overlay org-read-date-overlay)
16244 (setq org-read-date-overlay nil))))))
16246 (setq final (org-read-date-analyze ans org-def org-defdecode))
16248 (when org-read-date-analyze-forced-year
16249 (message "Year was forced into %s"
16250 (if org-read-date-force-compatible-dates
16251 "compatible range (1970-2037)"
16252 "range representable on this machine"))
16253 (ding))
16255 ;; One round trip to get rid of 34th of August and stuff like that....
16256 (setq final (decode-time (apply 'encode-time final)))
16258 (setq org-read-date-final-answer ans)
16260 (if to-time
16261 (apply 'encode-time final)
16262 (if (and (boundp 'org-time-was-given) org-time-was-given)
16263 (format "%04d-%02d-%02d %02d:%02d"
16264 (nth 5 final) (nth 4 final) (nth 3 final)
16265 (nth 2 final) (nth 1 final))
16266 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16268 (defun org-read-date-display ()
16269 "Display the current date prompt interpretation in the minibuffer."
16270 (when org-read-date-display-live
16271 (when org-read-date-overlay
16272 (delete-overlay org-read-date-overlay))
16273 (when (minibufferp (current-buffer))
16274 (save-excursion
16275 (end-of-line 1)
16276 (while (not (equal (buffer-substring
16277 (max (point-min) (- (point) 4)) (point))
16278 " "))
16279 (insert " ")))
16280 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16281 " " (or org-ans1 org-ans2)))
16282 (org-end-time-was-given nil)
16283 (f (org-read-date-analyze ans org-def org-defdecode))
16284 (fmts (if org-dcst
16285 org-time-stamp-custom-formats
16286 org-time-stamp-formats))
16287 (fmt (if (or org-with-time
16288 (and (boundp 'org-time-was-given) org-time-was-given))
16289 (cdr fmts)
16290 (car fmts)))
16291 (txt (format-time-string fmt (apply 'encode-time f)))
16292 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16293 (txt (concat "=> " txt)))
16294 (when (and org-end-time-was-given
16295 (string-match org-plain-time-of-day-regexp txt))
16296 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16297 org-end-time-was-given
16298 (substring txt (match-end 0)))))
16299 (when org-read-date-analyze-futurep
16300 (setq txt (concat txt " (=>F)")))
16301 (setq org-read-date-overlay
16302 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16303 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16305 (defun org-read-date-analyze (ans def defdecode)
16306 "Analyze the combined answer of the date prompt."
16307 ;; FIXME: cleanup and comment
16308 ;; Pass `current-time' result to `decode-time' (instead of calling
16309 ;; without arguments) so that only `current-time' has to be
16310 ;; overridden in tests.
16311 (let ((org-def def)
16312 (org-defdecode defdecode)
16313 (nowdecode (decode-time (current-time)))
16314 delta deltan deltaw deltadef year month day
16315 hour minute second wday pm h2 m2 tl wday1
16316 iso-year iso-weekday iso-week iso-date futurep kill-year)
16317 (setq org-read-date-analyze-futurep nil
16318 org-read-date-analyze-forced-year nil)
16319 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16320 (setq ans "+0"))
16322 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16323 (setq ans (replace-match "" t t ans)
16324 deltan (car delta)
16325 deltaw (nth 1 delta)
16326 deltadef (nth 2 delta)))
16328 ;; Check if there is an iso week date in there. If yes, store the
16329 ;; info and postpone interpreting it until the rest of the parsing
16330 ;; is done.
16331 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16332 (setq iso-year (when (match-end 1)
16333 (org-small-year-to-year
16334 (string-to-number (match-string 1 ans))))
16335 iso-weekday (when (match-end 3)
16336 (string-to-number (match-string 3 ans)))
16337 iso-week (string-to-number (match-string 2 ans)))
16338 (setq ans (replace-match "" t t ans)))
16340 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16341 (when (string-match
16342 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16343 (setq year (if (match-end 2)
16344 (string-to-number (match-string 2 ans))
16345 (progn (setq kill-year t)
16346 (string-to-number (format-time-string "%Y"))))
16347 month (string-to-number (match-string 3 ans))
16348 day (string-to-number (match-string 4 ans)))
16349 (setq year (org-small-year-to-year year))
16350 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16351 t nil ans)))
16353 ;; Help matching dotted european dates
16354 (when (string-match
16355 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16356 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16357 (setq kill-year t)
16358 (string-to-number (format-time-string "%Y")))
16359 day (string-to-number (match-string 1 ans))
16360 month (string-to-number (match-string 2 ans))
16361 ans (replace-match (format "%04d-%02d-%02d" year month day)
16362 t nil ans)))
16364 ;; Help matching american dates, like 5/30 or 5/30/7
16365 (when (string-match
16366 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16367 (setq year (if (match-end 4)
16368 (string-to-number (match-string 4 ans))
16369 (progn (setq kill-year t)
16370 (string-to-number (format-time-string "%Y"))))
16371 month (string-to-number (match-string 1 ans))
16372 day (string-to-number (match-string 2 ans)))
16373 (setq year (org-small-year-to-year year))
16374 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16375 t nil ans)))
16376 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16377 ;; If there is a time with am/pm, and *no* time without it, we convert
16378 ;; so that matching will be successful.
16379 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16380 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16381 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16382 (setq hour (string-to-number (match-string 1 ans))
16383 minute (if (match-end 3)
16384 (string-to-number (match-string 3 ans))
16386 pm (equal ?p
16387 (string-to-char (downcase (match-string 4 ans)))))
16388 (if (and (= hour 12) (not pm))
16389 (setq hour 0)
16390 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16391 (setq ans (replace-match (format "%02d:%02d" hour minute)
16392 t t ans))))
16394 ;; Check if a time range is given as a duration
16395 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16396 (setq hour (string-to-number (match-string 1 ans))
16397 h2 (+ hour (string-to-number (match-string 3 ans)))
16398 minute (string-to-number (match-string 2 ans))
16399 m2 (+ minute (if (match-end 5) (string-to-number
16400 (match-string 5 ans))0)))
16401 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16402 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16403 t t ans)))
16405 ;; Check if there is a time range
16406 (when (boundp 'org-end-time-was-given)
16407 (setq org-time-was-given nil)
16408 (when (and (string-match org-plain-time-of-day-regexp ans)
16409 (match-end 8))
16410 (setq org-end-time-was-given (match-string 8 ans))
16411 (setq ans (concat (substring ans 0 (match-beginning 7))
16412 (substring ans (match-end 7))))))
16414 (setq tl (parse-time-string ans)
16415 day (or (nth 3 tl) (nth 3 org-defdecode))
16416 month
16417 (cond ((nth 4 tl))
16418 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16419 ;; Day was specified. Make sure DAY+MONTH
16420 ;; combination happens in the future.
16421 ((nth 3 tl)
16422 (setq futurep t)
16423 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16424 (nth 4 nowdecode)))
16425 (t (nth 4 org-defdecode)))
16426 year
16427 (cond ((and (not kill-year) (nth 5 tl)))
16428 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16429 ;; Month was guessed in the future and is at least
16430 ;; equal to NOWDECODE's. Fix year accordingly.
16431 (futurep
16432 (if (or (> month (nth 4 nowdecode))
16433 (>= day (nth 3 nowdecode)))
16434 (nth 5 nowdecode)
16435 (1+ (nth 5 nowdecode))))
16436 ;; Month was specified. Make sure MONTH+YEAR
16437 ;; combination happens in the future.
16438 ((nth 4 tl)
16439 (setq futurep t)
16440 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16441 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16442 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16443 (t (nth 5 nowdecode))))
16444 (t (nth 5 org-defdecode)))
16445 hour (or (nth 2 tl) (nth 2 org-defdecode))
16446 minute (or (nth 1 tl) (nth 1 org-defdecode))
16447 second (or (nth 0 tl) 0)
16448 wday (nth 6 tl))
16450 (when (and (eq org-read-date-prefer-future 'time)
16451 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16452 (equal day (nth 3 nowdecode))
16453 (equal month (nth 4 nowdecode))
16454 (equal year (nth 5 nowdecode))
16455 (nth 2 tl)
16456 (or (< (nth 2 tl) (nth 2 nowdecode))
16457 (and (= (nth 2 tl) (nth 2 nowdecode))
16458 (nth 1 tl)
16459 (< (nth 1 tl) (nth 1 nowdecode)))))
16460 (setq day (1+ day)
16461 futurep t))
16463 ;; Special date definitions below
16464 (cond
16465 (iso-week
16466 ;; There was an iso week
16467 (require 'cal-iso)
16468 (setq futurep nil)
16469 (setq year (or iso-year year)
16470 day (or iso-weekday wday 1)
16471 wday nil ; to make sure that the trigger below does not match
16472 iso-date (calendar-gregorian-from-absolute
16473 (calendar-iso-to-absolute
16474 (list iso-week day year))))
16475 ; FIXME: Should we also push ISO weeks into the future?
16476 ; (when (and org-read-date-prefer-future
16477 ; (not iso-year)
16478 ; (< (calendar-absolute-from-gregorian iso-date)
16479 ; (time-to-days (current-time))))
16480 ; (setq year (1+ year)
16481 ; iso-date (calendar-gregorian-from-absolute
16482 ; (calendar-iso-to-absolute
16483 ; (list iso-week day year)))))
16484 (setq month (car iso-date)
16485 year (nth 2 iso-date)
16486 day (nth 1 iso-date)))
16487 (deltan
16488 (setq futurep nil)
16489 (unless deltadef
16490 ;; Pass `current-time' result to `decode-time' (instead of
16491 ;; calling without arguments) so that only `current-time' has
16492 ;; to be overridden in tests.
16493 (let ((now (decode-time (current-time))))
16494 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16495 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16496 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16497 ((equal deltaw "m") (setq month (+ month deltan)))
16498 ((equal deltaw "y") (setq year (+ year deltan)))))
16499 ((and wday (not (nth 3 tl)))
16500 ;; Weekday was given, but no day, so pick that day in the week
16501 ;; on or after the derived date.
16502 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16503 (unless (equal wday wday1)
16504 (setq day (+ day (% (- wday wday1 -7) 7))))))
16505 (when (and (boundp 'org-time-was-given)
16506 (nth 2 tl))
16507 (setq org-time-was-given t))
16508 (when (< year 100) (setq year (+ 2000 year)))
16509 ;; Check of the date is representable
16510 (if org-read-date-force-compatible-dates
16511 (progn
16512 (when (< year 1970)
16513 (setq year 1970 org-read-date-analyze-forced-year t))
16514 (when (> year 2037)
16515 (setq year 2037 org-read-date-analyze-forced-year t)))
16516 (condition-case nil
16517 (ignore (encode-time second minute hour day month year))
16518 (error
16519 (setq year (nth 5 org-defdecode))
16520 (setq org-read-date-analyze-forced-year t))))
16521 (setq org-read-date-analyze-futurep futurep)
16522 (list second minute hour day month year)))
16524 (defvar parse-time-weekdays)
16525 (defun org-read-date-get-relative (s today default)
16526 "Check string S for special relative date string.
16527 TODAY and DEFAULT are internal times, for today and for a default.
16528 Return shift list (N what def-flag)
16529 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16530 N is the number of WHATs to shift.
16531 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16532 the DEFAULT date rather than TODAY."
16533 (require 'parse-time)
16534 (when (and
16535 (string-match
16536 (concat
16537 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16538 "\\([0-9]+\\)?"
16539 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16540 "\\([ \t]\\|$\\)") s)
16541 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16542 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16543 (string-to-char (substring (match-string 1 s) -1))
16544 ?+))
16545 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16546 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16547 (what (if (match-end 3) (match-string 3 s) "d"))
16548 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16549 (date (if rel default today))
16550 (wday (nth 6 (decode-time date)))
16551 delta)
16552 (if wday1
16553 (progn
16554 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16555 (when (= delta 0) (setq delta 7))
16556 (when (= dir ?-)
16557 (setq delta (- delta 7))
16558 (when (= delta 0) (setq delta -7)))
16559 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16560 (list delta "d" rel))
16561 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16563 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16564 "Turn a user-specified date into the internal representation.
16565 The internal representation needed by the calendar is (month day year).
16566 This is a wrapper to handle the brain-dead convention in calendar that
16567 user function argument order change dependent on argument order."
16568 (pcase calendar-date-style
16569 (`american (list arg1 arg2 arg3))
16570 (`european (list arg2 arg1 arg3))
16571 (`iso (list arg2 arg3 arg1))))
16573 (defun org-eval-in-calendar (form &optional keepdate)
16574 "Eval FORM in the calendar window and return to current window.
16575 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16576 (let ((sf (selected-frame))
16577 (sw (selected-window)))
16578 (select-window (get-buffer-window "*Calendar*" t))
16579 (eval form)
16580 (when (and (not keepdate) (calendar-cursor-to-date))
16581 (let* ((date (calendar-cursor-to-date))
16582 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16583 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16584 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16585 (select-window sw)
16586 (select-frame-set-input-focus sf)))
16588 (defun org-calendar-select ()
16589 "Return to `org-read-date' with the date currently selected.
16590 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16591 (interactive)
16592 (when (calendar-cursor-to-date)
16593 (let* ((date (calendar-cursor-to-date))
16594 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16595 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16596 (when (active-minibuffer-window) (exit-minibuffer))))
16598 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16599 "Insert a date stamp for the date given by the internal TIME.
16600 See `format-time-string' for the format of TIME.
16601 WITH-HM means use the stamp format that includes the time of the day.
16602 INACTIVE means use square brackets instead of angular ones, so that the
16603 stamp will not contribute to the agenda.
16604 PRE and POST are optional strings to be inserted before and after the
16605 stamp.
16606 The command returns the inserted time stamp."
16607 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16608 stamp)
16609 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16610 (insert-before-markers (or pre ""))
16611 (when (listp extra)
16612 (setq extra (car extra))
16613 (if (and (stringp extra)
16614 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16615 (setq extra (format "-%02d:%02d"
16616 (string-to-number (match-string 1 extra))
16617 (string-to-number (match-string 2 extra))))
16618 (setq extra nil)))
16619 (when extra
16620 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16621 (insert-before-markers (setq stamp (format-time-string fmt time)))
16622 (insert-before-markers (or post ""))
16623 (setq org-last-inserted-timestamp stamp)))
16625 (defun org-toggle-time-stamp-overlays ()
16626 "Toggle the use of custom time stamp formats."
16627 (interactive)
16628 (setq org-display-custom-times (not org-display-custom-times))
16629 (unless org-display-custom-times
16630 (let ((p (point-min)) (bmp (buffer-modified-p)))
16631 (while (setq p (next-single-property-change p 'display))
16632 (when (and (get-text-property p 'display)
16633 (eq (get-text-property p 'face) 'org-date))
16634 (remove-text-properties
16635 p (setq p (next-single-property-change p 'display))
16636 '(display t))))
16637 (set-buffer-modified-p bmp)))
16638 (org-restart-font-lock)
16639 (setq org-table-may-need-update t)
16640 (if org-display-custom-times
16641 (message "Time stamps are overlaid with custom format")
16642 (message "Time stamp overlays removed")))
16644 (defun org-display-custom-time (beg end)
16645 "Overlay modified time stamp format over timestamp between BEG and END."
16646 (let* ((ts (buffer-substring beg end))
16647 t1 with-hm tf time str (off 0))
16648 (save-match-data
16649 (setq t1 (org-parse-time-string ts t))
16650 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16651 (setq off (- (match-end 0) (match-beginning 0)))))
16652 (setq end (- end off))
16653 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16654 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16655 time (org-fix-decoded-time t1)
16656 str (org-add-props
16657 (format-time-string
16658 (substring tf 1 -1) (apply 'encode-time time))
16659 nil 'mouse-face 'highlight))
16660 (put-text-property beg end 'display str)))
16662 (defun org-fix-decoded-time (time)
16663 "Set 0 instead of nil for the first 6 elements of time.
16664 Don't touch the rest."
16665 (let ((n 0))
16666 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16668 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16669 "Difference between TIMESTAMP-STRING and now in days.
16670 If SECONDS is non-nil, return the difference in seconds."
16671 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16672 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16673 (funcall fdiff (current-time)))))
16675 (defun org-deadline-close-p (timestamp-string &optional ndays)
16676 "Is the time in TIMESTAMP-STRING close to the current date?"
16677 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16678 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16679 (not (org-entry-is-done-p))))
16681 (defun org-get-wdays (ts &optional delay zero-delay)
16682 "Get the deadline lead time appropriate for timestring TS.
16683 When DELAY is non-nil, get the delay time for scheduled items
16684 instead of the deadline lead time. When ZERO-DELAY is non-nil
16685 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16686 don't try to find the delay cookie in the scheduled timestamp."
16687 (let ((tv (if delay org-scheduled-delay-days
16688 org-deadline-warning-days)))
16689 (cond
16690 ((or (and delay (< tv 0))
16691 (and delay zero-delay (<= tv 0))
16692 (and (not delay) (<= tv 0)))
16693 ;; Enforce this value no matter what
16694 (- tv))
16695 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16696 ;; lead time is specified.
16697 (floor (* (string-to-number (match-string 1 ts))
16698 (cdr (assoc (match-string 2 ts)
16699 '(("d" . 1) ("w" . 7)
16700 ("m" . 30.4) ("y" . 365.25)
16701 ("h" . 0.041667)))))))
16702 ;; go for the default.
16703 (t tv))))
16705 (defun org-calendar-select-mouse (ev)
16706 "Return to `org-read-date' with the date currently selected.
16707 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16708 (interactive "e")
16709 (mouse-set-point ev)
16710 (when (calendar-cursor-to-date)
16711 (let* ((date (calendar-cursor-to-date))
16712 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16713 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16714 (when (active-minibuffer-window) (exit-minibuffer))))
16716 (defun org-check-deadlines (ndays)
16717 "Check if there are any deadlines due or past due.
16718 A deadline is considered due if it happens within `org-deadline-warning-days'
16719 days from today's date. If the deadline appears in an entry marked DONE,
16720 it is not shown. A numeric prefix argument NDAYS can be used to test that
16721 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16722 are shown."
16723 (interactive "P")
16724 (let* ((org-warn-days
16725 (cond
16726 ((equal ndays '(4)) 100000)
16727 (ndays (prefix-numeric-value ndays))
16728 (t (abs org-deadline-warning-days))))
16729 (case-fold-search nil)
16730 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16731 (callback
16732 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16733 (message "%d deadlines past-due or due within %d days"
16734 (org-occur regexp nil callback)
16735 org-warn-days)))
16737 (defsubst org-re-timestamp (type)
16738 "Return a regexp for timestamp TYPE.
16739 Allowed values for TYPE are:
16741 all: all timestamps
16742 active: only active timestamps (<...>)
16743 inactive: only inactive timestamps ([...])
16744 scheduled: only scheduled timestamps
16745 deadline: only deadline timestamps
16746 closed: only closed time-stamps
16748 When TYPE is nil, fall back on returning a regexp that matches
16749 both scheduled and deadline timestamps."
16750 (cl-case type
16751 (all org-ts-regexp-both)
16752 (active org-ts-regexp)
16753 (inactive org-ts-regexp-inactive)
16754 (scheduled org-scheduled-time-regexp)
16755 (deadline org-deadline-time-regexp)
16756 (closed org-closed-time-regexp)
16757 (otherwise
16758 (concat "\\<"
16759 (regexp-opt (list org-deadline-string org-scheduled-string))
16760 " *<\\([^>]+\\)>"))))
16762 (defun org-check-before-date (d)
16763 "Check if there are deadlines or scheduled entries before date D."
16764 (interactive (list (org-read-date)))
16765 (let* ((case-fold-search nil)
16766 (regexp (org-re-timestamp org-ts-type))
16767 (ts-type org-ts-type)
16768 (callback
16769 (lambda ()
16770 (let ((match (match-string 1)))
16771 (and (if (memq ts-type '(active inactive all))
16772 (eq (org-element-type (save-excursion
16773 (backward-char)
16774 (org-element-context)))
16775 'timestamp)
16776 (org-at-planning-p))
16777 (time-less-p
16778 (org-time-string-to-time match)
16779 (org-time-string-to-time d)))))))
16780 (message "%d entries before %s"
16781 (org-occur regexp nil callback)
16782 d)))
16784 (defun org-check-after-date (d)
16785 "Check if there are deadlines or scheduled entries after date D."
16786 (interactive (list (org-read-date)))
16787 (let* ((case-fold-search nil)
16788 (regexp (org-re-timestamp org-ts-type))
16789 (ts-type org-ts-type)
16790 (callback
16791 (lambda ()
16792 (let ((match (match-string 1)))
16793 (and (if (memq ts-type '(active inactive all))
16794 (eq (org-element-type (save-excursion
16795 (backward-char)
16796 (org-element-context)))
16797 'timestamp)
16798 (org-at-planning-p))
16799 (not (time-less-p
16800 (org-time-string-to-time match)
16801 (org-time-string-to-time d))))))))
16802 (message "%d entries after %s"
16803 (org-occur regexp nil callback)
16804 d)))
16806 (defun org-check-dates-range (start-date end-date)
16807 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16808 (interactive (list (org-read-date nil nil nil "Range starts")
16809 (org-read-date nil nil nil "Range end")))
16810 (let ((case-fold-search nil)
16811 (regexp (org-re-timestamp org-ts-type))
16812 (callback
16813 (let ((type org-ts-type))
16814 (lambda ()
16815 (let ((match (match-string 1)))
16816 (and
16817 (if (memq type '(active inactive all))
16818 (eq (org-element-type (save-excursion
16819 (backward-char)
16820 (org-element-context)))
16821 'timestamp)
16822 (org-at-planning-p))
16823 (not (time-less-p
16824 (org-time-string-to-time match)
16825 (org-time-string-to-time start-date)))
16826 (time-less-p
16827 (org-time-string-to-time match)
16828 (org-time-string-to-time end-date))))))))
16829 (message "%d entries between %s and %s"
16830 (org-occur regexp nil callback) start-date end-date)))
16832 (defun org-evaluate-time-range (&optional to-buffer)
16833 "Evaluate a time range by computing the difference between start and end.
16834 Normally the result is just printed in the echo area, but with prefix arg
16835 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16836 If the time range is actually in a table, the result is inserted into the
16837 next column.
16838 For time difference computation, a year is assumed to be exactly 365
16839 days in order to avoid rounding problems."
16840 (interactive "P")
16842 (org-clock-update-time-maybe)
16843 (save-excursion
16844 (unless (org-at-date-range-p t)
16845 (goto-char (point-at-bol))
16846 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16847 (unless (org-at-date-range-p t)
16848 (user-error "Not at a time-stamp range, and none found in current line")))
16849 (let* ((ts1 (match-string 1))
16850 (ts2 (match-string 2))
16851 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16852 (match-end (match-end 0))
16853 (time1 (org-time-string-to-time ts1))
16854 (time2 (org-time-string-to-time ts2))
16855 (t1 (float-time time1))
16856 (t2 (float-time time2))
16857 (diff (abs (- t2 t1)))
16858 (negative (< (- t2 t1) 0))
16859 ;; (ys (floor (* 365 24 60 60)))
16860 (ds (* 24 60 60))
16861 (hs (* 60 60))
16862 (fy "%dy %dd %02d:%02d")
16863 (fy1 "%dy %dd")
16864 (fd "%dd %02d:%02d")
16865 (fd1 "%dd")
16866 (fh "%02d:%02d")
16867 y d h m align)
16868 (if havetime
16869 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16871 d (floor (/ diff ds)) diff (mod diff ds)
16872 h (floor (/ diff hs)) diff (mod diff hs)
16873 m (floor (/ diff 60)))
16874 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16876 d (floor (+ (/ diff ds) 0.5))
16877 h 0 m 0))
16878 (if (not to-buffer)
16879 (message "%s" (org-make-tdiff-string y d h m))
16880 (if (org-at-table-p)
16881 (progn
16882 (goto-char match-end)
16883 (setq align t)
16884 (and (looking-at " *|") (goto-char (match-end 0))))
16885 (goto-char match-end))
16886 (when (looking-at
16887 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16888 (replace-match ""))
16889 (when negative (insert " -"))
16890 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16891 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16892 (insert " " (format fh h m))))
16893 (when align (org-table-align))
16894 (message "Time difference inserted")))))
16896 (defun org-make-tdiff-string (y d h m)
16897 (let ((fmt "")
16898 (l nil))
16899 (when (> y 0)
16900 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16901 (push y l))
16902 (when (> d 0)
16903 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16904 (push d l))
16905 (when (> h 0)
16906 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16907 (push h l))
16908 (when (> m 0)
16909 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16910 (push m l))
16911 (apply 'format fmt (nreverse l))))
16913 (defun org-time-string-to-time (s)
16914 "Convert timestamp string S into internal time."
16915 (apply #'encode-time (org-parse-time-string s)))
16917 (defun org-time-string-to-seconds (s)
16918 "Convert a timestamp string S into a number of seconds."
16919 (float-time (org-time-string-to-time s)))
16921 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16923 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16924 "Convert time stamp S to an absolute day number.
16926 If DAYNR in non-nil, and there is a specifier for a cyclic time
16927 stamp, get the closest date to DAYNR. If PREFER is
16928 `past' (respectively `future') return a date past (respectively
16929 after) or equal to DAYNR.
16931 POS is the location of time stamp S, as a buffer position in
16932 BUFFER.
16934 Diary sexp timestamps are matched against DAYNR, when non-nil.
16935 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16936 signaled."
16937 (cond
16938 ((string-match "\\`%%\\((.*)\\)" s)
16939 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16940 ;; only able to match individual dates. If it fails, raise an
16941 ;; error.
16942 (if (and daynr
16943 (org-diary-sexp-entry
16944 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16945 daynr
16946 (signal 'org-diary-sexp-no-match (list s))))
16947 (daynr (org-closest-date s daynr prefer))
16948 (t (time-to-days
16949 (condition-case errdata
16950 (apply #'encode-time (org-parse-time-string s))
16951 (error (error "Bad timestamp `%s'%s\nError was: %s"
16953 (if (not (and buffer pos)) ""
16954 (format-message " at %d in buffer `%s'" pos buffer))
16955 (cdr errdata))))))))
16957 (defun org-days-to-iso-week (days)
16958 "Return the iso week number."
16959 (require 'cal-iso)
16960 (car (calendar-iso-from-absolute days)))
16962 (defun org-small-year-to-year (year)
16963 "Convert 2-digit years into 4-digit years.
16964 YEAR is expanded into one of the 30 next years, if possible, or
16965 into a past one. Any year larger than 99 is returned unchanged."
16966 (if (>= year 100) year
16967 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
16968 (century (/ current 100))
16969 (offset (- year (% current 100))))
16970 (cond ((> offset 30) (+ (* (1- century) 100) year))
16971 ((> offset -70) (+ (* century 100) year))
16972 (t (+ (* (1+ century) 100) year))))))
16974 (defun org-time-from-absolute (d)
16975 "Return the time corresponding to date D.
16976 D may be an absolute day number, or a calendar-type list (month day year)."
16977 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16978 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16980 (defvar org-agenda-current-date)
16981 (defun org-calendar-holiday ()
16982 "List of holidays, for Diary display in Org mode."
16983 (require 'holidays)
16984 (let ((hl (calendar-check-holidays org-agenda-current-date)))
16985 (and hl (mapconcat #'identity hl "; "))))
16987 (defun org-diary-sexp-entry (sexp entry d)
16988 "Process a SEXP diary ENTRY for date D."
16989 (require 'diary-lib)
16990 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
16991 ;; dynamically.
16992 (let* ((sexp `(let ((entry ,entry)
16993 (date ',d))
16994 ,(car (read-from-string sexp))))
16995 (result (if calendar-debug-sexp (eval sexp)
16996 (condition-case nil
16997 (eval sexp)
16998 (error
16999 (beep)
17000 (message "Bad sexp at line %d in %s: %s"
17001 (org-current-line)
17002 (buffer-file-name) sexp)
17003 (sleep-for 2))))))
17004 (cond ((stringp result) (split-string result "; "))
17005 ((and (consp result)
17006 (not (consp (cdr result)))
17007 (stringp (cdr result))) (cdr result))
17008 ((and (consp result)
17009 (stringp (car result))) result)
17010 (result entry))))
17012 (defun org-diary-to-ical-string (frombuf)
17013 "Get iCalendar entries from diary entries in buffer FROMBUF.
17014 This uses the icalendar.el library."
17015 (let* ((tmpdir temporary-file-directory)
17016 (tmpfile (make-temp-name
17017 (expand-file-name "orgics" tmpdir)))
17018 buf rtn b e)
17019 (with-current-buffer frombuf
17020 (icalendar-export-region (point-min) (point-max) tmpfile)
17021 (setq buf (find-buffer-visiting tmpfile))
17022 (set-buffer buf)
17023 (goto-char (point-min))
17024 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17025 (setq b (match-beginning 0)))
17026 (goto-char (point-max))
17027 (when (re-search-backward "^END:VEVENT" nil t)
17028 (setq e (match-end 0)))
17029 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17030 (kill-buffer buf)
17031 (delete-file tmpfile)
17032 rtn))
17034 (defun org-closest-date (start current prefer)
17035 "Return closest date to CURRENT starting from START.
17037 CURRENT and START are both time stamps.
17039 When PREFER is `past', return a date that is either CURRENT or
17040 past. When PREFER is `future', return a date that is either
17041 CURRENT or future.
17043 Only time stamps with a repeater are modified. Any other time
17044 stamp stay unchanged. In any case, return value is an absolute
17045 day number."
17046 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17047 ;; No repeater. Do not shift time stamp.
17048 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17049 (let ((value (string-to-number (match-string 1 start)))
17050 (type (match-string 2 start)))
17051 (if (= 0 value)
17052 ;; Repeater with a 0-value is considered as void.
17053 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17054 (let* ((base (org-date-to-gregorian start))
17055 (target (org-date-to-gregorian current))
17056 (sday (calendar-absolute-from-gregorian base))
17057 (cday (calendar-absolute-from-gregorian target))
17058 n1 n2)
17059 ;; If START is already past CURRENT, just return START.
17060 (if (<= cday sday) sday
17061 ;; Compute closest date before (N1) and closest date past
17062 ;; (N2) CURRENT.
17063 (pcase type
17064 ("h"
17065 (let ((missing-hours
17066 (mod (+ (- (* 24 (- cday sday))
17067 (nth 2 (org-parse-time-string start)))
17068 org-extend-today-until)
17069 value)))
17070 (setf n1 (if (= missing-hours 0) cday
17071 (- cday (1+ (/ missing-hours 24)))))
17072 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17073 ((or "d" "w")
17074 (let ((value (if (equal type "w") (* 7 value) value)))
17075 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17076 (setf n2 (+ n1 value))))
17077 ("m"
17078 (let* ((add-months
17079 (lambda (d n)
17080 ;; Add N months to gregorian date D, i.e.,
17081 ;; a list (MONTH DAY YEAR). Return a valid
17082 ;; gregorian date.
17083 (let ((m (+ (nth 0 d) n)))
17084 (list (mod m 12)
17085 (nth 1 d)
17086 (+ (/ m 12) (nth 2 d))))))
17087 (months ; Complete months to TARGET.
17088 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17089 (- (nth 0 target) (nth 0 base))
17090 ;; If START's day is greater than
17091 ;; TARGET's, remove incomplete month.
17092 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17093 value)
17094 value))
17095 (before (funcall add-months base months)))
17096 (setf n1 (calendar-absolute-from-gregorian before))
17097 (setf n2
17098 (calendar-absolute-from-gregorian
17099 (funcall add-months before value)))))
17101 (let* ((d (nth 1 base))
17102 (m (nth 0 base))
17103 (y (nth 2 base))
17104 (years ; Complete years to TARGET.
17105 (* (/ (- (nth 2 target)
17107 ;; If START's month and day are
17108 ;; greater than TARGET's, remove
17109 ;; incomplete year.
17110 (if (or (> (nth 0 target) m)
17111 (and (= (nth 0 target) m)
17112 (> (nth 1 target) d)))
17115 value)
17116 value))
17117 (before (list m d (+ y years))))
17118 (setf n1 (calendar-absolute-from-gregorian before))
17119 (setf n2 (calendar-absolute-from-gregorian
17120 (list m d (+ (nth 2 before) value)))))))
17121 ;; Handle PREFER parameter, if any.
17122 (cond
17123 ((eq prefer 'past) (if (= cday n2) n2 n1))
17124 ((eq prefer 'future) (if (= cday n1) n1 n2))
17125 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17127 (defun org-date-to-gregorian (d)
17128 "Turn any specification of date D into a Gregorian date for the calendar."
17129 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17130 ((and (listp d) (= (length d) 3)) d)
17131 ((stringp d)
17132 (let ((d (org-parse-time-string d)))
17133 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17134 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17136 (defun org-parse-time-string (s &optional nodefault)
17137 "Parse the standard Org time string.
17139 This should be a lot faster than the normal `parse-time-string'.
17141 If time is not given, defaults to 0:00. However, with optional
17142 NODEFAULT, hour and minute fields will be nil if not given."
17143 (cond ((string-match org-ts-regexp0 s)
17144 (list 0
17145 (when (or (match-beginning 8) (not nodefault))
17146 (string-to-number (or (match-string 8 s) "0")))
17147 (when (or (match-beginning 7) (not nodefault))
17148 (string-to-number (or (match-string 7 s) "0")))
17149 (string-to-number (match-string 4 s))
17150 (string-to-number (match-string 3 s))
17151 (string-to-number (match-string 2 s))
17152 nil nil nil))
17153 ((string-match "^<[^>]+>$" s)
17154 ;; FIXME: `decode-time' needs to be called with ZONE as its
17155 ;; second argument. However, this requires at least Emacs
17156 ;; 25.1. We can do it when we switch to this version as our
17157 ;; minimal requirement.
17158 (decode-time (seconds-to-time (org-matcher-time s))))
17159 (t (error "Not a standard Org time string: %s" s))))
17161 (defun org-timestamp-up (&optional arg)
17162 "Increase the date item at the cursor by one.
17163 If the cursor is on the year, change the year. If it is on the month,
17164 the day or the time, change that.
17165 With prefix ARG, change by that many units."
17166 (interactive "p")
17167 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17169 (defun org-timestamp-down (&optional arg)
17170 "Decrease the date item at the cursor by one.
17171 If the cursor is on the year, change the year. If it is on the month,
17172 the day or the time, change that.
17173 With prefix ARG, change by that many units."
17174 (interactive "p")
17175 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17177 (defun org-timestamp-up-day (&optional arg)
17178 "Increase the date in the time stamp by one day.
17179 With prefix ARG, change that many days."
17180 (interactive "p")
17181 (if (and (not (org-at-timestamp-p 'lax))
17182 (org-at-heading-p))
17183 (org-todo 'up)
17184 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17186 (defun org-timestamp-down-day (&optional arg)
17187 "Decrease the date in the time stamp by one day.
17188 With prefix ARG, change that many days."
17189 (interactive "p")
17190 (if (and (not (org-at-timestamp-p 'lax))
17191 (org-at-heading-p))
17192 (org-todo 'down)
17193 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17195 (defun org-at-timestamp-p (&optional extended)
17196 "Non-nil if point is inside a timestamp.
17198 By default, the function only consider syntactically valid active
17199 timestamps. However, the caller may have a broader definition
17200 for timestamps. As a consequence, optional argument EXTENDED can
17201 be set to the following values
17203 `inactive'
17205 Include also syntactically valid inactive timestamps.
17207 `agenda'
17209 Include timestamps allowed in Agenda, i.e., those in
17210 properties drawers, planning lines and clock lines.
17212 `lax'
17214 Ignore context. The function matches any part of the
17215 document looking like a timestamp. This includes comments,
17216 example blocks...
17218 For backward-compatibility with Org 9.0, every other non-nil
17219 value is equivalent to `inactive'.
17221 When at a timestamp, return the position of the point as a symbol
17222 among `bracket', `after', `year', `month', `hour', `minute',
17223 `day' or a number of character from the last know part of the
17224 time stamp.
17226 When matching, the match groups are the following:
17227 group 1: year
17228 group 2: month
17229 group 3: day number
17230 group 4: day name
17231 group 5: hours, if any
17232 group 6: minutes, if any"
17233 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17234 (pos (point))
17235 (match?
17236 (let ((boundaries (org-in-regexp regexp)))
17237 (save-match-data
17238 (cond ((null boundaries) nil)
17239 ((eq extended 'lax) t)
17241 (or (and (eq extended 'agenda)
17242 (or (org-at-planning-p)
17243 (org-at-property-p)
17244 (and (bound-and-true-p
17245 org-agenda-include-inactive-timestamps)
17246 (org-at-clock-log-p))))
17247 (eq 'timestamp
17248 (save-excursion
17249 (when (= pos (cdr boundaries)) (forward-char -1))
17250 (org-element-type (org-element-context)))))))))))
17251 (cond
17252 ((not match?) nil)
17253 ((= pos (match-beginning 0)) 'bracket)
17254 ;; Distinguish location right before the closing bracket from
17255 ;; right after it.
17256 ((= pos (1- (match-end 0))) 'bracket)
17257 ((= pos (match-end 0)) 'after)
17258 ((org-pos-in-match-range pos 2) 'year)
17259 ((org-pos-in-match-range pos 3) 'month)
17260 ((org-pos-in-match-range pos 7) 'hour)
17261 ((org-pos-in-match-range pos 8) 'minute)
17262 ((or (org-pos-in-match-range pos 4)
17263 (org-pos-in-match-range pos 5)) 'day)
17264 ((and (> pos (or (match-end 8) (match-end 5)))
17265 (< pos (match-end 0)))
17266 (- pos (or (match-end 8) (match-end 5))))
17267 (t 'day))))
17269 (defun org-toggle-timestamp-type ()
17270 "Toggle the type (<active> or [inactive]) of a time stamp."
17271 (interactive)
17272 (when (org-at-timestamp-p 'lax)
17273 (let ((beg (match-beginning 0)) (end (match-end 0))
17274 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17275 (save-excursion
17276 (goto-char beg)
17277 (while (re-search-forward "[][<>]" end t)
17278 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17279 t t)))
17280 (message "Timestamp is now %sactive"
17281 (if (equal (char-after beg) ?<) "" "in")))))
17283 (defun org-at-clock-log-p ()
17284 "Non-nil if point is on a clock log line."
17285 (and (org-match-line org-clock-line-re)
17286 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17288 (defvar org-clock-history) ; defined in org-clock.el
17289 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17290 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17291 "Change the date in the time stamp at point.
17292 The date will be changed by N times WHAT. WHAT can be `day', `month',
17293 `year', `minute', `second'. If WHAT is not given, the cursor position
17294 in the timestamp determines what will be changed.
17295 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17296 (let ((origin (point))
17297 (timestamp? (org-at-timestamp-p 'lax))
17298 origin-cat
17299 with-hm inactive
17300 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17301 extra rem
17302 ts time time0 fixnext clrgx)
17303 (unless timestamp? (user-error "Not at a timestamp"))
17304 (if (and (not what) (eq timestamp? 'bracket))
17305 (org-toggle-timestamp-type)
17306 ;; Point isn't on brackets. Remember the part of the time-stamp
17307 ;; the point was in. Indeed, size of time-stamps may change,
17308 ;; but point must be kept in the same category nonetheless.
17309 (setq origin-cat timestamp?)
17310 (when (and (not what) (not (eq timestamp? 'day))
17311 org-display-custom-times
17312 (get-text-property (point) 'display)
17313 (not (get-text-property (1- (point)) 'display)))
17314 (setq timestamp? 'day))
17315 (setq timestamp? (or what timestamp?)
17316 inactive (= (char-after (match-beginning 0)) ?\[)
17317 ts (match-string 0))
17318 (replace-match "")
17319 (when (string-match
17320 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17322 (setq extra (match-string 1 ts))
17323 (when suppress-tmp-delay
17324 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17325 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17326 (setq with-hm t))
17327 (setq time0 (org-parse-time-string ts))
17328 (when (and updown
17329 (eq timestamp? 'minute)
17330 (not current-prefix-arg))
17331 ;; This looks like s-up and s-down. Change by one rounding step.
17332 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17333 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17334 (setcar (cdr time0) (+ (nth 1 time0)
17335 (if (> n 0) (- rem) (- dm rem))))))
17336 (setq time
17337 (apply #'encode-time
17338 (or (car time0) 0)
17339 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17340 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17341 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17342 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17343 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17344 (nthcdr 6 time0)))
17345 (when (and (memq timestamp? '(hour minute))
17346 extra
17347 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17348 (setq extra (org-modify-ts-extra
17349 extra
17350 (if (eq timestamp? 'hour) 2 5)
17351 n dm)))
17352 (when (integerp timestamp?)
17353 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17354 (when (eq what 'calendar)
17355 (let ((cal-date (org-get-date-from-calendar)))
17356 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17357 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17358 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17359 (setcar time0 (or (car time0) 0))
17360 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17361 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17362 (setq time (apply 'encode-time time0))))
17363 ;; Insert the new time-stamp, and ensure point stays in the same
17364 ;; category as before (i.e. not after the last position in that
17365 ;; category).
17366 (let ((pos (point)))
17367 ;; Stay before inserted string. `save-excursion' is of no use.
17368 (setq org-last-changed-timestamp
17369 (org-insert-time-stamp time with-hm inactive nil nil extra))
17370 (goto-char pos))
17371 (save-match-data
17372 (looking-at org-ts-regexp3)
17373 (goto-char
17374 (pcase origin-cat
17375 ;; `day' category ends before `hour' if any, or at the end
17376 ;; of the day name.
17377 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17378 (`hour (min (match-end 7) origin))
17379 (`minute (min (1- (match-end 8)) origin))
17380 ((pred integerp) (min (1- (match-end 0)) origin))
17381 ;; Point was right after the time-stamp. However, the
17382 ;; time-stamp length might have changed, so refer to
17383 ;; (match-end 0) instead.
17384 (`after (match-end 0))
17385 ;; `year' and `month' have both fixed size: point couldn't
17386 ;; have moved into another part.
17387 (_ origin))))
17388 ;; Update clock if on a CLOCK line.
17389 (org-clock-update-time-maybe)
17390 ;; Maybe adjust the closest clock in `org-clock-history'
17391 (when org-clock-adjust-closest
17392 (if (not (and (org-at-clock-log-p)
17393 (< 1 (length (delq nil (mapcar 'marker-position
17394 org-clock-history))))))
17395 (message "No clock to adjust")
17396 (cond ((save-excursion ; fix previous clock?
17397 (re-search-backward org-ts-regexp0 nil t)
17398 (looking-back (concat org-clock-string " \\[")
17399 (line-beginning-position)))
17400 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17401 ((save-excursion ; fix next clock?
17402 (re-search-backward org-ts-regexp0 nil t)
17403 (looking-at (concat org-ts-regexp0 "\\] =>")))
17404 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17405 (save-window-excursion
17406 ;; Find closest clock to point, adjust the previous/next one in history
17407 (let* ((p (save-excursion (org-back-to-heading t)))
17408 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17409 (clfixnth
17410 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17411 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17412 (if (not clfixpos)
17413 (message "No clock to adjust")
17414 (save-excursion
17415 (org-goto-marker-or-bmk clfixpos)
17416 (org-show-subtree)
17417 (when (re-search-forward clrgx nil t)
17418 (goto-char (match-beginning 1))
17419 (let (org-clock-adjust-closest)
17420 (org-timestamp-change n timestamp? updown))
17421 (message "Clock adjusted in %s for heading: %s"
17422 (file-name-nondirectory (buffer-file-name))
17423 (org-get-heading t t)))))))))
17424 ;; Try to recenter the calendar window, if any.
17425 (when (and org-calendar-follow-timestamp-change
17426 (get-buffer-window "*Calendar*" t)
17427 (memq timestamp? '(day month year)))
17428 (org-recenter-calendar (time-to-days time))))))
17430 (defun org-modify-ts-extra (s pos n dm)
17431 "Change the different parts of the lead-time and repeat fields in timestamp."
17432 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17433 ng h m new rem)
17434 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17435 (cond
17436 ((or (org-pos-in-match-range pos 2)
17437 (org-pos-in-match-range pos 3))
17438 (setq m (string-to-number (match-string 3 s))
17439 h (string-to-number (match-string 2 s)))
17440 (if (org-pos-in-match-range pos 2)
17441 (setq h (+ h n))
17442 (setq n (* dm (with-no-warnings (signum n))))
17443 (unless (= 0 (setq rem (% m dm)))
17444 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17445 (setq m (+ m n)))
17446 (when (< m 0) (setq m (+ m 60) h (1- h)))
17447 (when (> m 59) (setq m (- m 60) h (1+ h)))
17448 (setq h (mod h 24))
17449 (setq ng 1 new (format "-%02d:%02d" h m)))
17450 ((org-pos-in-match-range pos 6)
17451 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17452 ((org-pos-in-match-range pos 5)
17453 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17455 ((org-pos-in-match-range pos 9)
17456 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17457 ((org-pos-in-match-range pos 8)
17458 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17460 (when ng
17461 (setq s (concat
17462 (substring s 0 (match-beginning ng))
17464 (substring s (match-end ng))))))
17467 (defun org-recenter-calendar (d)
17468 "If the calendar is visible, recenter it to date D."
17469 (let ((cwin (get-buffer-window "*Calendar*" t)))
17470 (when cwin
17471 (let ((calendar-move-hook nil))
17472 (with-selected-window cwin
17473 (calendar-goto-date
17474 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17476 (defun org-goto-calendar (&optional arg)
17477 "Go to the Emacs calendar at the current date.
17478 If there is a time stamp in the current line, go to that date.
17479 A prefix ARG can be used to force the current date."
17480 (interactive "P")
17481 (let ((calendar-move-hook nil)
17482 (calendar-view-holidays-initially-flag nil)
17483 (calendar-view-diary-initially-flag nil)
17484 diff)
17485 (when (or (org-at-timestamp-p 'lax)
17486 (org-match-line (concat ".*" org-ts-regexp)))
17487 (let ((d1 (time-to-days (current-time)))
17488 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17489 (setq diff (- d2 d1))))
17490 (calendar)
17491 (calendar-goto-today)
17492 (when (and diff (not arg)) (calendar-forward-day diff))))
17494 (defun org-get-date-from-calendar ()
17495 "Return a list (month day year) of date at point in calendar."
17496 (with-current-buffer "*Calendar*"
17497 (save-match-data
17498 (calendar-cursor-to-date))))
17500 (defun org-date-from-calendar ()
17501 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17502 If there is already a time stamp at the cursor position, update it."
17503 (interactive)
17504 (if (org-at-timestamp-p 'lax)
17505 (org-timestamp-change 0 'calendar)
17506 (let ((cal-date (org-get-date-from-calendar)))
17507 (org-insert-time-stamp
17508 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17510 (defcustom org-effort-durations
17511 `(("min" . 1)
17512 ("h" . 60)
17513 ("d" . ,(* 60 8))
17514 ("w" . ,(* 60 8 5))
17515 ("m" . ,(* 60 8 5 4))
17516 ("y" . ,(* 60 8 5 40)))
17517 "Conversion factor to minutes for an effort modifier.
17519 Each entry has the form (MODIFIER . MINUTES).
17521 In an effort string, a number followed by MODIFIER is multiplied
17522 by the specified number of MINUTES to obtain an effort in
17523 minutes.
17525 For example, if the value of this variable is ((\"hours\" . 60)), then an
17526 effort string \"2hours\" is equivalent to 120 minutes."
17527 :group 'org-agenda
17528 :version "26.1"
17529 :package-version '(Org . "8.3")
17530 :type '(alist :key-type (string :tag "Modifier")
17531 :value-type (number :tag "Minutes")))
17533 (defcustom org-image-actual-width t
17534 "Should we use the actual width of images when inlining them?
17536 When set to t, always use the image width.
17538 When set to a number, use imagemagick (when available) to set
17539 the image's width to this value.
17541 When set to a number in a list, try to get the width from any
17542 #+ATTR.* keyword if it matches a width specification like
17544 #+ATTR_HTML: :width 300px
17546 and fall back on that number if none is found.
17548 When set to nil, try to get the width from an #+ATTR.* keyword
17549 and fall back on the original width if none is found.
17551 This requires Emacs >= 24.1, build with imagemagick support."
17552 :group 'org-appearance
17553 :version "24.4"
17554 :package-version '(Org . "8.0")
17555 :type '(choice
17556 (const :tag "Use the image width" t)
17557 (integer :tag "Use a number of pixels")
17558 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17559 (const :tag "Use #+ATTR* or don't resize" nil)))
17561 (defcustom org-agenda-inhibit-startup nil
17562 "Inhibit startup when preparing agenda buffers.
17563 When this variable is t, the initialization of the Org agenda
17564 buffers is inhibited: e.g. the visibility state is not set, the
17565 tables are not re-aligned, etc."
17566 :type 'boolean
17567 :version "24.3"
17568 :group 'org-agenda)
17570 (defcustom org-agenda-ignore-properties nil
17571 "Avoid updating text properties when building the agenda.
17572 Properties are used to prepare buffers for effort estimates,
17573 appointments, statistics and subtree-local categories.
17574 If you don't use these in the agenda, you can add them to this
17575 list and agenda building will be a bit faster.
17576 The value is a list, with zero or more of the symbols `effort', `appt',
17577 `stats' or `category'."
17578 :type '(set :greedy t
17579 (const effort)
17580 (const appt)
17581 (const stats)
17582 (const category))
17583 :version "26.1"
17584 :package-version '(Org . "8.3")
17585 :group 'org-agenda)
17587 ;;;; Files
17589 (defun org-save-all-org-buffers ()
17590 "Save all Org buffers without user confirmation."
17591 (interactive)
17592 (message "Saving all Org buffers...")
17593 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17594 (when (featurep 'org-id) (org-id-locations-save))
17595 (message "Saving all Org buffers... done"))
17597 (defun org-revert-all-org-buffers ()
17598 "Revert all Org buffers.
17599 Prompt for confirmation when there are unsaved changes.
17600 Be sure you know what you are doing before letting this function
17601 overwrite your changes.
17603 This function is useful in a setup where one tracks Org files
17604 with a version control system, to revert on one machine after pulling
17605 changes from another. I believe the procedure must be like this:
17607 1. M-x org-save-all-org-buffers
17608 2. Pull changes from the other machine, resolve conflicts
17609 3. M-x org-revert-all-org-buffers"
17610 (interactive)
17611 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17612 (user-error "Abort"))
17613 (save-excursion
17614 (save-window-excursion
17615 (dolist (b (buffer-list))
17616 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17617 (with-current-buffer b buffer-file-name))
17618 (pop-to-buffer-same-window b)
17619 (revert-buffer t 'no-confirm)))
17620 (when (and (featurep 'org-id) org-id-track-globally)
17621 (org-id-locations-load)))))
17623 ;;;; Agenda files
17625 ;;;###autoload
17626 (defun org-switchb (&optional arg)
17627 "Switch between Org buffers.
17629 With `\\[universal-argument]' prefix, restrict available buffers to files.
17631 With `\\[universal-argument] \\[universal-argument]' \
17632 prefix, restrict available buffers to agenda files."
17633 (interactive "P")
17634 (let ((blist (org-buffer-list
17635 (cond ((equal arg '(4)) 'files)
17636 ((equal arg '(16)) 'agenda)))))
17637 (pop-to-buffer-same-window
17638 (completing-read "Org buffer: "
17639 (mapcar #'list (mapcar #'buffer-name blist))
17640 nil t))))
17642 (defun org-buffer-list (&optional predicate exclude-tmp)
17643 "Return a list of Org buffers.
17644 PREDICATE can be `export', `files' or `agenda'.
17646 export restrict the list to Export buffers.
17647 files restrict the list to buffers visiting Org files.
17648 agenda restrict the list to buffers visiting agenda files.
17650 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17651 (let* ((bfn nil)
17652 (agenda-files (and (eq predicate 'agenda)
17653 (mapcar 'file-truename (org-agenda-files t))))
17654 (filter
17655 (cond
17656 ((eq predicate 'files)
17657 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17658 ((eq predicate 'export)
17659 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17660 ((eq predicate 'agenda)
17661 (lambda (b)
17662 (with-current-buffer b
17663 (and (derived-mode-p 'org-mode)
17664 (setq bfn (buffer-file-name b))
17665 (member (file-truename bfn) agenda-files)))))
17666 (t (lambda (b) (with-current-buffer b
17667 (or (derived-mode-p 'org-mode)
17668 (string-match "\\*Org .*Export"
17669 (buffer-name b)))))))))
17670 (delq nil
17671 (mapcar
17672 (lambda(b)
17673 (if (and (funcall filter b)
17674 (or (not exclude-tmp)
17675 (not (string-match "tmp" (buffer-name b)))))
17677 nil))
17678 (buffer-list)))))
17680 (defun org-agenda-files (&optional unrestricted archives)
17681 "Get the list of agenda files.
17682 Optional UNRESTRICTED means return the full list even if a restriction
17683 is currently in place.
17684 When ARCHIVES is t, include all archive files that are really being
17685 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17686 `org-agenda-archives-mode' is t."
17687 (let ((files
17688 (cond
17689 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17690 ((stringp org-agenda-files) (org-read-agenda-file-list))
17691 ((listp org-agenda-files) org-agenda-files)
17692 (t (error "Invalid value of `org-agenda-files'")))))
17693 (setq files (apply 'append
17694 (mapcar (lambda (f)
17695 (if (file-directory-p f)
17696 (directory-files
17697 f t org-agenda-file-regexp)
17698 (list f)))
17699 files)))
17700 (when org-agenda-skip-unavailable-files
17701 (setq files (delq nil
17702 (mapcar (function
17703 (lambda (file)
17704 (and (file-readable-p file) file)))
17705 files))))
17706 (when (or (eq archives t)
17707 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17708 (setq files (org-add-archive-files files)))
17709 files))
17711 (defun org-agenda-file-p (&optional file)
17712 "Return non-nil, if FILE is an agenda file.
17713 If FILE is omitted, use the file associated with the current
17714 buffer."
17715 (let ((fname (or file (buffer-file-name))))
17716 (and fname
17717 (member (file-truename fname)
17718 (mapcar #'file-truename (org-agenda-files t))))))
17720 (defun org-edit-agenda-file-list ()
17721 "Edit the list of agenda files.
17722 Depending on setup, this either uses customize to edit the variable
17723 `org-agenda-files', or it visits the file that is holding the list. In the
17724 latter case, the buffer is set up in a way that saving it automatically kills
17725 the buffer and restores the previous window configuration."
17726 (interactive)
17727 (if (stringp org-agenda-files)
17728 (let ((cw (current-window-configuration)))
17729 (find-file org-agenda-files)
17730 (setq-local org-window-configuration cw)
17731 (add-hook 'after-save-hook
17732 (lambda ()
17733 (set-window-configuration
17734 (prog1 org-window-configuration
17735 (kill-buffer (current-buffer))))
17736 (org-install-agenda-files-menu)
17737 (message "New agenda file list installed"))
17738 nil 'local)
17739 (message "%s" (substitute-command-keys
17740 "Edit list and finish with \\[save-buffer]")))
17741 (customize-variable 'org-agenda-files)))
17743 (defun org-store-new-agenda-file-list (list)
17744 "Set new value for the agenda file list and save it correctly."
17745 (if (stringp org-agenda-files)
17746 (let ((fe (org-read-agenda-file-list t)) b u)
17747 (while (setq b (find-buffer-visiting org-agenda-files))
17748 (kill-buffer b))
17749 (with-temp-file org-agenda-files
17750 (insert
17751 (mapconcat
17752 (lambda (f) ;; Keep un-expanded entries.
17753 (if (setq u (assoc f fe))
17754 (cdr u)
17756 list "\n")
17757 "\n")))
17758 (let ((org-mode-hook nil) (org-inhibit-startup t)
17759 (org-insert-mode-line-in-empty-file nil))
17760 (setq org-agenda-files list)
17761 (customize-save-variable 'org-agenda-files org-agenda-files))))
17763 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17764 "Read the list of agenda files from a file.
17765 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17766 filenames, used by `org-store-new-agenda-file-list' to write back
17767 un-expanded file names."
17768 (when (file-directory-p org-agenda-files)
17769 (error "`org-agenda-files' cannot be a single directory"))
17770 (when (stringp org-agenda-files)
17771 (with-temp-buffer
17772 (insert-file-contents org-agenda-files)
17773 (mapcar
17774 (lambda (f)
17775 (let ((e (expand-file-name (substitute-in-file-name f)
17776 org-directory)))
17777 (if pair-with-expansion
17778 (cons e f)
17779 e)))
17780 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17782 ;;;###autoload
17783 (defun org-cycle-agenda-files ()
17784 "Cycle through the files in `org-agenda-files'.
17785 If the current buffer visits an agenda file, find the next one in the list.
17786 If the current buffer does not, find the first agenda file."
17787 (interactive)
17788 (let* ((fs (or (org-agenda-files t)
17789 (user-error "No agenda files")))
17790 (files (copy-sequence fs))
17791 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17792 file)
17793 (when tcf
17794 (while (and (setq file (pop files))
17795 (not (equal (file-truename file) tcf)))))
17796 (find-file (car (or files fs)))
17797 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17799 (defun org-agenda-file-to-front (&optional to-end)
17800 "Move/add the current file to the top of the agenda file list.
17801 If the file is not present in the list, it is added to the front. If it is
17802 present, it is moved there. With optional argument TO-END, add/move to the
17803 end of the list."
17804 (interactive "P")
17805 (let ((org-agenda-skip-unavailable-files nil)
17806 (file-alist (mapcar (lambda (x)
17807 (cons (file-truename x) x))
17808 (org-agenda-files t)))
17809 (ctf (file-truename
17810 (or buffer-file-name
17811 (user-error "Please save the current buffer to a file"))))
17812 x had)
17813 (setq x (assoc ctf file-alist) had x)
17815 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17816 (if to-end
17817 (setq file-alist (append (delq x file-alist) (list x)))
17818 (setq file-alist (cons x (delq x file-alist))))
17819 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17820 (org-install-agenda-files-menu)
17821 (message "File %s to %s of agenda file list"
17822 (if had "moved" "added") (if to-end "end" "front"))))
17824 (defun org-remove-file (&optional file)
17825 "Remove current file from the list of files in variable `org-agenda-files'.
17826 These are the files which are being checked for agenda entries.
17827 Optional argument FILE means use this file instead of the current."
17828 (interactive)
17829 (let* ((org-agenda-skip-unavailable-files nil)
17830 (file (or file buffer-file-name
17831 (user-error "Current buffer does not visit a file")))
17832 (true-file (file-truename file))
17833 (afile (abbreviate-file-name file))
17834 (files (delq nil (mapcar
17835 (lambda (x)
17836 (unless (equal true-file
17837 (file-truename x))
17839 (org-agenda-files t)))))
17840 (if (not (= (length files) (length (org-agenda-files t))))
17841 (progn
17842 (org-store-new-agenda-file-list files)
17843 (org-install-agenda-files-menu)
17844 (message "Removed from Org Agenda list: %s" afile))
17845 (message "File was not in list: %s (not removed)" afile))))
17847 (defun org-file-menu-entry (file)
17848 (vector file (list 'find-file file) t))
17850 (defun org-check-agenda-file (file)
17851 "Make sure FILE exists. If not, ask user what to do."
17852 (unless (file-exists-p file)
17853 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17854 (abbreviate-file-name file))
17855 (let ((r (downcase (read-char-exclusive))))
17856 (cond
17857 ((equal r ?r)
17858 (org-remove-file file)
17859 (throw 'nextfile t))
17860 (t (user-error "Abort"))))))
17862 (defun org-get-agenda-file-buffer (file)
17863 "Get an agenda buffer visiting FILE.
17864 If the buffer needs to be created, add it to the list of buffers
17865 which might be released later."
17866 (let ((buf (org-find-base-buffer-visiting file)))
17867 (if buf
17868 buf ; just return it
17869 ;; Make a new buffer and remember it
17870 (setq buf (find-file-noselect file))
17871 (when buf (push buf org-agenda-new-buffers))
17872 buf)))
17874 (defun org-release-buffers (blist)
17875 "Release all buffers in list, asking the user for confirmation when needed.
17876 When a buffer is unmodified, it is just killed. When modified, it is saved
17877 \(if the user agrees) and then killed."
17878 (let (file)
17879 (dolist (buf blist)
17880 (setq file (buffer-file-name buf))
17881 (when (and (buffer-modified-p buf)
17882 file
17883 (y-or-n-p (format "Save file %s? " file)))
17884 (with-current-buffer buf (save-buffer)))
17885 (kill-buffer buf))))
17887 (defun org-agenda-prepare-buffers (files)
17888 "Create buffers for all agenda files, protect archived trees and comments."
17889 (interactive)
17890 (let ((pa '(:org-archived t))
17891 (pc '(:org-comment t))
17892 (pall '(:org-archived t :org-comment t))
17893 (inhibit-read-only t)
17894 (org-inhibit-startup org-agenda-inhibit-startup)
17895 (rea (concat ":" org-archive-tag ":"))
17896 re pos)
17897 (setq org-tag-alist-for-agenda nil
17898 org-tag-groups-alist-for-agenda nil)
17899 (save-excursion
17900 (save-restriction
17901 (dolist (file files)
17902 (catch 'nextfile
17903 (if (bufferp file)
17904 (set-buffer file)
17905 (org-check-agenda-file file)
17906 (set-buffer (org-get-agenda-file-buffer file)))
17907 (widen)
17908 (org-set-regexps-and-options 'tags-only)
17909 (setq pos (point))
17910 (or (memq 'category org-agenda-ignore-properties)
17911 (org-refresh-category-properties))
17912 (or (memq 'stats org-agenda-ignore-properties)
17913 (org-refresh-stats-properties))
17914 (or (memq 'effort org-agenda-ignore-properties)
17915 (org-refresh-effort-properties))
17916 (or (memq 'appt org-agenda-ignore-properties)
17917 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17918 (setq org-todo-keywords-for-agenda
17919 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17920 (setq org-done-keywords-for-agenda
17921 (append org-done-keywords-for-agenda org-done-keywords))
17922 (setq org-todo-keyword-alist-for-agenda
17923 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17924 (setq org-tag-alist-for-agenda
17925 (org-uniquify
17926 (append org-tag-alist-for-agenda
17927 org-current-tag-alist)))
17928 ;; Merge current file's tag groups into global
17929 ;; `org-tag-groups-alist-for-agenda'.
17930 (when org-group-tags
17931 (dolist (alist org-tag-groups-alist)
17932 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17933 (if old
17934 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17935 (push alist org-tag-groups-alist-for-agenda)))))
17936 (org-with-silent-modifications
17937 (save-excursion
17938 (remove-text-properties (point-min) (point-max) pall)
17939 (when org-agenda-skip-archived-trees
17940 (goto-char (point-min))
17941 (while (re-search-forward rea nil t)
17942 (when (org-at-heading-p t)
17943 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17944 (goto-char (point-min))
17945 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17946 (while (re-search-forward re nil t)
17947 (when (save-match-data (org-in-commented-heading-p t))
17948 (add-text-properties
17949 (match-beginning 0) (org-end-of-subtree t) pc)))))
17950 (goto-char pos)))))
17951 (setq org-todo-keywords-for-agenda
17952 (org-uniquify org-todo-keywords-for-agenda))
17953 (setq org-todo-keyword-alist-for-agenda
17954 (org-uniquify org-todo-keyword-alist-for-agenda))))
17957 ;;;; CDLaTeX minor mode
17959 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17960 "Keymap for the minor `org-cdlatex-mode'.")
17962 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
17963 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
17964 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
17965 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
17966 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
17968 (defvar org-cdlatex-texmathp-advice-is-done nil
17969 "Flag remembering if we have applied the advice to texmathp already.")
17971 (define-minor-mode org-cdlatex-mode
17972 "Toggle the minor `org-cdlatex-mode'.
17973 This mode supports entering LaTeX environment and math in LaTeX fragments
17974 in Org mode.
17975 \\{org-cdlatex-mode-map}"
17976 nil " OCDL" nil
17977 (when org-cdlatex-mode
17978 (require 'cdlatex)
17979 (run-hooks 'cdlatex-mode-hook)
17980 (cdlatex-compute-tables))
17981 (unless org-cdlatex-texmathp-advice-is-done
17982 (setq org-cdlatex-texmathp-advice-is-done t)
17983 (defadvice texmathp (around org-math-always-on activate)
17984 "Always return t in Org buffers.
17985 This is because we want to insert math symbols without dollars even outside
17986 the LaTeX math segments. If Org mode thinks that point is actually inside
17987 an embedded LaTeX fragment, let `texmathp' do its job.
17988 `\\[org-cdlatex-mode-map]'"
17989 (interactive)
17990 (let (p)
17991 (cond
17992 ((not (derived-mode-p 'org-mode)) ad-do-it)
17993 ((eq this-command 'cdlatex-math-symbol)
17994 (setq ad-return-value t
17995 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17997 (let ((p (org-inside-LaTeX-fragment-p)))
17998 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17999 (setq ad-return-value t
18000 texmathp-why '("Org mode embedded math" . 0))
18001 (when p ad-do-it)))))))))
18003 (defun turn-on-org-cdlatex ()
18004 "Unconditionally turn on `org-cdlatex-mode'."
18005 (org-cdlatex-mode 1))
18007 (defun org-try-cdlatex-tab ()
18008 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18009 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18010 - inside a LaTeX fragment, or
18011 - after the first word in a line, where an abbreviation expansion could
18012 insert a LaTeX environment."
18013 (when org-cdlatex-mode
18014 (cond
18015 ;; Before any word on the line: No expansion possible.
18016 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18017 ;; Just after first word on the line: Expand it. Make sure it
18018 ;; cannot happen on headlines, though.
18019 ((save-excursion
18020 (skip-chars-backward "a-zA-Z0-9*")
18021 (skip-chars-backward " \t")
18022 (and (bolp) (not (org-at-heading-p))))
18023 (cdlatex-tab) t)
18024 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18026 (defun org-cdlatex-underscore-caret (&optional _arg)
18027 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18028 Revert to the normal definition outside of these fragments."
18029 (interactive "P")
18030 (if (org-inside-LaTeX-fragment-p)
18031 (call-interactively 'cdlatex-sub-superscript)
18032 (let (org-cdlatex-mode)
18033 (call-interactively (key-binding (vector last-input-event))))))
18035 (defun org-cdlatex-math-modify (&optional _arg)
18036 "Execute `cdlatex-math-modify' in LaTeX fragments.
18037 Revert to the normal definition outside of these fragments."
18038 (interactive "P")
18039 (if (org-inside-LaTeX-fragment-p)
18040 (call-interactively 'cdlatex-math-modify)
18041 (let (org-cdlatex-mode)
18042 (call-interactively (key-binding (vector last-input-event))))))
18044 (defun org-cdlatex-environment-indent (&optional environment item)
18045 "Execute `cdlatex-environment' and indent the inserted environment.
18047 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18049 The inserted environment is indented to current indentation
18050 unless point is at the beginning of the line, in which the
18051 environment remains unintended."
18052 (interactive)
18053 ;; cdlatex-environment always return nil. Therefore, capture output
18054 ;; first and determine if an environment was selected.
18055 (let* ((beg (point-marker))
18056 (end (copy-marker (point) t))
18057 (inserted (progn
18058 (ignore-errors (cdlatex-environment environment item))
18059 (< beg end)))
18060 ;; Figure out how many lines to move forward after the
18061 ;; environment has been inserted.
18062 (lines (when inserted
18063 (save-excursion
18064 (- (cl-loop while (< beg (point))
18065 with x = 0
18066 do (forward-line -1)
18067 (cl-incf x)
18068 finally return x)
18069 (if (progn (goto-char beg)
18070 (and (progn (skip-chars-forward " \t") (eolp))
18071 (progn (skip-chars-backward " \t") (bolp))))
18072 1 0)))))
18073 (env (org-trim (delete-and-extract-region beg end))))
18074 (when inserted
18075 ;; Get indentation of next line unless at column 0.
18076 (let ((ind (if (bolp) 0
18077 (save-excursion
18078 (org-return-indent)
18079 (prog1 (org-get-indentation)
18080 (when (progn (skip-chars-forward " \t") (eolp))
18081 (delete-region beg (point)))))))
18082 (bol (progn (skip-chars-backward " \t") (bolp))))
18083 ;; Insert a newline before environment unless at column zero
18084 ;; to "escape" the current line. Insert a newline if
18085 ;; something is one the same line as \end{ENVIRONMENT}.
18086 (insert
18087 (concat (unless bol "\n") env
18088 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18089 (unless (zerop ind)
18090 (save-excursion
18091 (goto-char beg)
18092 (while (< (point) end)
18093 (unless (eolp) (indent-line-to ind))
18094 (forward-line))))
18095 (goto-char beg)
18096 (forward-line lines)
18097 (indent-line-to ind)))
18098 (set-marker beg nil)
18099 (set-marker end nil)))
18102 ;;;; LaTeX fragments
18104 (defun org-inside-LaTeX-fragment-p ()
18105 "Test if point is inside a LaTeX fragment.
18106 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18107 sequence appearing also before point.
18108 Even though the matchers for math are configurable, this function assumes
18109 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18110 delimiters are skipped when they have been removed by customization.
18111 The return value is nil, or a cons cell with the delimiter and the
18112 position of this delimiter.
18114 This function does a reasonably good job, but can locally be fooled by
18115 for example currency specifications. For example it will assume being in
18116 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18117 fragments that are properly closed, but during editing, we have to live
18118 with the uncertainty caused by missing closing delimiters. This function
18119 looks only before point, not after."
18120 (catch 'exit
18121 (let ((pos (point))
18122 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18123 (lim (save-excursion (org-backward-paragraph) (point)))
18124 dd-on str (start 0) m re)
18125 (goto-char pos)
18126 (when dodollar
18127 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18128 re (nth 1 (assoc "$" org-latex-regexps)))
18129 (while (string-match re str start)
18130 (cond
18131 ((= (match-end 0) (length str))
18132 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18133 ((= (match-end 0) (- (length str) 5))
18134 (throw 'exit nil))
18135 (t (setq start (match-end 0))))))
18136 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18137 (goto-char pos)
18138 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18139 (and (match-beginning 2) (throw 'exit nil))
18140 ;; count $$
18141 (while (re-search-backward "\\$\\$" lim t)
18142 (setq dd-on (not dd-on)))
18143 (goto-char pos)
18144 (when dd-on (cons "$$" m))))))
18146 (defun org-inside-latex-macro-p ()
18147 "Is point inside a LaTeX macro or its arguments?"
18148 (save-match-data
18149 (org-in-regexp
18150 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18152 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18153 "Build an overlay between BEG and END using IMAGE file.
18154 Argument IMAGETYPE is the extension of the displayed image,
18155 as a string. It defaults to \"png\"."
18156 (let ((ov (make-overlay beg end))
18157 (imagetype (or (intern imagetype) 'png)))
18158 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18159 (overlay-put ov 'evaporate t)
18160 (overlay-put ov
18161 'modification-hooks
18162 (list (lambda (o _flag _beg _end &optional _l)
18163 (delete-overlay o))))
18164 (overlay-put ov
18165 'display
18166 (list 'image :type imagetype :file image :ascent 'center))))
18168 (defun org--list-latex-overlays (&optional beg end)
18169 "List all Org LaTeX overlays in current buffer.
18170 Limit to overlays between BEG and END when those are provided."
18171 (cl-remove-if-not
18172 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18173 (overlays-in (or beg (point-min)) (or end (point-max)))))
18175 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18176 "Remove all overlays with LaTeX fragment images in current buffer.
18177 When optional arguments BEG and END are non-nil, remove all
18178 overlays between them instead. Return a non-nil value when some
18179 overlays were removed, nil otherwise."
18180 (let ((overlays (org--list-latex-overlays beg end)))
18181 (mapc #'delete-overlay overlays)
18182 overlays))
18184 (defun org-toggle-latex-fragment (&optional arg)
18185 "Preview the LaTeX fragment at point, or all locally or globally.
18187 If the cursor is on a LaTeX fragment, create the image and overlay
18188 it over the source code, if there is none. Remove it otherwise.
18189 If there is no fragment at point, display all fragments in the
18190 current section.
18192 With prefix ARG, preview or clear image for all fragments in the
18193 current subtree or in the whole buffer when used before the first
18194 headline. With a prefix ARG `\\[universal-argument] \
18195 \\[universal-argument]' preview or clear images
18196 for all fragments in the buffer."
18197 (interactive "P")
18198 (when (display-graphic-p)
18199 (catch 'exit
18200 (save-excursion
18201 (let (beg end msg)
18202 (cond
18203 ((or (equal arg '(16))
18204 (and (equal arg '(4))
18205 (org-with-limited-levels (org-before-first-heading-p))))
18206 (if (org-remove-latex-fragment-image-overlays)
18207 (progn (message "LaTeX fragments images removed from buffer")
18208 (throw 'exit nil))
18209 (setq msg "Creating images for buffer...")))
18210 ((equal arg '(4))
18211 (org-with-limited-levels (org-back-to-heading t))
18212 (setq beg (point))
18213 (setq end (progn (org-end-of-subtree t) (point)))
18214 (if (org-remove-latex-fragment-image-overlays beg end)
18215 (progn
18216 (message "LaTeX fragment images removed from subtree")
18217 (throw 'exit nil))
18218 (setq msg "Creating images for subtree...")))
18219 ((let ((datum (org-element-context)))
18220 (when (memq (org-element-type datum)
18221 '(latex-environment latex-fragment))
18222 (setq beg (org-element-property :begin datum))
18223 (setq end (org-element-property :end datum))
18224 (if (org-remove-latex-fragment-image-overlays beg end)
18225 (progn (message "LaTeX fragment image removed")
18226 (throw 'exit nil))
18227 (setq msg "Creating image...")))))
18229 (org-with-limited-levels
18230 (setq beg (if (org-at-heading-p) (line-beginning-position)
18231 (outline-previous-heading)
18232 (point)))
18233 (setq end (progn (outline-next-heading) (point)))
18234 (if (org-remove-latex-fragment-image-overlays beg end)
18235 (progn
18236 (message "LaTeX fragment images removed from section")
18237 (throw 'exit nil))
18238 (setq msg "Creating images for section...")))))
18239 (let ((file (buffer-file-name (buffer-base-buffer))))
18240 (org-format-latex
18241 (concat org-preview-latex-image-directory "org-ltximg")
18242 beg end
18243 ;; Emacs cannot overlay images from remote hosts. Create
18244 ;; it in `temporary-file-directory' instead.
18245 (if (or (not file) (file-remote-p file))
18246 temporary-file-directory
18247 default-directory)
18248 'overlays msg 'forbuffer org-preview-latex-default-process))
18249 (message (concat msg "done")))))))
18251 (defun org-format-latex
18252 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18253 "Replace LaTeX fragments with links to an image.
18255 The function takes care of creating the replacement image.
18257 Only consider fragments between BEG and END when those are
18258 provided.
18260 When optional argument OVERLAYS is non-nil, display the image on
18261 top of the fragment instead of replacing it.
18263 PROCESSING-TYPE is the conversion method to use, as a symbol.
18265 Some of the options can be changed using the variable
18266 `org-format-latex-options', which see."
18267 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18268 (unless (eq processing-type 'verbatim)
18269 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18270 (cnt 0)
18271 checkdir-flag)
18272 (goto-char (or beg (point-min)))
18273 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18274 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18275 (overlay-recenter (or end (point-max))))
18276 (while (re-search-forward math-regexp end t)
18277 (unless (and overlays
18278 (eq (get-char-property (point) 'org-overlay-type)
18279 'org-latex-overlay))
18280 (let* ((context (org-element-context))
18281 (type (org-element-type context)))
18282 (when (memq type '(latex-environment latex-fragment))
18283 (let ((block-type (eq type 'latex-environment))
18284 (value (org-element-property :value context))
18285 (beg (org-element-property :begin context))
18286 (end (save-excursion
18287 (goto-char (org-element-property :end context))
18288 (skip-chars-backward " \r\t\n")
18289 (point))))
18290 (cond
18291 ((eq processing-type 'mathjax)
18292 ;; Prepare for MathJax processing.
18293 (if (not (string-match "\\`\\$\\$?" value))
18294 (goto-char end)
18295 (delete-region beg end)
18296 (if (string= (match-string 0 value) "$$")
18297 (insert "\\[" (substring value 2 -2) "\\]")
18298 (insert "\\(" (substring value 1 -1) "\\)"))))
18299 ((assq processing-type org-preview-latex-process-alist)
18300 ;; Process to an image.
18301 (cl-incf cnt)
18302 (goto-char beg)
18303 (let* ((processing-info
18304 (cdr (assq processing-type org-preview-latex-process-alist)))
18305 (face (face-at-point))
18306 ;; Get the colors from the face at point.
18308 (let ((color (plist-get org-format-latex-options
18309 :foreground)))
18310 (if (and forbuffer (eq color 'auto))
18311 (face-attribute face :foreground nil 'default)
18312 color)))
18314 (let ((color (plist-get org-format-latex-options
18315 :background)))
18316 (if (and forbuffer (eq color 'auto))
18317 (face-attribute face :background nil 'default)
18318 color)))
18319 (hash (sha1 (prin1-to-string
18320 (list org-format-latex-header
18321 org-latex-default-packages-alist
18322 org-latex-packages-alist
18323 org-format-latex-options
18324 forbuffer value fg bg))))
18325 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18326 (absprefix (expand-file-name prefix dir))
18327 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18328 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18329 (sep (and block-type "\n\n"))
18330 (link (concat sep "[[file:" linkfile "]]" sep))
18331 (options
18332 (org-combine-plists
18333 org-format-latex-options
18334 `(:foreground ,fg :background ,bg))))
18335 (when msg (message msg cnt))
18336 (unless checkdir-flag ; Ensure the directory exists.
18337 (setq checkdir-flag t)
18338 (let ((todir (file-name-directory absprefix)))
18339 (unless (file-directory-p todir)
18340 (make-directory todir t))))
18341 (unless (file-exists-p movefile)
18342 (org-create-formula-image
18343 value movefile options forbuffer processing-type))
18344 (if overlays
18345 (progn
18346 (dolist (o (overlays-in beg end))
18347 (when (eq (overlay-get o 'org-overlay-type)
18348 'org-latex-overlay)
18349 (delete-overlay o)))
18350 (org--format-latex-make-overlay beg end movefile imagetype)
18351 (goto-char end))
18352 (delete-region beg end)
18353 (insert
18354 (org-add-props link
18355 (list 'org-latex-src
18356 (replace-regexp-in-string "\"" "" value)
18357 'org-latex-src-embed-type
18358 (if block-type 'paragraph 'character)))))))
18359 ((eq processing-type 'mathml)
18360 ;; Process to MathML.
18361 (unless (org-format-latex-mathml-available-p)
18362 (user-error "LaTeX to MathML converter not configured"))
18363 (cl-incf cnt)
18364 (when msg (message msg cnt))
18365 (goto-char beg)
18366 (delete-region beg end)
18367 (insert (org-format-latex-as-mathml
18368 value block-type prefix dir)))
18370 (error "Unknown conversion process %s for LaTeX fragments"
18371 processing-type)))))))))))
18373 (defun org-create-math-formula (latex-frag &optional mathml-file)
18374 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18375 Use `org-latex-to-mathml-convert-command'. If the conversion is
18376 sucessful, return the portion between \"<math...> </math>\"
18377 elements otherwise return nil. When MATHML-FILE is specified,
18378 write the results in to that file. When invoked as an
18379 interactive command, prompt for LATEX-FRAG, with initial value
18380 set to the current active region and echo the results for user
18381 inspection."
18382 (interactive (list (let ((frag (when (org-region-active-p)
18383 (buffer-substring-no-properties
18384 (region-beginning) (region-end)))))
18385 (read-string "LaTeX Fragment: " frag nil frag))))
18386 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18387 (let* ((tmp-in-file
18388 (let ((file (file-relative-name
18389 (make-temp-name (expand-file-name "ltxmathml-in")))))
18390 (write-region latex-frag nil file)
18391 file))
18392 (tmp-out-file (file-relative-name
18393 (make-temp-name (expand-file-name "ltxmathml-out"))))
18394 (cmd (format-spec
18395 org-latex-to-mathml-convert-command
18396 `((?j . ,(and org-latex-to-mathml-jar-file
18397 (shell-quote-argument
18398 (expand-file-name
18399 org-latex-to-mathml-jar-file))))
18400 (?I . ,(shell-quote-argument tmp-in-file))
18401 (?i . ,latex-frag)
18402 (?o . ,(shell-quote-argument tmp-out-file)))))
18403 mathml shell-command-output)
18404 (when (called-interactively-p 'any)
18405 (unless (org-format-latex-mathml-available-p)
18406 (user-error "LaTeX to MathML converter not configured")))
18407 (message "Running %s" cmd)
18408 (setq shell-command-output (shell-command-to-string cmd))
18409 (setq mathml
18410 (when (file-readable-p tmp-out-file)
18411 (with-current-buffer (find-file-noselect tmp-out-file t)
18412 (goto-char (point-min))
18413 (when (re-search-forward
18414 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18415 (regexp-quote
18416 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18417 nil t)
18418 (prog1 (match-string 0) (kill-buffer))))))
18419 (cond
18420 (mathml
18421 (setq mathml
18422 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18423 (when mathml-file
18424 (write-region mathml nil mathml-file))
18425 (when (called-interactively-p 'any)
18426 (message mathml)))
18427 ((message "LaTeX to MathML conversion failed")
18428 (message shell-command-output)))
18429 (delete-file tmp-in-file)
18430 (when (file-exists-p tmp-out-file)
18431 (delete-file tmp-out-file))
18432 mathml))
18434 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18435 prefix &optional dir)
18436 "Use `org-create-math-formula' but check local cache first."
18437 (let* ((absprefix (expand-file-name prefix dir))
18438 (print-length nil) (print-level nil)
18439 (formula-id (concat
18440 "formula-"
18441 (sha1
18442 (prin1-to-string
18443 (list latex-frag
18444 org-latex-to-mathml-convert-command)))))
18445 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18446 (formula-cache-dir (file-name-directory formula-cache)))
18448 (unless (file-directory-p formula-cache-dir)
18449 (make-directory formula-cache-dir t))
18451 (unless (file-exists-p formula-cache)
18452 (org-create-math-formula latex-frag formula-cache))
18454 (if (file-exists-p formula-cache)
18455 ;; Successful conversion. Return the link to MathML file.
18456 (org-add-props
18457 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18458 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18459 'org-latex-src-embed-type (if latex-frag-type
18460 'paragraph 'character)))
18461 ;; Failed conversion. Return the LaTeX fragment verbatim
18462 latex-frag)))
18464 (defun org--get-display-dpi ()
18465 "Get the DPI of the display.
18466 The function assumes that the display has the same pixel width in
18467 the horizontal and vertical directions."
18468 (if (display-graphic-p)
18469 (round (/ (display-pixel-height)
18470 (/ (display-mm-height) 25.4)))
18471 (error "Attempt to calculate the dpi of a non-graphic display")))
18473 (defun org-create-formula-image
18474 (string tofile options buffer &optional processing-type)
18475 "Create an image from LaTeX source using external processes.
18477 The LaTeX STRING is saved to a temporary LaTeX file, then
18478 converted to an image file by process PROCESSING-TYPE defined in
18479 `org-preview-latex-process-alist'. A nil value defaults to
18480 `org-preview-latex-default-process'.
18482 The generated image file is eventually moved to TOFILE.
18484 The OPTIONS argument controls the size, foreground color and
18485 background color of the generated image.
18487 When BUFFER non-nil, this function is used for LaTeX previewing.
18488 Otherwise, it is used to deal with LaTeX snippets showed in
18489 a HTML file."
18490 (let* ((processing-type (or processing-type
18491 org-preview-latex-default-process))
18492 (processing-info
18493 (cdr (assq processing-type org-preview-latex-process-alist)))
18494 (programs (plist-get processing-info :programs))
18495 (error-message (or (plist-get processing-info :message) ""))
18496 (use-xcolor (plist-get processing-info :use-xcolor))
18497 (image-input-type (plist-get processing-info :image-input-type))
18498 (image-output-type (plist-get processing-info :image-output-type))
18499 (post-clean (or (plist-get processing-info :post-clean)
18500 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18501 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18502 (latex-header
18503 (or (plist-get processing-info :latex-header)
18504 (org-latex-make-preamble
18505 (org-export-get-environment (org-export-get-backend 'latex))
18506 org-format-latex-header
18507 'snippet)))
18508 (latex-compiler (plist-get processing-info :latex-compiler))
18509 (image-converter (plist-get processing-info :image-converter))
18510 (tmpdir temporary-file-directory)
18511 (texfilebase (make-temp-name
18512 (expand-file-name "orgtex" tmpdir)))
18513 (texfile (concat texfilebase ".tex"))
18514 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18515 '(1.0 . 1.0)))
18516 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18517 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18518 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18519 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18520 "Black"))
18521 (bg (or (plist-get options (if buffer :background :html-background))
18522 "Transparent"))
18523 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18524 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18525 (dolist (program programs)
18526 (org-check-external-command program error-message))
18527 (if use-xcolor
18528 (progn (if (eq fg 'default)
18529 (setq fg (org-latex-color :foreground))
18530 (setq fg (org-latex-color-format fg)))
18531 (if (eq bg 'default)
18532 (setq bg (org-latex-color :background))
18533 (setq bg (org-latex-color-format
18534 (if (string= bg "Transparent") "white" bg))))
18535 (with-temp-file texfile
18536 (insert latex-header)
18537 (insert "\n\\begin{document}\n"
18538 "\\definecolor{fg}{rgb}{" fg "}\n"
18539 "\\definecolor{bg}{rgb}{" bg "}\n"
18540 "\n\\pagecolor{bg}\n"
18541 "\n{\\color{fg}\n"
18542 string
18543 "\n}\n"
18544 "\n\\end{document}\n")))
18545 (if (eq fg 'default)
18546 (setq fg (org-dvipng-color :foreground))
18547 (unless (string= fg "Transparent")
18548 (setq fg (org-dvipng-color-format fg))))
18549 (if (eq bg 'default)
18550 (setq bg (org-dvipng-color :background))
18551 (unless (string= bg "Transparent")
18552 (setq bg (org-dvipng-color-format bg))))
18553 (with-temp-file texfile
18554 (insert latex-header)
18555 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18557 (let* ((err-msg (format "Please adjust `%s' part of \
18558 `org-preview-latex-process-alist'."
18559 processing-type))
18560 (image-input-file
18561 (org-compile-file
18562 texfile latex-compiler image-input-type err-msg log-buf))
18563 (image-output-file
18564 (org-compile-file
18565 image-input-file image-converter image-output-type err-msg log-buf
18566 `((?F . ,(shell-quote-argument fg))
18567 (?B . ,(shell-quote-argument bg))
18568 (?D . ,(shell-quote-argument (format "%s" dpi)))
18569 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18570 (copy-file image-output-file tofile 'replace)
18571 (dolist (e post-clean)
18572 (when (file-exists-p (concat texfilebase e))
18573 (delete-file (concat texfilebase e))))
18574 image-output-file)))
18576 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18577 "Fill a LaTeX header template TPL.
18578 In the template, the following place holders will be recognized:
18580 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18581 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18582 [PACKAGES] \\usepackage statements for PKG
18583 [NO-PACKAGES] do not include PKG
18584 [EXTRA] the string EXTRA
18585 [NO-EXTRA] do not include EXTRA
18587 For backward compatibility, if both the positive and the negative place
18588 holder is missing, the positive one (without the \"NO-\") will be
18589 assumed to be present at the end of the template.
18590 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18591 EXTRA is a string.
18592 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18593 (let (rpl (end ""))
18594 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18595 (setq rpl (if (or (match-end 1) (not def-pkg))
18596 "" (org-latex-packages-to-string def-pkg snippets-p t))
18597 tpl (replace-match rpl t t tpl))
18598 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18600 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18601 (setq rpl (if (or (match-end 1) (not pkg))
18602 "" (org-latex-packages-to-string pkg snippets-p t))
18603 tpl (replace-match rpl t t tpl))
18604 (when pkg (setq end
18605 (concat end "\n"
18606 (org-latex-packages-to-string pkg snippets-p)))))
18608 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18609 (setq rpl (if (or (match-end 1) (not extra))
18610 "" (concat extra "\n"))
18611 tpl (replace-match rpl t t tpl))
18612 (when (and extra (string-match "\\S-" extra))
18613 (setq end (concat end "\n" extra))))
18615 (if (string-match "\\S-" end)
18616 (concat tpl "\n" end)
18617 tpl)))
18619 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18620 "Turn an alist of packages into a string with the \\usepackage macros."
18621 (setq pkg (mapconcat (lambda(p)
18622 (cond
18623 ((stringp p) p)
18624 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18625 (format "%% Package %s omitted" (cadr p)))
18626 ((equal "" (car p))
18627 (format "\\usepackage{%s}" (cadr p)))
18629 (format "\\usepackage[%s]{%s}"
18630 (car p) (cadr p)))))
18632 "\n"))
18633 (if newline (concat pkg "\n") pkg))
18635 (defun org-dvipng-color (attr)
18636 "Return a RGB color specification for dvipng."
18637 (org-dvipng-color-format (face-attribute 'default attr nil)))
18639 (defun org-dvipng-color-format (color-name)
18640 "Convert COLOR-NAME to a RGB color value for dvipng."
18641 (apply #'format "rgb %s %s %s"
18642 (mapcar 'org-normalize-color
18643 (color-values color-name))))
18645 (defun org-latex-color (attr)
18646 "Return a RGB color for the LaTeX color package."
18647 (org-latex-color-format (face-attribute 'default attr nil)))
18649 (defun org-latex-color-format (color-name)
18650 "Convert COLOR-NAME to a RGB color value."
18651 (apply #'format "%s,%s,%s"
18652 (mapcar 'org-normalize-color
18653 (color-values color-name))))
18655 (defun org-normalize-color (value)
18656 "Return string to be used as color value for an RGB component."
18657 (format "%g" (/ value 65535.0)))
18661 ;; Image display
18663 (defvar-local org-inline-image-overlays nil)
18665 (defun org-toggle-inline-images (&optional include-linked)
18666 "Toggle the display of inline images.
18667 INCLUDE-LINKED is passed to `org-display-inline-images'."
18668 (interactive "P")
18669 (if org-inline-image-overlays
18670 (progn
18671 (org-remove-inline-images)
18672 (when (called-interactively-p 'interactive)
18673 (message "Inline image display turned off")))
18674 (org-display-inline-images include-linked)
18675 (when (called-interactively-p 'interactive)
18676 (message (if org-inline-image-overlays
18677 (format "%d images displayed inline"
18678 (length org-inline-image-overlays))
18679 "No images to display inline")))))
18681 (defun org-redisplay-inline-images ()
18682 "Refresh the display of inline images."
18683 (interactive)
18684 (if (not org-inline-image-overlays)
18685 (org-toggle-inline-images)
18686 (org-toggle-inline-images)
18687 (org-toggle-inline-images)))
18689 (defun org-display-inline-images (&optional include-linked refresh beg end)
18690 "Display inline images.
18692 An inline image is a link which follows either of these
18693 conventions:
18695 1. Its path is a file with an extension matching return value
18696 from `image-file-name-regexp' and it has no contents.
18698 2. Its description consists in a single link of the previous
18699 type.
18701 When optional argument INCLUDE-LINKED is non-nil, also links with
18702 a text description part will be inlined. This can be nice for
18703 a quick look at those images, but it does not reflect what
18704 exported files will look like.
18706 When optional argument REFRESH is non-nil, refresh existing
18707 images between BEG and END. This will create new image displays
18708 only if necessary. BEG and END default to the buffer
18709 boundaries."
18710 (interactive "P")
18711 (when (display-graphic-p)
18712 (unless refresh
18713 (org-remove-inline-images)
18714 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18715 (org-with-wide-buffer
18716 (goto-char (or beg (point-min)))
18717 (let* ((case-fold-search t)
18718 (file-extension-re (image-file-name-regexp))
18719 (link-abbrevs (mapcar #'car
18720 (append org-link-abbrev-alist-local
18721 org-link-abbrev-alist)))
18722 ;; Check absolute, relative file names and explicit
18723 ;; "file:" links. Also check link abbreviations since
18724 ;; some might expand to "file" links.
18725 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18726 (if (not link-abbrevs) ""
18727 (format "\\|\\(?:%s:\\)"
18728 (regexp-opt link-abbrevs))))))
18729 (while (re-search-forward file-types-re end t)
18730 (let ((link (save-match-data (org-element-context))))
18731 ;; Check if we're at an inline image, i.e., an image file
18732 ;; link without a description (unless INCLUDE-LINKED is
18733 ;; non-nil).
18734 (when (and (equal "file" (org-element-property :type link))
18735 (or include-linked
18736 (null (org-element-contents link)))
18737 (string-match-p file-extension-re
18738 (org-element-property :path link)))
18739 (let ((file (expand-file-name
18740 (org-link-unescape
18741 (org-element-property :path link)))))
18742 (when (file-exists-p file)
18743 (let ((width
18744 ;; Apply `org-image-actual-width' specifications.
18745 (cond
18746 ((not (image-type-available-p 'imagemagick)) nil)
18747 ((eq org-image-actual-width t) nil)
18748 ((listp org-image-actual-width)
18750 ;; First try to find a width among
18751 ;; attributes associated to the paragraph
18752 ;; containing link.
18753 (let ((paragraph
18754 (let ((e link))
18755 (while (and (setq e (org-element-property
18756 :parent e))
18757 (not (eq (org-element-type e)
18758 'paragraph))))
18759 e)))
18760 (when paragraph
18761 (save-excursion
18762 (goto-char (org-element-property :begin paragraph))
18763 (when
18764 (re-search-forward
18765 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18766 (org-element-property
18767 :post-affiliated paragraph)
18769 (string-to-number (match-string 1))))))
18770 ;; Otherwise, fall-back to provided number.
18771 (car org-image-actual-width)))
18772 ((numberp org-image-actual-width)
18773 org-image-actual-width)))
18774 (old (get-char-property-and-overlay
18775 (org-element-property :begin link)
18776 'org-image-overlay)))
18777 (if (and (car-safe old) refresh)
18778 (image-refresh (overlay-get (cdr old) 'display))
18779 (let ((image (create-image file
18780 (and width 'imagemagick)
18782 :width width)))
18783 (when image
18784 (let ((ov (make-overlay
18785 (org-element-property :begin link)
18786 (progn
18787 (goto-char
18788 (org-element-property :end link))
18789 (skip-chars-backward " \t")
18790 (point)))))
18791 (overlay-put ov 'display image)
18792 (overlay-put ov 'face 'default)
18793 (overlay-put ov 'org-image-overlay t)
18794 (overlay-put
18795 ov 'modification-hooks
18796 (list 'org-display-inline-remove-overlay))
18797 (push ov org-inline-image-overlays)))))))))))))))
18799 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18800 "Remove inline-display overlay if a corresponding region is modified."
18801 (let ((inhibit-modification-hooks t))
18802 (when (and ov after)
18803 (delete ov org-inline-image-overlays)
18804 (delete-overlay ov))))
18806 (defun org-remove-inline-images ()
18807 "Remove inline display of images."
18808 (interactive)
18809 (mapc #'delete-overlay org-inline-image-overlays)
18810 (setq org-inline-image-overlays nil))
18813 ;;; Key bindings
18815 (defun org-remap (map &rest commands)
18816 "In MAP, remap the functions given in COMMANDS.
18817 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18818 (let (new old)
18819 (while commands
18820 (setq old (pop commands) new (pop commands))
18821 (org-defkey map (vector 'remap old) new))))
18823 ;;;; Outline functions that can be remapped in Org
18824 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18825 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18826 (define-key org-mode-map [remap outline-forward-same-level]
18827 #'org-forward-heading-same-level)
18828 (define-key org-mode-map [remap outline-backward-same-level]
18829 #'org-backward-heading-same-level)
18830 (define-key org-mode-map [remap outline-show-branches]
18831 #'org-kill-note-or-show-branches)
18832 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18833 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18834 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18835 (define-key org-mode-map [remap outline-next-visible-heading]
18836 #'org-next-visible-heading)
18837 (define-key org-mode-map [remap outline-previous-visible-heading]
18838 #'org-previous-visible-heading)
18839 (define-key org-mode-map [remap show-children] #'org-show-children)
18841 ;;;; Make `C-c C-x' a prefix key
18842 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18844 ;;;; TAB key with modifiers
18845 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18846 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18847 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18848 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18849 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18851 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18852 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18853 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18855 ;;;; RET key with modifiers
18856 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18857 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18858 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18859 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18860 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18862 ;;;; Cursor keys with modifiers
18863 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18864 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18865 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18866 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18867 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18868 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18869 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18871 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18872 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18873 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18874 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18875 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18876 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18877 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18878 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18879 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18880 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18882 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18883 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18884 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18885 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18887 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18888 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18889 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18890 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18892 ;;;; Babel keys
18893 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18894 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18895 (define-key org-babel-map key def))
18897 ;;;; Extra keys for TTY access.
18899 ;; We only set them when really needed because otherwise the
18900 ;; menus don't show the simple keys
18902 (when (or org-use-extra-keys (not window-system))
18903 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18904 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18905 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18906 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18907 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18908 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18909 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18910 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18911 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18912 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18913 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18914 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18915 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18916 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18917 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18918 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18919 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18920 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18921 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18922 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18924 ;;;; Narrow map
18925 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18926 (org-defkey narrow-map "b" #'org-narrow-to-block)
18927 (org-defkey narrow-map "e" #'org-narrow-to-element)
18929 ;;;; Remap usual Emacs bindings
18930 (org-remap org-mode-map
18931 'self-insert-command 'org-self-insert-command
18932 'delete-char 'org-delete-char
18933 'delete-backward-char 'org-delete-backward-char
18934 'kill-line 'org-kill-line
18935 'open-line 'org-open-line
18936 'yank 'org-yank
18937 'comment-dwim 'org-comment-dwim
18938 'move-beginning-of-line 'org-beginning-of-line
18939 'move-end-of-line 'org-end-of-line
18940 'forward-paragraph 'org-forward-paragraph
18941 'backward-paragraph 'org-backward-paragraph
18942 'backward-sentence 'org-backward-sentence
18943 'forward-sentence 'org-forward-sentence
18944 'fill-paragraph 'org-fill-paragraph
18945 'delete-indentation 'org-delete-indentation
18946 'transpose-words 'org-transpose-words)
18948 ;;;; All the other keys
18949 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18950 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18951 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18952 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18953 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18954 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18955 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18956 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18957 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18958 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18959 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18960 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18961 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18962 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18963 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18964 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18965 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18966 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18967 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
18968 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
18969 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
18970 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
18971 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
18972 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
18973 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
18974 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
18975 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
18976 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
18977 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
18978 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
18979 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
18980 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
18981 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
18982 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
18983 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
18984 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
18985 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
18986 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
18987 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
18988 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
18989 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
18990 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
18991 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
18992 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
18993 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
18994 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
18995 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
18996 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
18997 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
18998 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
18999 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
19000 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
19001 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19002 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19003 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19004 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19005 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19006 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19007 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19008 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19009 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19010 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19011 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19012 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19013 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19014 (org-defkey org-mode-map (kbd "RET") #'org-return)
19015 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19016 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19017 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19018 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19019 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19020 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19021 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19022 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19023 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19024 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19025 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19026 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19027 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19028 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19029 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19030 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19031 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19032 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19033 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19034 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19035 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19036 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19037 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19039 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19040 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19041 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19043 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19044 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19045 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19046 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19047 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19048 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19049 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19050 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19051 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19052 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19053 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19054 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19055 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19056 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19057 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19058 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19059 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19060 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19061 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19062 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19063 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19064 (org-defkey org-mode-map (kbd "C-c C-x w") #'org-insert-structure-template)
19066 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19067 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19068 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19069 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19070 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19071 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19073 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19075 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19077 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19078 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19080 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19083 ;;; Speed commands
19085 (defconst org-speed-commands-default
19087 ("Outline Navigation")
19088 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19089 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19090 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19091 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19092 ("F" . org-next-block)
19093 ("B" . org-previous-block)
19094 ("u" . (org-speed-move-safe 'outline-up-heading))
19095 ("j" . org-goto)
19096 ("g" . (org-refile t))
19097 ("Outline Visibility")
19098 ("c" . org-cycle)
19099 ("C" . org-shifttab)
19100 (" " . org-display-outline-path)
19101 ("s" . org-narrow-to-subtree)
19102 ("=" . org-columns)
19103 ("Outline Structure Editing")
19104 ("U" . org-metaup)
19105 ("D" . org-metadown)
19106 ("r" . org-metaright)
19107 ("l" . org-metaleft)
19108 ("R" . org-shiftmetaright)
19109 ("L" . org-shiftmetaleft)
19110 ("i" . (progn (forward-char 1) (call-interactively
19111 'org-insert-heading-respect-content)))
19112 ("^" . org-sort)
19113 ("w" . org-refile)
19114 ("a" . org-archive-subtree-default-with-confirmation)
19115 ("@" . org-mark-subtree)
19116 ("#" . org-toggle-comment)
19117 ("Clock Commands")
19118 ("I" . org-clock-in)
19119 ("O" . org-clock-out)
19120 ("Meta Data Editing")
19121 ("t" . org-todo)
19122 ("," . (org-priority))
19123 ("0" . (org-priority ?\ ))
19124 ("1" . (org-priority ?A))
19125 ("2" . (org-priority ?B))
19126 ("3" . (org-priority ?C))
19127 (":" . org-set-tags-command)
19128 ("e" . org-set-effort)
19129 ("E" . org-inc-effort)
19130 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19131 (org-entry-put (point) "APPT_WARNTIME" m)))
19132 ("Agenda Views etc")
19133 ("v" . org-agenda)
19134 ("/" . org-sparse-tree)
19135 ("Misc")
19136 ("o" . org-open-at-point)
19137 ("?" . org-speed-command-help)
19138 ("<" . (org-agenda-set-restriction-lock 'subtree))
19139 (">" . (org-agenda-remove-restriction-lock))
19141 "The default speed commands.")
19143 (defun org-print-speed-command (e)
19144 (if (> (length (car e)) 1)
19145 (progn
19146 (princ "\n")
19147 (princ (car e))
19148 (princ "\n")
19149 (princ (make-string (length (car e)) ?-))
19150 (princ "\n"))
19151 (princ (car e))
19152 (princ " ")
19153 (if (symbolp (cdr e))
19154 (princ (symbol-name (cdr e)))
19155 (prin1 (cdr e)))
19156 (princ "\n")))
19158 (defun org-speed-command-help ()
19159 "Show the available speed commands."
19160 (interactive)
19161 (if (not org-use-speed-commands)
19162 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19163 (with-output-to-temp-buffer "*Help*"
19164 (princ "User-defined Speed commands\n===========================\n")
19165 (mapc #'org-print-speed-command org-speed-commands-user)
19166 (princ "\n")
19167 (princ "Built-in Speed commands\n=======================\n")
19168 (mapc #'org-print-speed-command org-speed-commands-default))
19169 (with-current-buffer "*Help*"
19170 (setq truncate-lines t))))
19172 (defun org-speed-move-safe (cmd)
19173 "Execute CMD, but make sure that the cursor always ends up in a headline.
19174 If not, return to the original position and throw an error."
19175 (interactive)
19176 (let ((pos (point)))
19177 (call-interactively cmd)
19178 (unless (and (bolp) (org-at-heading-p))
19179 (goto-char pos)
19180 (error "Boundary reached while executing %s" cmd))))
19182 (defvar org-self-insert-command-undo-counter 0)
19184 (defvar org-table-auto-blank-field) ; defined in org-table.el
19185 (defvar org-speed-command nil)
19187 (defun org-speed-command-activate (keys)
19188 "Hook for activating single-letter speed commands.
19189 `org-speed-commands-default' specifies a minimal command set.
19190 Use `org-speed-commands-user' for further customization."
19191 (when (or (and (bolp) (looking-at org-outline-regexp))
19192 (and (functionp org-use-speed-commands)
19193 (funcall org-use-speed-commands)))
19194 (cdr (assoc keys (append org-speed-commands-user
19195 org-speed-commands-default)))))
19197 (defun org-babel-speed-command-activate (keys)
19198 "Hook for activating single-letter code block commands."
19199 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19200 (cdr (assoc keys org-babel-key-bindings))))
19202 (defcustom org-speed-command-hook
19203 '(org-speed-command-activate org-babel-speed-command-activate)
19204 "Hook for activating speed commands at strategic locations.
19205 Hook functions are called in sequence until a valid handler is
19206 found.
19208 Each hook takes a single argument, a user-pressed command key
19209 which is also a `self-insert-command' from the global map.
19211 Within the hook, examine the cursor position and the command key
19212 and return nil or a valid handler as appropriate. Handler could
19213 be one of an interactive command, a function, or a form.
19215 Set `org-use-speed-commands' to non-nil value to enable this
19216 hook. The default setting is `org-speed-command-activate'."
19217 :group 'org-structure
19218 :version "24.1"
19219 :type 'hook)
19221 (defun org-self-insert-command (N)
19222 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19223 If the cursor is in a table looking at whitespace, the whitespace is
19224 overwritten, and the table is not marked as requiring realignment."
19225 (interactive "p")
19226 (org-check-before-invisible-edit 'insert)
19227 (cond
19228 ((and org-use-speed-commands
19229 (let ((kv (this-command-keys-vector)))
19230 (setq org-speed-command
19231 (run-hook-with-args-until-success
19232 'org-speed-command-hook
19233 (make-string 1 (aref kv (1- (length kv))))))))
19234 (cond
19235 ((commandp org-speed-command)
19236 (setq this-command org-speed-command)
19237 (call-interactively org-speed-command))
19238 ((functionp org-speed-command)
19239 (funcall org-speed-command))
19240 ((and org-speed-command (listp org-speed-command))
19241 (eval org-speed-command))
19242 (t (let (org-use-speed-commands)
19243 (call-interactively 'org-self-insert-command)))))
19244 ((and
19245 (= N 1)
19246 (not (org-region-active-p))
19247 (org-at-table-p)
19248 (progn
19249 ;; Check if we blank the field, and if that triggers align.
19250 (and (featurep 'org-table)
19251 org-table-auto-blank-field
19252 (memq last-command
19253 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19254 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19255 ;; Got extra space, this field does not determine
19256 ;; column width.
19257 (let (org-table-may-need-update) (org-table-blank-field))
19258 ;; No extra space, this field may determine column
19259 ;; width.
19260 (org-table-blank-field)))
19262 (looking-at "[^|\n]* |"))
19263 ;; There is room for insertion without re-aligning the table.
19264 (self-insert-command N)
19265 (org-table-with-shrunk-field
19266 (save-excursion
19267 (skip-chars-forward "^|")
19268 ;; Do not delete last space, which is
19269 ;; `org-table-separator-space', but the regular space before
19270 ;; it.
19271 (delete-region (- (point) 2) (1- (point))))))
19273 (setq org-table-may-need-update t)
19274 (self-insert-command N)
19275 (org-fix-tags-on-the-fly)
19276 (when org-self-insert-cluster-for-undo
19277 (if (not (eq last-command 'org-self-insert-command))
19278 (setq org-self-insert-command-undo-counter 1)
19279 (if (>= org-self-insert-command-undo-counter 20)
19280 (setq org-self-insert-command-undo-counter 1)
19281 (and (> org-self-insert-command-undo-counter 0)
19282 buffer-undo-list (listp buffer-undo-list)
19283 (not (cadr buffer-undo-list)) ; remove nil entry
19284 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19285 (setq org-self-insert-command-undo-counter
19286 (1+ org-self-insert-command-undo-counter))))))))
19288 (defun org-check-before-invisible-edit (kind)
19289 "Check is editing if kind KIND would be dangerous with invisible text around.
19290 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19291 ;; First, try to get out of here as quickly as possible, to reduce overhead
19292 (when (and org-catch-invisible-edits
19293 (or (not (boundp 'visible-mode)) (not visible-mode))
19294 (or (get-char-property (point) 'invisible)
19295 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19296 ;; OK, we need to take a closer look. Do not consider
19297 ;; invisibility obtained through text properties (e.g., link
19298 ;; fontification), as it cannot be toggled.
19299 (let* ((invisible-at-point
19300 (pcase (get-char-property-and-overlay (point) 'invisible)
19301 (`(,_ . ,(and (pred overlayp) o)) o)))
19302 ;; Assume that point cannot land in the middle of an
19303 ;; overlay, or between two overlays.
19304 (invisible-before-point
19305 (and (not invisible-at-point)
19306 (not (bobp))
19307 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19308 (`(,_ . ,(and (pred overlayp) o)) o))))
19309 (border-and-ok-direction
19311 ;; Check if we are acting predictably before invisible
19312 ;; text.
19313 (and invisible-at-point
19314 (memq kind '(insert delete-backward)))
19315 ;; Check if we are acting predictably after invisible text
19316 ;; This works not well, and I have turned it off. It seems
19317 ;; better to always show and stop after invisible text.
19318 ;; (and (not invisible-at-point) invisible-before-point
19319 ;; (memq kind '(insert delete)))
19321 (when (or invisible-at-point invisible-before-point)
19322 (when (eq org-catch-invisible-edits 'error)
19323 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19324 (if (and org-custom-properties-overlays
19325 (y-or-n-p "Display invisible properties in this buffer? "))
19326 (org-toggle-custom-properties-visibility)
19327 ;; Make the area visible
19328 (save-excursion
19329 (when invisible-before-point
19330 (goto-char
19331 (previous-single-char-property-change (point) 'invisible)))
19332 ;; Remove whatever overlay is currently making yet-to-be
19333 ;; edited text invisible. Also remove nested invisibility
19334 ;; related overlays.
19335 (delete-overlay (or invisible-at-point invisible-before-point))
19336 (let ((origin (if invisible-at-point (point) (1- (point)))))
19337 (while (pcase (get-char-property-and-overlay origin 'invisible)
19338 (`(,_ . ,(and (pred overlayp) o))
19339 (delete-overlay o)
19340 t)))))
19341 (cond
19342 ((eq org-catch-invisible-edits 'show)
19343 ;; That's it, we do the edit after showing
19344 (message
19345 "Unfolding invisible region around point before editing")
19346 (sit-for 1))
19347 ((and (eq org-catch-invisible-edits 'smart)
19348 border-and-ok-direction)
19349 (message "Unfolding invisible region around point before editing"))
19351 ;; Don't do the edit, make the user repeat it in full visibility
19352 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19354 (defun org-fix-tags-on-the-fly ()
19355 "Align tags in headline at point.
19356 Unlike to `org-set-tags', it ignores region and sorting."
19357 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19358 (org-at-heading-p))
19359 (let ((org-ignore-region t)
19360 (org-tags-sort-function nil))
19361 (org-set-tags nil t))))
19363 (defun org-delete-backward-char (N)
19364 "Like `delete-backward-char', insert whitespace at field end in tables.
19365 When deleting backwards, in tables this function will insert whitespace in
19366 front of the next \"|\" separator, to keep the table aligned. The table will
19367 still be marked for re-alignment if the field did fill the entire column,
19368 because, in this case the deletion might narrow the column."
19369 (interactive "p")
19370 (save-match-data
19371 (org-check-before-invisible-edit 'delete-backward)
19372 (if (and (= N 1)
19373 (not overwrite-mode)
19374 (not (org-region-active-p))
19375 (not (eq (char-before) ?|))
19376 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19377 (looking-at-p ".*?|")
19378 (org-at-table-p))
19379 (progn (forward-char -1) (org-delete-char 1))
19380 (backward-delete-char N)
19381 (org-fix-tags-on-the-fly))))
19383 (defun org-delete-char (N)
19384 "Like `delete-char', but insert whitespace at field end in tables.
19385 When deleting characters, in tables this function will insert whitespace in
19386 front of the next \"|\" separator, to keep the table aligned. The table will
19387 still be marked for re-alignment if the field did fill the entire column,
19388 because, in this case the deletion might narrow the column."
19389 (interactive "p")
19390 (save-match-data
19391 (org-check-before-invisible-edit 'delete)
19392 (cond
19393 ((or (/= N 1)
19394 (eq (char-after) ?|)
19395 (save-excursion (skip-chars-backward " \t") (bolp))
19396 (not (org-at-table-p)))
19397 (delete-char N)
19398 (org-fix-tags-on-the-fly))
19399 ((looking-at ".\\(.*?\\)|")
19400 (let* ((update? org-table-may-need-update)
19401 (noalign (looking-at-p ".*? |")))
19402 (delete-char 1)
19403 (org-table-with-shrunk-field
19404 (save-excursion
19405 ;; Last space is `org-table-separator-space', so insert
19406 ;; a regular one before it instead.
19407 (goto-char (- (match-end 0) 2))
19408 (insert " ")))
19409 ;; If there were two spaces at the end, this field does not
19410 ;; determine the width of the column.
19411 (when noalign (setq org-table-may-need-update update?))))
19413 (delete-char N)))))
19415 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19416 (put 'org-self-insert-command 'delete-selection
19417 (lambda ()
19418 (not (run-hook-with-args-until-success
19419 'self-insert-uses-region-functions))))
19420 (put 'orgtbl-self-insert-command 'delete-selection
19421 (lambda ()
19422 (not (run-hook-with-args-until-success
19423 'self-insert-uses-region-functions))))
19424 (put 'org-delete-char 'delete-selection 'supersede)
19425 (put 'org-delete-backward-char 'delete-selection 'supersede)
19426 (put 'org-yank 'delete-selection 'yank)
19428 ;; Make `flyspell-mode' delay after some commands
19429 (put 'org-self-insert-command 'flyspell-delayed t)
19430 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19431 (put 'org-delete-char 'flyspell-delayed t)
19432 (put 'org-delete-backward-char 'flyspell-delayed t)
19434 ;; Make pabbrev-mode expand after Org mode commands
19435 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19436 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19438 (defun org-transpose-words ()
19439 "Transpose words for Org.
19440 This uses the `org-mode-transpose-word-syntax-table' syntax
19441 table, which interprets characters in `org-emphasis-alist' as
19442 word constituents."
19443 (interactive)
19444 (with-syntax-table org-mode-transpose-word-syntax-table
19445 (call-interactively 'transpose-words)))
19447 (defvar org-ctrl-c-ctrl-c-hook nil
19448 "Hook for functions attaching themselves to `C-c C-c'.
19450 This can be used to add additional functionality to the C-c C-c
19451 key which executes context-dependent commands. This hook is run
19452 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19453 run after the last test.
19455 Each function will be called with no arguments. The function
19456 must check if the context is appropriate for it to act. If yes,
19457 it should do its thing and then return a non-nil value. If the
19458 context is wrong, just do nothing and return nil.")
19460 (defvar org-ctrl-c-ctrl-c-final-hook nil
19461 "Hook for functions attaching themselves to `C-c C-c'.
19463 This can be used to add additional functionality to the C-c C-c
19464 key which executes context-dependent commands. This hook is run
19465 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19466 before the first test.
19468 Each function will be called with no arguments. The function
19469 must check if the context is appropriate for it to act. If yes,
19470 it should do its thing and then return a non-nil value. If the
19471 context is wrong, just do nothing and return nil.")
19473 (defvar org-tab-first-hook nil
19474 "Hook for functions to attach themselves to TAB.
19475 See `org-ctrl-c-ctrl-c-hook' for more information.
19476 This hook runs as the first action when TAB is pressed, even before
19477 `org-cycle' messes around with the `outline-regexp' to cater for
19478 inline tasks and plain list item folding.
19479 If any function in this hook returns t, any other actions that
19480 would have been caused by TAB (such as table field motion or visibility
19481 cycling) will not occur.")
19483 (defvar org-tab-after-check-for-table-hook nil
19484 "Hook for functions to attach themselves to TAB.
19485 See `org-ctrl-c-ctrl-c-hook' for more information.
19486 This hook runs after it has been established that the cursor is not in a
19487 table, but before checking if the cursor is in a headline or if global cycling
19488 should be done.
19489 If any function in this hook returns t, not other actions like visibility
19490 cycling will be done.")
19492 (defvar org-tab-after-check-for-cycling-hook nil
19493 "Hook for functions to attach themselves to TAB.
19494 See `org-ctrl-c-ctrl-c-hook' for more information.
19495 This hook runs after it has been established that not table field motion and
19496 not visibility should be done because of current context. This is probably
19497 the place where a package like yasnippets can hook in.")
19499 (defvar org-tab-before-tab-emulation-hook nil
19500 "Hook for functions to attach themselves to TAB.
19501 See `org-ctrl-c-ctrl-c-hook' for more information.
19502 This hook runs after every other options for TAB have been exhausted, but
19503 before indentation and \t insertion takes place.")
19505 (defvar org-metaleft-hook nil
19506 "Hook for functions attaching themselves to `M-left'.
19507 See `org-ctrl-c-ctrl-c-hook' for more information.")
19508 (defvar org-metaright-hook nil
19509 "Hook for functions attaching themselves to `M-right'.
19510 See `org-ctrl-c-ctrl-c-hook' for more information.")
19511 (defvar org-metaup-hook nil
19512 "Hook for functions attaching themselves to `M-up'.
19513 See `org-ctrl-c-ctrl-c-hook' for more information.")
19514 (defvar org-metadown-hook nil
19515 "Hook for functions attaching themselves to `M-down'.
19516 See `org-ctrl-c-ctrl-c-hook' for more information.")
19517 (defvar org-shiftmetaleft-hook nil
19518 "Hook for functions attaching themselves to `M-S-left'.
19519 See `org-ctrl-c-ctrl-c-hook' for more information.")
19520 (defvar org-shiftmetaright-hook nil
19521 "Hook for functions attaching themselves to `M-S-right'.
19522 See `org-ctrl-c-ctrl-c-hook' for more information.")
19523 (defvar org-shiftmetaup-hook nil
19524 "Hook for functions attaching themselves to `M-S-up'.
19525 See `org-ctrl-c-ctrl-c-hook' for more information.")
19526 (defvar org-shiftmetadown-hook nil
19527 "Hook for functions attaching themselves to `M-S-down'.
19528 See `org-ctrl-c-ctrl-c-hook' for more information.")
19529 (defvar org-metareturn-hook nil
19530 "Hook for functions attaching themselves to `M-RET'.
19531 See `org-ctrl-c-ctrl-c-hook' for more information.")
19532 (defvar org-shiftup-hook nil
19533 "Hook for functions attaching themselves to `S-up'.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.")
19535 (defvar org-shiftup-final-hook nil
19536 "Hook for functions attaching themselves to `S-up'.
19537 This one runs after all other options except shift-select have been excluded.
19538 See `org-ctrl-c-ctrl-c-hook' for more information.")
19539 (defvar org-shiftdown-hook nil
19540 "Hook for functions attaching themselves to `S-down'.
19541 See `org-ctrl-c-ctrl-c-hook' for more information.")
19542 (defvar org-shiftdown-final-hook nil
19543 "Hook for functions attaching themselves to `S-down'.
19544 This one runs after all other options except shift-select have been excluded.
19545 See `org-ctrl-c-ctrl-c-hook' for more information.")
19546 (defvar org-shiftleft-hook nil
19547 "Hook for functions attaching themselves to `S-left'.
19548 See `org-ctrl-c-ctrl-c-hook' for more information.")
19549 (defvar org-shiftleft-final-hook nil
19550 "Hook for functions attaching themselves to `S-left'.
19551 This one runs after all other options except shift-select have been excluded.
19552 See `org-ctrl-c-ctrl-c-hook' for more information.")
19553 (defvar org-shiftright-hook nil
19554 "Hook for functions attaching themselves to `S-right'.
19555 See `org-ctrl-c-ctrl-c-hook' for more information.")
19556 (defvar org-shiftright-final-hook nil
19557 "Hook for functions attaching themselves to `S-right'.
19558 This one runs after all other options except shift-select have been excluded.
19559 See `org-ctrl-c-ctrl-c-hook' for more information.")
19561 (defun org-modifier-cursor-error ()
19562 "Throw an error, a modified cursor command was applied in wrong context."
19563 (user-error "This command is active in special context like tables, headlines or items"))
19565 (defun org-shiftselect-error ()
19566 "Throw an error because Shift-Cursor command was applied in wrong context."
19567 (if (and (boundp 'shift-select-mode) shift-select-mode)
19568 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19569 (user-error "This command works only in special context like headlines or timestamps")))
19571 (defun org-call-for-shift-select (cmd)
19572 (let ((this-command-keys-shift-translated t))
19573 (call-interactively cmd)))
19575 (defun org-shifttab (&optional arg)
19576 "Global visibility cycling or move to previous table field.
19577 Call `org-table-previous-field' within a table.
19578 When ARG is nil, cycle globally through visibility states.
19579 When ARG is a numeric prefix, show contents of this level."
19580 (interactive "P")
19581 (cond
19582 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19583 ((integerp arg)
19584 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19585 (message "Content view to level: %d" arg)
19586 (org-content (prefix-numeric-value arg2))
19587 (org-cycle-show-empty-lines t)
19588 (setq org-cycle-global-status 'overview)))
19589 (t (call-interactively 'org-global-cycle))))
19591 (defun org-shiftmetaleft ()
19592 "Promote subtree or delete table column.
19593 Calls `org-promote-subtree', `org-outdent-item-tree', or
19594 `org-table-delete-column', depending on context. See the
19595 individual commands for more information."
19596 (interactive)
19597 (cond
19598 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19599 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19600 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19601 ((if (not (org-region-active-p)) (org-at-item-p)
19602 (save-excursion (goto-char (region-beginning))
19603 (org-at-item-p)))
19604 (call-interactively 'org-outdent-item-tree))
19605 (t (org-modifier-cursor-error))))
19607 (defun org-shiftmetaright ()
19608 "Demote subtree or insert table column.
19609 Calls `org-demote-subtree', `org-indent-item-tree', or
19610 `org-table-insert-column', depending on context. See the
19611 individual commands for more information."
19612 (interactive)
19613 (cond
19614 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19615 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19616 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19617 ((if (not (org-region-active-p)) (org-at-item-p)
19618 (save-excursion (goto-char (region-beginning))
19619 (org-at-item-p)))
19620 (call-interactively 'org-indent-item-tree))
19621 (t (org-modifier-cursor-error))))
19623 (defun org-shiftmetaup (&optional _arg)
19624 "Drag the line at point up.
19625 In a table, kill the current row.
19626 On a clock timestamp, update the value of the timestamp like `S-<up>'
19627 but also adjust the previous clocked item in the clock history.
19628 Everywhere else, drag the line at point up."
19629 (interactive "P")
19630 (cond
19631 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19632 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19633 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19634 (call-interactively 'org-timestamp-up)))
19635 (t (call-interactively 'org-drag-line-backward))))
19637 (defun org-shiftmetadown (&optional _arg)
19638 "Drag the line at point down.
19639 In a table, insert an empty row at the current line.
19640 On a clock timestamp, update the value of the timestamp like `S-<down>'
19641 but also adjust the previous clocked item in the clock history.
19642 Everywhere else, drag the line at point down."
19643 (interactive "P")
19644 (cond
19645 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19646 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19647 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19648 (call-interactively 'org-timestamp-down)))
19649 (t (call-interactively 'org-drag-line-forward))))
19651 (defsubst org-hidden-tree-error ()
19652 (user-error
19653 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19655 (defun org-metaleft (&optional _arg)
19656 "Promote heading, list item at point or move table column left.
19658 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19659 depending on context. With no specific context, calls the Emacs
19660 default `backward-word'. See the individual commands for more
19661 information.
19663 This function runs the hook `org-metaleft-hook' as a first step,
19664 and returns at first non-nil value."
19665 (interactive "P")
19666 (cond
19667 ((run-hook-with-args-until-success 'org-metaleft-hook))
19668 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19669 ((org-with-limited-levels
19670 (or (org-at-heading-p)
19671 (and (org-region-active-p)
19672 (save-excursion
19673 (goto-char (region-beginning))
19674 (org-at-heading-p)))))
19675 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19676 (call-interactively 'org-do-promote))
19677 ;; At an inline task.
19678 ((org-at-heading-p)
19679 (call-interactively 'org-inlinetask-promote))
19680 ((or (org-at-item-p)
19681 (and (org-region-active-p)
19682 (save-excursion
19683 (goto-char (region-beginning))
19684 (org-at-item-p))))
19685 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19686 (call-interactively 'org-outdent-item))
19687 (t (call-interactively 'backward-word))))
19689 (defun org-metaright (&optional _arg)
19690 "Demote heading, list item at point or move table column right.
19692 In front of a drawer or a block keyword, indent it correctly.
19694 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19695 `org-indent-drawer' or `org-indent-block' depending on context.
19696 With no specific context, calls the Emacs default `forward-word'.
19697 See the individual commands for more information.
19699 This function runs the hook `org-metaright-hook' as a first step,
19700 and returns at first non-nil value."
19701 (interactive "P")
19702 (cond
19703 ((run-hook-with-args-until-success 'org-metaright-hook))
19704 ((org-at-table-p) (call-interactively 'org-table-move-column))
19705 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19706 ((org-at-block-p) (call-interactively 'org-indent-block))
19707 ((org-with-limited-levels
19708 (or (org-at-heading-p)
19709 (and (org-region-active-p)
19710 (save-excursion
19711 (goto-char (region-beginning))
19712 (org-at-heading-p)))))
19713 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19714 (call-interactively 'org-do-demote))
19715 ;; At an inline task.
19716 ((org-at-heading-p)
19717 (call-interactively 'org-inlinetask-demote))
19718 ((or (org-at-item-p)
19719 (and (org-region-active-p)
19720 (save-excursion
19721 (goto-char (region-beginning))
19722 (org-at-item-p))))
19723 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19724 (call-interactively 'org-indent-item))
19725 (t (call-interactively 'forward-word))))
19727 (defun org-check-for-hidden (what)
19728 "Check if there are hidden headlines/items in the current visual line.
19729 WHAT can be either `headlines' or `items'. If the current line is
19730 an outline or item heading and it has a folded subtree below it,
19731 this function returns t, nil otherwise."
19732 (let ((re (cond
19733 ((eq what 'headlines) org-outline-regexp-bol)
19734 ((eq what 'items) (org-item-beginning-re))
19735 (t (error "This should not happen"))))
19736 beg end)
19737 (save-excursion
19738 (catch 'exit
19739 (unless (org-region-active-p)
19740 (setq beg (point-at-bol))
19741 (beginning-of-line 2)
19742 (while (and (not (eobp)) ;; this is like `next-line'
19743 (get-char-property (1- (point)) 'invisible))
19744 (beginning-of-line 2))
19745 (setq end (point))
19746 (goto-char beg)
19747 (goto-char (point-at-eol))
19748 (setq end (max end (point)))
19749 (while (re-search-forward re end t)
19750 (when (get-char-property (match-beginning 0) 'invisible)
19751 (throw 'exit t))))
19752 nil))))
19754 (defun org-metaup (&optional _arg)
19755 "Move subtree up or move table row up.
19756 Calls `org-move-subtree-up' or `org-table-move-row' or
19757 `org-move-item-up', depending on context. See the individual commands
19758 for more information."
19759 (interactive "P")
19760 (cond
19761 ((run-hook-with-args-until-success 'org-metaup-hook))
19762 ((org-region-active-p)
19763 (let* ((a (min (region-beginning) (region-end)))
19764 (b (1- (max (region-beginning) (region-end))))
19765 (c (save-excursion (goto-char a)
19766 (move-beginning-of-line 0)))
19767 (d (save-excursion (goto-char a)
19768 (move-end-of-line 0) (point))))
19769 (transpose-regions a b c d)
19770 (goto-char c)))
19771 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19772 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19773 ((org-at-item-p) (call-interactively 'org-move-item-up))
19774 (t (org-drag-element-backward))))
19776 (defun org-metadown (&optional _arg)
19777 "Move subtree down or move table row down.
19778 Calls `org-move-subtree-down' or `org-table-move-row' or
19779 `org-move-item-down', depending on context. See the individual
19780 commands for more information."
19781 (interactive "P")
19782 (cond
19783 ((run-hook-with-args-until-success 'org-metadown-hook))
19784 ((org-region-active-p)
19785 (let* ((a (min (region-beginning) (region-end)))
19786 (b (max (region-beginning) (region-end)))
19787 (c (save-excursion (goto-char b)
19788 (move-beginning-of-line 1)))
19789 (d (save-excursion (goto-char b)
19790 (move-end-of-line 1) (1+ (point)))))
19791 (transpose-regions a b c d)
19792 (goto-char d)))
19793 ((org-at-table-p) (call-interactively 'org-table-move-row))
19794 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19795 ((org-at-item-p) (call-interactively 'org-move-item-down))
19796 (t (org-drag-element-forward))))
19798 (defun org-shiftup (&optional arg)
19799 "Increase item in timestamp or increase priority of current headline.
19800 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19801 depending on context. See the individual commands for more information."
19802 (interactive "P")
19803 (cond
19804 ((run-hook-with-args-until-success 'org-shiftup-hook))
19805 ((and org-support-shift-select (org-region-active-p))
19806 (org-call-for-shift-select 'previous-line))
19807 ((org-at-timestamp-p 'lax)
19808 (call-interactively (if org-edit-timestamp-down-means-later
19809 'org-timestamp-down 'org-timestamp-up)))
19810 ((and (not (eq org-support-shift-select 'always))
19811 org-enable-priority-commands
19812 (org-at-heading-p))
19813 (call-interactively 'org-priority-up))
19814 ((and (not org-support-shift-select) (org-at-item-p))
19815 (call-interactively 'org-previous-item))
19816 ((org-clocktable-try-shift 'up arg))
19817 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19818 (org-support-shift-select
19819 (org-call-for-shift-select 'previous-line))
19820 (t (org-shiftselect-error))))
19822 (defun org-shiftdown (&optional arg)
19823 "Decrease item in timestamp or decrease priority of current headline.
19824 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19825 depending on context. See the individual commands for more information."
19826 (interactive "P")
19827 (cond
19828 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19829 ((and org-support-shift-select (org-region-active-p))
19830 (org-call-for-shift-select 'next-line))
19831 ((org-at-timestamp-p 'lax)
19832 (call-interactively (if org-edit-timestamp-down-means-later
19833 'org-timestamp-up 'org-timestamp-down)))
19834 ((and (not (eq org-support-shift-select 'always))
19835 org-enable-priority-commands
19836 (org-at-heading-p))
19837 (call-interactively 'org-priority-down))
19838 ((and (not org-support-shift-select) (org-at-item-p))
19839 (call-interactively 'org-next-item))
19840 ((org-clocktable-try-shift 'down arg))
19841 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19842 (org-support-shift-select
19843 (org-call-for-shift-select 'next-line))
19844 (t (org-shiftselect-error))))
19846 (defun org-shiftright (&optional arg)
19847 "Cycle the thing at point or in the current line, depending on context.
19848 Depending on context, this does one of the following:
19850 - switch a timestamp at point one day into the future
19851 - on a headline, switch to the next TODO keyword.
19852 - on an item, switch entire list to the next bullet type
19853 - on a property line, switch to the next allowed value
19854 - on a clocktable definition line, move time block into the future"
19855 (interactive "P")
19856 (cond
19857 ((run-hook-with-args-until-success 'org-shiftright-hook))
19858 ((and org-support-shift-select (org-region-active-p))
19859 (org-call-for-shift-select 'forward-char))
19860 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19861 ((and (not (eq org-support-shift-select 'always))
19862 (org-at-heading-p))
19863 (let ((org-inhibit-logging
19864 (not org-treat-S-cursor-todo-selection-as-state-change))
19865 (org-inhibit-blocking
19866 (not org-treat-S-cursor-todo-selection-as-state-change)))
19867 (org-call-with-arg 'org-todo 'right)))
19868 ((or (and org-support-shift-select
19869 (not (eq org-support-shift-select 'always))
19870 (org-at-item-bullet-p))
19871 (and (not org-support-shift-select) (org-at-item-p)))
19872 (org-call-with-arg 'org-cycle-list-bullet nil))
19873 ((and (not (eq org-support-shift-select 'always))
19874 (org-at-property-p))
19875 (call-interactively 'org-property-next-allowed-value))
19876 ((org-clocktable-try-shift 'right arg))
19877 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19878 (org-support-shift-select
19879 (org-call-for-shift-select 'forward-char))
19880 (t (org-shiftselect-error))))
19882 (defun org-shiftleft (&optional arg)
19883 "Cycle the thing at point or in the current line, depending on context.
19884 Depending on context, this does one of the following:
19886 - switch a timestamp at point one day into the past
19887 - on a headline, switch to the previous TODO keyword.
19888 - on an item, switch entire list to the previous bullet type
19889 - on a property line, switch to the previous allowed value
19890 - on a clocktable definition line, move time block into the past"
19891 (interactive "P")
19892 (cond
19893 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19894 ((and org-support-shift-select (org-region-active-p))
19895 (org-call-for-shift-select 'backward-char))
19896 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19897 ((and (not (eq org-support-shift-select 'always))
19898 (org-at-heading-p))
19899 (let ((org-inhibit-logging
19900 (not org-treat-S-cursor-todo-selection-as-state-change))
19901 (org-inhibit-blocking
19902 (not org-treat-S-cursor-todo-selection-as-state-change)))
19903 (org-call-with-arg 'org-todo 'left)))
19904 ((or (and org-support-shift-select
19905 (not (eq org-support-shift-select 'always))
19906 (org-at-item-bullet-p))
19907 (and (not org-support-shift-select) (org-at-item-p)))
19908 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19909 ((and (not (eq org-support-shift-select 'always))
19910 (org-at-property-p))
19911 (call-interactively 'org-property-previous-allowed-value))
19912 ((org-clocktable-try-shift 'left arg))
19913 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19914 (org-support-shift-select
19915 (org-call-for-shift-select 'backward-char))
19916 (t (org-shiftselect-error))))
19918 (defun org-shiftcontrolright ()
19919 "Switch to next TODO set."
19920 (interactive)
19921 (cond
19922 ((and org-support-shift-select (org-region-active-p))
19923 (org-call-for-shift-select 'forward-word))
19924 ((and (not (eq org-support-shift-select 'always))
19925 (org-at-heading-p))
19926 (org-call-with-arg 'org-todo 'nextset))
19927 (org-support-shift-select
19928 (org-call-for-shift-select 'forward-word))
19929 (t (org-shiftselect-error))))
19931 (defun org-shiftcontrolleft ()
19932 "Switch to previous TODO set."
19933 (interactive)
19934 (cond
19935 ((and org-support-shift-select (org-region-active-p))
19936 (org-call-for-shift-select 'backward-word))
19937 ((and (not (eq org-support-shift-select 'always))
19938 (org-at-heading-p))
19939 (org-call-with-arg 'org-todo 'previousset))
19940 (org-support-shift-select
19941 (org-call-for-shift-select 'backward-word))
19942 (t (org-shiftselect-error))))
19944 (defun org-shiftcontrolup (&optional n)
19945 "Change timestamps synchronously up in CLOCK log lines.
19946 Optional argument N tells to change by that many units."
19947 (interactive "P")
19948 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19949 (let (org-support-shift-select)
19950 (org-clock-timestamps-up n))
19951 (user-error "Not at a clock log")))
19953 (defun org-shiftcontroldown (&optional n)
19954 "Change timestamps synchronously down in CLOCK log lines.
19955 Optional argument N tells to change by that many units."
19956 (interactive "P")
19957 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19958 (let (org-support-shift-select)
19959 (org-clock-timestamps-down n))
19960 (user-error "Not at a clock log")))
19962 (defun org-increase-number-at-point (&optional inc)
19963 "Increment the number at point.
19964 With an optional prefix numeric argument INC, increment using
19965 this numeric value."
19966 (interactive "p")
19967 (if (not (number-at-point))
19968 (user-error "Not on a number")
19969 (unless inc (setq inc 1))
19970 (let ((pos (point))
19971 (beg (skip-chars-backward "-+^/*0-9eE."))
19972 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
19973 (setq nap (buffer-substring-no-properties
19974 (+ pos beg) (+ pos beg end)))
19975 (delete-region (+ pos beg) (+ pos beg end))
19976 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
19977 (when (org-at-table-p)
19978 (org-table-align)
19979 (org-table-end-of-field 1))))
19981 (defun org-decrease-number-at-point (&optional inc)
19982 "Decrement the number at point.
19983 With an optional prefix numeric argument INC, decrement using
19984 this numeric value."
19985 (interactive "p")
19986 (org-increase-number-at-point (- (or inc 1))))
19988 (defun org-ctrl-c-ret ()
19989 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19990 (interactive)
19991 (cond
19992 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19993 (t (call-interactively 'org-insert-heading))))
19995 (defun org-find-visible ()
19996 (let ((s (point)))
19997 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19998 (get-char-property s 'invisible)))
20000 (defun org-find-invisible ()
20001 (let ((s (point)))
20002 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20003 (not (get-char-property s 'invisible))))
20006 (defun org-copy-visible (beg end)
20007 "Copy the visible parts of the region."
20008 (interactive "r")
20009 (let ((result ""))
20010 (while (/= beg end)
20011 (when (get-char-property beg 'invisible)
20012 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20013 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20014 (setq result (concat result (buffer-substring beg next)))
20015 (setq beg next)))
20016 (kill-new result)))
20018 (defun org-copy-special ()
20019 "Copy region in table or copy current subtree.
20020 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20021 context. See the individual commands for more information."
20022 (interactive)
20023 (call-interactively
20024 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20026 (defun org-cut-special ()
20027 "Cut region in table or cut current subtree.
20028 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20029 context. See the individual commands for more information."
20030 (interactive)
20031 (call-interactively
20032 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20034 (defun org-paste-special (arg)
20035 "Paste rectangular region into table, or past subtree relative to level.
20036 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20037 See the individual commands for more information."
20038 (interactive "P")
20039 (if (org-at-table-p)
20040 (org-table-paste-rectangle)
20041 (org-paste-subtree arg)))
20043 (defun org-edit-special (&optional arg)
20044 "Call a special editor for the element at point.
20045 When at a table, call the formula editor with `org-table-edit-formulas'.
20046 When in a source code block, call `org-edit-src-code'.
20047 When in a fixed-width region, call `org-edit-fixed-width-region'.
20048 When in an export block, call `org-edit-export-block'.
20049 When in a LaTeX environment, call `org-edit-latex-environment'.
20050 When at an #+INCLUDE keyword, visit the included file.
20051 When at a footnote reference, call `org-edit-footnote-reference'
20052 On a link, call `ffap' to visit the link at point.
20053 Otherwise, return a user error."
20054 (interactive "P")
20055 (let ((element (org-element-at-point)))
20056 (barf-if-buffer-read-only)
20057 (pcase (org-element-type element)
20058 (`src-block
20059 (if (not arg) (org-edit-src-code)
20060 (let* ((info (org-babel-get-src-block-info))
20061 (lang (nth 0 info))
20062 (params (nth 2 info))
20063 (session (cdr (assq :session params))))
20064 (if (not session) (org-edit-src-code)
20065 ;; At a src-block with a session and function called with
20066 ;; an ARG: switch to the buffer related to the inferior
20067 ;; process.
20068 (switch-to-buffer
20069 (funcall (intern (concat "org-babel-prep-session:" lang))
20070 session params))))))
20071 (`keyword
20072 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20073 (org-open-link-from-string
20074 (format "[[%s]]"
20075 (expand-file-name
20076 (let ((value (org-element-property :value element)))
20077 (cond ((org-file-url-p value)
20078 (user-error "The file is specified as a URL, cannot be edited"))
20079 ((not (org-string-nw-p value))
20080 (user-error "No file to edit"))
20081 ((string-match "\\`\"\\(.*?\\)\"" value)
20082 (match-string 1 value))
20083 ((string-match "\\`[^ \t\"]\\S-*" value)
20084 (match-string 0 value))
20085 (t (user-error "No valid file specified")))))))
20086 (user-error "No special environment to edit here")))
20087 (`table
20088 (if (eq (org-element-property :type element) 'table.el)
20089 (org-edit-table.el)
20090 (call-interactively 'org-table-edit-formulas)))
20091 ;; Only Org tables contain `table-row' type elements.
20092 (`table-row (call-interactively 'org-table-edit-formulas))
20093 (`example-block (org-edit-src-code))
20094 (`export-block (org-edit-export-block))
20095 (`fixed-width (org-edit-fixed-width-region))
20096 (`latex-environment (org-edit-latex-environment))
20098 ;; No notable element at point. Though, we may be at a link or
20099 ;; a footnote reference, which are objects. Thus, scan deeper.
20100 (let ((context (org-element-context element)))
20101 (pcase (org-element-type context)
20102 (`footnote-reference (org-edit-footnote-reference))
20103 (`inline-src-block (org-edit-inline-src-code))
20104 (`link (call-interactively #'ffap))
20105 (_ (user-error "No special environment to edit here"))))))))
20107 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20108 (defun org-ctrl-c-ctrl-c (&optional arg)
20109 "Set tags in headline, or update according to changed information at point.
20111 This command does many different things, depending on context:
20113 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20114 this is what we do.
20116 - If the cursor is on a statistics cookie, update it.
20118 - If the cursor is in a headline, prompt for tags and insert them
20119 into the current line, aligned to `org-tags-column'. When called
20120 with prefix arg, realign all tags in the current buffer.
20122 - If the cursor is in one of the special #+KEYWORD lines, this
20123 triggers scanning the buffer for these lines and updating the
20124 information.
20126 - If the cursor is inside a table, realign the table. This command
20127 works even if the automatic table editor has been turned off.
20129 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20130 the entire table.
20132 - If the cursor is at a footnote reference or definition, jump to
20133 the corresponding definition or references, respectively.
20135 - If the cursor is a the beginning of a dynamic block, update it.
20137 - If the current buffer is a capture buffer, close note and file it.
20139 - If the cursor is on a <<<target>>>, update radio targets and
20140 corresponding links in this buffer.
20142 - If the cursor is on a numbered item in a plain list, renumber the
20143 ordered list.
20145 - If the cursor is on a checkbox, toggle it.
20147 - If the cursor is on a code block, evaluate it. The variable
20148 `org-confirm-babel-evaluate' can be used to control prompting
20149 before code block evaluation, by default every code block
20150 evaluation requires confirmation. Code block evaluation can be
20151 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20152 (interactive "P")
20153 (cond
20154 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20155 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20156 (org-remove-occur-highlights)
20157 (message "Temporary highlights/overlays removed from current buffer"))
20158 ((and (local-variable-p 'org-finish-function)
20159 (fboundp org-finish-function))
20160 (funcall org-finish-function))
20161 ((org-babel-hash-at-point))
20162 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20164 (let* ((context
20165 (org-element-lineage
20166 (org-element-context)
20167 ;; Limit to supported contexts.
20168 '(babel-call clock dynamic-block footnote-definition
20169 footnote-reference inline-babel-call inline-src-block
20170 inlinetask item keyword node-property paragraph
20171 plain-list planning property-drawer radio-target
20172 src-block statistics-cookie table table-cell table-row
20173 timestamp)
20175 (type (org-element-type context)))
20176 ;; For convenience: at the first line of a paragraph on the same
20177 ;; line as an item, apply function on that item instead.
20178 (when (eq type 'paragraph)
20179 (let ((parent (org-element-property :parent context)))
20180 (when (and (eq (org-element-type parent) 'item)
20181 (= (line-beginning-position)
20182 (org-element-property :begin parent)))
20183 (setq context parent)
20184 (setq type 'item))))
20185 ;; Act according to type of element or object at point.
20187 ;; Do nothing on a blank line, except if it is contained in
20188 ;; a src block. Hence, we first check if point is in such
20189 ;; a block and then if it is at a blank line.
20190 (pcase type
20191 ((or `inline-src-block `src-block)
20192 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20193 (org-babel-eval-wipe-error-buffer)
20194 (org-babel-execute-src-block
20195 current-prefix-arg (org-babel-get-src-block-info nil context))))
20196 ((guard (org-match-line "[ \t]*$"))
20197 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20198 (user-error
20199 (substitute-command-keys
20200 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20201 ((or `babel-call `inline-babel-call)
20202 (let ((info (org-babel-lob-get-info context)))
20203 (when info (org-babel-execute-src-block nil info))))
20204 (`clock (org-clock-update-time-maybe))
20205 (`dynamic-block
20206 (save-excursion
20207 (goto-char (org-element-property :post-affiliated context))
20208 (org-update-dblock)))
20209 (`footnote-definition
20210 (goto-char (org-element-property :post-affiliated context))
20211 (call-interactively 'org-footnote-action))
20212 (`footnote-reference (call-interactively #'org-footnote-action))
20213 ((or `headline `inlinetask)
20214 (save-excursion (goto-char (org-element-property :begin context))
20215 (call-interactively #'org-set-tags)))
20216 (`item
20217 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20218 ;; unconditionally, whereas `C-u' will toggle its presence.
20219 ;; Without a universal argument, if the item has a checkbox,
20220 ;; toggle it. Otherwise repair the list.
20221 (let* ((box (org-element-property :checkbox context))
20222 (struct (org-element-property :structure context))
20223 (old-struct (copy-tree struct))
20224 (parents (org-list-parents-alist struct))
20225 (prevs (org-list-prevs-alist struct))
20226 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20227 (org-list-set-checkbox
20228 (org-element-property :begin context) struct
20229 (cond ((equal arg '(16)) "[-]")
20230 ((and (not box) (equal arg '(4))) "[ ]")
20231 ((or (not box) (equal arg '(4))) nil)
20232 ((eq box 'on) "[ ]")
20233 (t "[X]")))
20234 ;; Mimic `org-list-write-struct' but with grabbing a return
20235 ;; value from `org-list-struct-fix-box'.
20236 (org-list-struct-fix-ind struct parents 2)
20237 (org-list-struct-fix-item-end struct)
20238 (org-list-struct-fix-bul struct prevs)
20239 (org-list-struct-fix-ind struct parents)
20240 (let ((block-item
20241 (org-list-struct-fix-box struct parents prevs orderedp)))
20242 (if (and box (equal struct old-struct))
20243 (if (equal arg '(16))
20244 (message "Checkboxes already reset")
20245 (user-error "Cannot toggle this checkbox: %s"
20246 (if (eq box 'on)
20247 "all subitems checked"
20248 "unchecked subitems")))
20249 (org-list-struct-apply-struct struct old-struct)
20250 (org-update-checkbox-count-maybe))
20251 (when block-item
20252 (message "Checkboxes were removed due to empty box at line %d"
20253 (org-current-line block-item))))))
20254 (`keyword
20255 (let ((org-inhibit-startup-visibility-stuff t)
20256 (org-startup-align-all-tables nil))
20257 (when (boundp 'org-table-coordinate-overlays)
20258 (mapc #'delete-overlay org-table-coordinate-overlays)
20259 (setq org-table-coordinate-overlays nil))
20260 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20261 (message "Local setup has been refreshed"))
20262 (`plain-list
20263 ;; At a plain list, with a double C-u argument, set
20264 ;; checkboxes of each item to "[-]", whereas a single one
20265 ;; will toggle their presence according to the state of the
20266 ;; first item in the list. Without an argument, repair the
20267 ;; list.
20268 (let* ((begin (org-element-property :contents-begin context))
20269 (struct (org-element-property :structure context))
20270 (old-struct (copy-tree struct))
20271 (first-box (save-excursion
20272 (goto-char begin)
20273 (looking-at org-list-full-item-re)
20274 (match-string-no-properties 3)))
20275 (new-box (cond ((equal arg '(16)) "[-]")
20276 ((equal arg '(4)) (unless first-box "[ ]"))
20277 ((equal first-box "[X]") "[ ]")
20278 (t "[X]"))))
20279 (cond
20280 (arg
20281 (dolist (pos
20282 (org-list-get-all-items
20283 begin struct (org-list-prevs-alist struct)))
20284 (org-list-set-checkbox pos struct new-box)))
20285 ((and first-box (eq (point) begin))
20286 ;; For convenience, when point is at bol on the first
20287 ;; item of the list and no argument is provided, simply
20288 ;; toggle checkbox of that item, if any.
20289 (org-list-set-checkbox begin struct new-box)))
20290 (org-list-write-struct
20291 struct (org-list-parents-alist struct) old-struct)
20292 (org-update-checkbox-count-maybe)))
20293 ((or `property-drawer `node-property)
20294 (call-interactively #'org-property-action))
20295 (`radio-target
20296 (call-interactively #'org-update-radio-target-regexp))
20297 (`statistics-cookie
20298 (call-interactively #'org-update-statistics-cookies))
20299 ((or `table `table-cell `table-row)
20300 ;; At a table, recalculate every field and align it. Also
20301 ;; send the table if necessary. If the table has
20302 ;; a `table.el' type, just give up. At a table row or cell,
20303 ;; maybe recalculate line but always align table.
20304 (if (eq (org-element-property :type context) 'table.el)
20305 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20306 Use `\\[org-edit-special]' to edit table.el tables"))
20307 (if (or (eq type 'table)
20308 ;; Check if point is at a TBLFM line.
20309 (and (eq type 'table-row)
20310 (= (point) (org-element-property :end context))))
20311 (save-excursion
20312 (if (org-at-TBLFM-p)
20313 (progn (require 'org-table)
20314 (org-table-calc-current-TBLFM))
20315 (goto-char (org-element-property :contents-begin context))
20316 (org-call-with-arg 'org-table-recalculate (or arg t))
20317 (orgtbl-send-table 'maybe)))
20318 (org-table-maybe-eval-formula)
20319 (cond (arg (call-interactively #'org-table-recalculate))
20320 ((org-table-maybe-recalculate-line))
20321 (t (org-table-align))))))
20322 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20323 (org-timestamp-change 0 'day))
20324 ((and `nil (guard (org-at-heading-p)))
20325 ;; When point is on an unsupported object type, we can miss
20326 ;; the fact that it also is at a heading. Handle it here.
20327 (call-interactively #'org-set-tags))
20328 ((guard
20329 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20331 (user-error
20332 (substitute-command-keys
20333 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20335 (defun org-mode-restart ()
20336 (interactive)
20337 (let ((indent-status (bound-and-true-p org-indent-mode)))
20338 (funcall major-mode)
20339 (hack-local-variables)
20340 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20341 (org-indent-mode -1))
20342 (org-reset-file-cache))
20343 (message "%s restarted" major-mode))
20345 (defun org-kill-note-or-show-branches ()
20346 "Abort storing current note, or call `outline-show-branches'."
20347 (interactive)
20348 (if (not org-finish-function)
20349 (save-excursion
20350 (save-restriction
20351 (org-narrow-to-subtree)
20352 (org-flag-subtree t)
20353 (call-interactively 'outline-show-branches)
20354 (org-hide-archived-subtrees (point-min) (point-max))))
20355 (let ((org-note-abort t))
20356 (funcall org-finish-function))))
20358 (defun org-delete-indentation (&optional arg)
20359 "Join current line to previous and fix whitespace at join.
20361 If previous line is a headline add to headline title. Otherwise
20362 the function calls `delete-indentation'.
20364 With a non-nil optional argument, join it to the following one."
20365 (interactive "*P")
20366 (if (save-excursion
20367 (beginning-of-line (if arg 1 0))
20368 (let ((case-fold-search nil))
20369 (looking-at org-complex-heading-regexp)))
20370 ;; At headline.
20371 (let ((tags-column (when (match-beginning 5)
20372 (save-excursion (goto-char (match-beginning 5))
20373 (current-column))))
20374 (string (concat " " (progn (when arg (forward-line 1))
20375 (org-trim (delete-and-extract-region
20376 (line-beginning-position)
20377 (line-end-position)))))))
20378 (unless (bobp) (delete-region (point) (1- (point))))
20379 (goto-char (or (match-end 4)
20380 (match-beginning 5)
20381 (match-end 0)))
20382 (skip-chars-backward " \t")
20383 (save-excursion (insert string))
20384 ;; Adjust alignment of tags.
20385 (cond
20386 ((not tags-column)) ;no tags
20387 (org-auto-align-tags (org-set-tags nil t))
20388 (t (org--align-tags-here tags-column)))) ;preserve tags column
20389 (delete-indentation arg)))
20391 (defun org-open-line (n)
20392 "Insert a new row in tables, call `open-line' elsewhere.
20393 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20394 As a special case, when a document starts with a table, allow to
20395 call `open-line' on the very first character."
20396 (interactive "*p")
20397 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20398 (org-table-insert-row)
20399 (open-line n)))
20401 (defun org-return (&optional indent)
20402 "Goto next table row or insert a newline.
20404 Calls `org-table-next-row' or `newline', depending on context.
20406 When optional INDENT argument is non-nil, call
20407 `newline-and-indent' instead of `newline'.
20409 When `org-return-follows-link' is non-nil and point is on
20410 a timestamp or a link, call `org-open-at-point'. However, it
20411 will not happen if point is in a table or on a \"dead\"
20412 object (e.g., within a comment). In these case, you need to use
20413 `org-open-at-point' directly."
20414 (interactive)
20415 (let ((context (if org-return-follows-link (org-element-context)
20416 (org-element-at-point))))
20417 (cond
20418 ;; In a table, call `org-table-next-row'. However, before first
20419 ;; column or after last one, split the table.
20420 ((or (and (eq (org-element-type context) 'table)
20421 (>= (point) (org-element-property :contents-begin context))
20422 (< (point) (org-element-property :contents-end context)))
20423 (org-element-lineage context '(table-row table-cell) t))
20424 (if (or (looking-at-p "[ \t]*$")
20425 (save-excursion (skip-chars-backward " \t") (bolp)))
20426 (insert "\n")
20427 (org-table-justify-field-maybe)
20428 (call-interactively #'org-table-next-row)))
20429 ;; On a link or a timestamp, call `org-open-at-point' if
20430 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20431 ;; locations, e.g., in a comment, as `org-open-at-point'.
20432 ((and org-return-follows-link
20433 (or (org-in-regexp org-ts-regexp-both nil t)
20434 (org-in-regexp org-tsr-regexp-both nil t)
20435 (org-in-regexp org-any-link-re nil t)))
20436 (call-interactively #'org-open-at-point))
20437 ;; Insert newline in heading, but preserve tags.
20438 ((and (not (bolp))
20439 (save-excursion (beginning-of-line)
20440 (let ((case-fold-search nil))
20441 (looking-at org-complex-heading-regexp))))
20442 ;; At headline. Split line. However, if point is on keyword,
20443 ;; priority cookie or tags, do not break any of them: add
20444 ;; a newline after the headline instead.
20445 (let ((tags-column (and (match-beginning 5)
20446 (save-excursion (goto-char (match-beginning 5))
20447 (current-column))))
20448 (string
20449 (when (and (match-end 4) (org-point-in-group (point) 4))
20450 (delete-and-extract-region (point) (match-end 4)))))
20451 ;; Adjust tag alignment.
20452 (cond
20453 ((not (and tags-column string)))
20454 (org-auto-align-tags (org-set-tags nil t))
20455 (t (org--align-tags-here tags-column))) ;preserve tags column
20456 (end-of-line)
20457 (org-show-entry)
20458 (if indent (newline-and-indent) (newline))
20459 (when string (save-excursion (insert (org-trim string))))))
20460 ;; In a list, make sure indenting keeps trailing text within.
20461 ((and indent
20462 (not (eolp))
20463 (org-element-lineage context '(item)))
20464 (let ((trailing-data
20465 (delete-and-extract-region (point) (line-end-position))))
20466 (newline-and-indent)
20467 (save-excursion (insert trailing-data))))
20469 ;; Do not auto-fill when point is in an Org property drawer.
20470 (let ((auto-fill-function (and (not (org-at-property-p))
20471 auto-fill-function)))
20472 (if indent
20473 (newline-and-indent)
20474 (newline)))))))
20476 (defun org-return-indent ()
20477 "Goto next table row or insert a newline and indent.
20478 Calls `org-table-next-row' or `newline-and-indent', depending on
20479 context. See the individual commands for more information."
20480 (interactive)
20481 (org-return t))
20483 (defun org-ctrl-c-tab (&optional _arg)
20484 "Toggle columns width in a table, or show children.
20485 Call `org-table-toggle-column-width' if point is in a table.
20486 Otherwise, call `org-show-children'."
20487 (interactive "p")
20488 (call-interactively
20489 (if (org-at-table-p) #'org-table-toggle-column-width
20490 #'org-show-children)))
20492 (defun org-ctrl-c-star ()
20493 "Compute table, or change heading status of lines.
20494 Calls `org-table-recalculate' or `org-toggle-heading',
20495 depending on context."
20496 (interactive)
20497 (cond
20498 ((org-at-table-p)
20499 (call-interactively 'org-table-recalculate))
20501 ;; Convert all lines in region to list items
20502 (call-interactively 'org-toggle-heading))))
20504 (defun org-ctrl-c-minus ()
20505 "Insert separator line in table or modify bullet status of line.
20506 Also turns a plain line or a region of lines into list items.
20507 Calls `org-table-insert-hline', `org-toggle-item', or
20508 `org-cycle-list-bullet', depending on context."
20509 (interactive)
20510 (cond
20511 ((org-at-table-p)
20512 (call-interactively 'org-table-insert-hline))
20513 ((org-region-active-p)
20514 (call-interactively 'org-toggle-item))
20515 ((org-in-item-p)
20516 (call-interactively 'org-cycle-list-bullet))
20518 (call-interactively 'org-toggle-item))))
20520 (defun org-toggle-heading (&optional nstars)
20521 "Convert headings to normal text, or items or text to headings.
20522 If there is no active region, only convert the current line.
20524 With a `\\[universal-argument]' prefix, convert the whole list at
20525 point into heading.
20527 In a region:
20529 - If the first non blank line is a headline, remove the stars
20530 from all headlines in the region.
20532 - If it is a normal line, turn each and every normal line (i.e.,
20533 not an heading or an item) in the region into headings. If you
20534 want to convert only the first line of this region, use one
20535 universal prefix argument.
20537 - If it is a plain list item, turn all plain list items into headings.
20539 When converting a line into a heading, the number of stars is chosen
20540 such that the lines become children of the current entry. However,
20541 when a numeric prefix argument is given, its value determines the
20542 number of stars to add."
20543 (interactive "P")
20544 (let ((skip-blanks
20545 (function
20546 ;; Return beginning of first non-blank line, starting from
20547 ;; line at POS.
20548 (lambda (pos)
20549 (save-excursion
20550 (goto-char pos)
20551 (while (org-at-comment-p) (forward-line))
20552 (skip-chars-forward " \r\t\n")
20553 (point-at-bol)))))
20554 beg end toggled)
20555 ;; Determine boundaries of changes. If a universal prefix has
20556 ;; been given, put the list in a region. If region ends at a bol,
20557 ;; do not consider the last line to be in the region.
20559 (when (and current-prefix-arg (org-at-item-p))
20560 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20561 (org-mark-element))
20563 (if (org-region-active-p)
20564 (setq beg (funcall skip-blanks (region-beginning))
20565 end (copy-marker (save-excursion
20566 (goto-char (region-end))
20567 (if (bolp) (point) (point-at-eol)))))
20568 (setq beg (funcall skip-blanks (point-at-bol))
20569 end (copy-marker (point-at-eol))))
20570 ;; Ensure inline tasks don't count as headings.
20571 (org-with-limited-levels
20572 (save-excursion
20573 (goto-char beg)
20574 (cond
20575 ;; Case 1. Started at an heading: de-star headings.
20576 ((org-at-heading-p)
20577 (while (< (point) end)
20578 (when (org-at-heading-p t)
20579 (looking-at org-outline-regexp) (replace-match "")
20580 (setq toggled t))
20581 (forward-line)))
20582 ;; Case 2. Started at an item: change items into headlines.
20583 ;; One star will be added by `org-list-to-subtree'.
20584 ((org-at-item-p)
20585 (while (< (point) end)
20586 (when (org-at-item-p)
20587 ;; Pay attention to cases when region ends before list.
20588 (let* ((struct (org-list-struct))
20589 (list-end
20590 (min (org-list-get-bottom-point struct) (1+ end))))
20591 (save-restriction
20592 (narrow-to-region (point) list-end)
20593 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20594 (setq toggled t))
20595 (forward-line)))
20596 ;; Case 3. Started at normal text: make every line an heading,
20597 ;; skipping headlines and items.
20598 (t (let* ((stars
20599 (make-string
20600 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20601 (add-stars
20602 (cond (nstars "") ; stars from prefix only
20603 ((equal stars "") "*") ; before first heading
20604 (org-odd-levels-only "**") ; inside heading, odd
20605 (t "*"))) ; inside heading, oddeven
20606 (rpl (concat stars add-stars " "))
20607 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20608 (while (< (point) (if (equal nstars '(4)) lend end))
20609 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20610 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20611 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20612 (forward-line)))))))
20613 (unless toggled (message "Cannot toggle heading from here"))))
20615 (defun org-meta-return (&optional arg)
20616 "Insert a new heading or wrap a region in a table.
20617 Calls `org-insert-heading', `org-insert-item' or
20618 `org-table-wrap-region', depending on context. When called with
20619 an argument, unconditionally call `org-insert-heading'."
20620 (interactive "P")
20621 (org-check-before-invisible-edit 'insert)
20622 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20623 (call-interactively (cond (arg #'org-insert-heading)
20624 ((org-at-table-p) #'org-table-wrap-region)
20625 ((org-in-item-p) #'org-insert-item)
20626 (t #'org-insert-heading)))))
20628 ;;; Menu entries
20630 (defsubst org-in-subtree-not-table-p ()
20631 "Are we in a subtree and not in a table?"
20632 (and (not (org-before-first-heading-p))
20633 (not (org-at-table-p))))
20635 ;; Define the Org mode menus
20636 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20637 '("Tbl"
20638 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20639 ["Next Field" org-cycle (org-at-table-p)]
20640 ["Previous Field" org-shifttab (org-at-table-p)]
20641 ["Next Row" org-return (org-at-table-p)]
20642 "--"
20643 ["Blank Field" org-table-blank-field (org-at-table-p)]
20644 ["Edit Field" org-table-edit-field (org-at-table-p)]
20645 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20646 "--"
20647 ("Column"
20648 ["Move Column Left" org-metaleft (org-at-table-p)]
20649 ["Move Column Right" org-metaright (org-at-table-p)]
20650 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20651 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20652 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20653 ("Row"
20654 ["Move Row Up" org-metaup (org-at-table-p)]
20655 ["Move Row Down" org-metadown (org-at-table-p)]
20656 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20657 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20658 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20659 "--"
20660 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20661 ("Rectangle"
20662 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20663 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20664 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20665 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20666 "--"
20667 ("Calculate"
20668 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20669 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20670 ["Edit Formulas" org-edit-special (org-at-table-p)]
20671 "--"
20672 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20673 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20674 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20675 "--"
20676 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20677 "--"
20678 ["Sum Column/Rectangle" org-table-sum
20679 (or (org-at-table-p) (org-region-active-p))]
20680 ["Which Column?" org-table-current-column (org-at-table-p)])
20681 ["Debug Formulas"
20682 org-table-toggle-formula-debugger
20683 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20684 ["Show Col/Row Numbers"
20685 org-table-toggle-coordinate-overlays
20686 :style toggle
20687 :selected (bound-and-true-p org-table-overlay-coordinates)]
20688 "--"
20689 ["Create" org-table-create (not (org-at-table-p))]
20690 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20691 ["Import from File" org-table-import (not (org-at-table-p))]
20692 ["Export to File" org-table-export (org-at-table-p)]
20693 "--"
20694 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20695 "--"
20696 ("Plot"
20697 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20698 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20700 (easy-menu-define org-org-menu org-mode-map "Org menu"
20701 '("Org"
20702 ("Show/Hide"
20703 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20704 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20705 ["Sparse Tree..." org-sparse-tree t]
20706 ["Reveal Context" org-reveal t]
20707 ["Show All" org-show-all t]
20708 "--"
20709 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20710 "--"
20711 ["New Heading" org-insert-heading t]
20712 ("Navigate Headings"
20713 ["Up" outline-up-heading t]
20714 ["Next" outline-next-visible-heading t]
20715 ["Previous" outline-previous-visible-heading t]
20716 ["Next Same Level" outline-forward-same-level t]
20717 ["Previous Same Level" outline-backward-same-level t]
20718 "--"
20719 ["Jump" org-goto t])
20720 ("Edit Structure"
20721 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20722 "--"
20723 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20724 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20725 "--"
20726 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20727 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20728 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20729 "--"
20730 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20731 "--"
20732 ["Copy visible text" org-copy-visible t]
20733 "--"
20734 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20735 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20736 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20737 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20738 "--"
20739 ["Sort Region/Children" org-sort t]
20740 "--"
20741 ["Convert to odd levels" org-convert-to-odd-levels t]
20742 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20743 ("Editing"
20744 ["Emphasis..." org-emphasize t]
20745 ["Edit Source Example" org-edit-special t]
20746 "--"
20747 ["Footnote new/jump" org-footnote-action t]
20748 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20749 ("Archive"
20750 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20751 "--"
20752 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20753 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20754 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20756 "--"
20757 ("Hyperlinks"
20758 ["Store Link (Global)" org-store-link t]
20759 ["Find existing link to here" org-occur-link-in-agenda-files t]
20760 ["Insert Link" org-insert-link t]
20761 ["Follow Link" org-open-at-point t]
20762 "--"
20763 ["Next link" org-next-link t]
20764 ["Previous link" org-previous-link t]
20765 "--"
20766 ["Descriptive Links"
20767 org-toggle-link-display
20768 :style radio
20769 :selected org-descriptive-links
20771 ["Literal Links"
20772 org-toggle-link-display
20773 :style radio
20774 :selected (not org-descriptive-links)])
20775 "--"
20776 ("TODO Lists"
20777 ["TODO/DONE/-" org-todo t]
20778 ("Select keyword"
20779 ["Next keyword" org-shiftright (org-at-heading-p)]
20780 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20781 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20782 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20783 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20784 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20785 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20786 "--"
20787 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20788 :selected org-enforce-todo-dependencies :style toggle :active t]
20789 "Settings for tree at point"
20790 ["Do Children sequentially" org-toggle-ordered-property :style radio
20791 :selected (org-entry-get nil "ORDERED")
20792 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20793 ["Do Children parallel" org-toggle-ordered-property :style radio
20794 :selected (not (org-entry-get nil "ORDERED"))
20795 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20796 "--"
20797 ["Set Priority" org-priority t]
20798 ["Priority Up" org-shiftup t]
20799 ["Priority Down" org-shiftdown t]
20800 "--"
20801 ["Get news from all feeds" org-feed-update-all t]
20802 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20803 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20804 ("TAGS and Properties"
20805 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20806 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20807 "--"
20808 ["Set property" org-set-property (not (org-before-first-heading-p))]
20809 ["Column view of properties" org-columns t]
20810 ["Insert Column View DBlock" org-columns-insert-dblock t])
20811 ("Dates and Scheduling"
20812 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20813 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20814 ("Change Date"
20815 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20816 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20817 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20818 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20819 ["Compute Time Range" org-evaluate-time-range t]
20820 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20821 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20822 "--"
20823 ["Custom time format" org-toggle-time-stamp-overlays
20824 :style radio :selected org-display-custom-times]
20825 "--"
20826 ["Goto Calendar" org-goto-calendar t]
20827 ["Date from Calendar" org-date-from-calendar t]
20828 "--"
20829 ["Start/Restart Timer" org-timer-start t]
20830 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20831 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20832 ["Insert Timer String" org-timer t]
20833 ["Insert Timer Item" org-timer-item t])
20834 ("Logging work"
20835 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20836 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20837 ["Clock out" org-clock-out t]
20838 ["Clock cancel" org-clock-cancel t]
20839 "--"
20840 ["Mark as default task" org-clock-mark-default-task t]
20841 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20842 ["Goto running clock" org-clock-goto t]
20843 "--"
20844 ["Display times" org-clock-display t]
20845 ["Create clock table" org-clock-report t]
20846 "--"
20847 ["Record DONE time"
20848 (progn (setq org-log-done (not org-log-done))
20849 (message "Switching to %s will %s record a timestamp"
20850 (car org-done-keywords)
20851 (if org-log-done "automatically" "not")))
20852 :style toggle :selected org-log-done])
20853 "--"
20854 ["Agenda Command..." org-agenda t]
20855 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20856 ("File List for Agenda")
20857 ("Special views current file"
20858 ["TODO Tree" org-show-todo-tree t]
20859 ["Check Deadlines" org-check-deadlines t]
20860 ["Tags/Property tree" org-match-sparse-tree t])
20861 "--"
20862 ["Export/Publish..." org-export-dispatch t]
20863 ("LaTeX"
20864 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20865 :style toggle :selected org-cdlatex-mode]
20866 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20867 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20868 ["Modify math symbol" org-cdlatex-math-modify
20869 (org-inside-LaTeX-fragment-p)]
20870 ["Insert citation" org-reftex-citation t])
20871 "--"
20872 ("MobileOrg"
20873 ["Push Files and Views" org-mobile-push t]
20874 ["Get Captured and Flagged" org-mobile-pull t]
20875 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20876 "--"
20877 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20878 "--"
20879 ("Documentation"
20880 ["Show Version" org-version t]
20881 ["Info Documentation" org-info t])
20882 ("Customize"
20883 ["Browse Org Group" org-customize t]
20884 "--"
20885 ["Expand This Menu" org-create-customize-menu
20886 (fboundp 'customize-menu-create)])
20887 ["Send bug report" org-submit-bug-report t]
20888 "--"
20889 ("Refresh/Reload"
20890 ["Refresh setup current buffer" org-mode-restart t]
20891 ["Reload Org (after update)" org-reload t]
20892 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20895 (defun org-info (&optional node)
20896 "Read documentation for Org in the info system.
20897 With optional NODE, go directly to that node."
20898 (interactive)
20899 (info (format "(org)%s" (or node ""))))
20901 ;;;###autoload
20902 (defun org-submit-bug-report ()
20903 "Submit a bug report on Org via mail.
20905 Don't hesitate to report any problems or inaccurate documentation.
20907 If you don't have setup sending mail from (X)Emacs, please copy the
20908 output buffer into your mail program, as it gives us important
20909 information about your Org version and configuration."
20910 (interactive)
20911 (require 'reporter)
20912 (defvar reporter-prompt-for-summary-p)
20913 (org-load-modules-maybe)
20914 (org-require-autoloaded-modules)
20915 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20916 (reporter-submit-bug-report
20917 "emacs-orgmode@gnu.org"
20918 (org-version nil 'full)
20919 (let (list)
20920 (save-window-excursion
20921 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20922 (delete-other-windows)
20923 (erase-buffer)
20924 (insert "You are about to submit a bug report to the Org mailing list.
20926 We would like to add your full Org and Outline configuration to the
20927 bug report. This greatly simplifies the work of the maintainer and
20928 other experts on the mailing list.
20930 HOWEVER, some variables you have customized may contain private
20931 information. The names of customers, colleagues, or friends, might
20932 appear in the form of file names, tags, todo states, or search strings.
20933 If you answer yes to the prompt, you might want to check and remove
20934 such private information before sending the email.")
20935 (add-text-properties (point-min) (point-max) '(face org-warning))
20936 (when (yes-or-no-p "Include your Org configuration ")
20937 (mapatoms
20938 (lambda (v)
20939 (and (boundp v)
20940 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20941 (or (and (symbol-value v)
20942 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20943 (and
20944 (get v 'custom-type) (get v 'standard-value)
20945 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20946 (push v list)))))
20947 (kill-buffer (get-buffer "*Warn about privacy*"))
20948 list))
20949 nil nil
20950 "Remember to cover the basics, that is, what you expected to happen and
20951 what in fact did happen. You don't know how to make a good report? See
20953 https://orgmode.org/manual/Feedback.html#Feedback
20955 Your bug report will be posted to the Org mailing list.
20956 ------------------------------------------------------------------------")
20957 (save-excursion
20958 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20959 (replace-match "\\1Bug: \\3 [\\2]")))))
20962 (defun org-install-agenda-files-menu ()
20963 (let ((bl (buffer-list)))
20964 (save-excursion
20965 (while bl
20966 (set-buffer (pop bl))
20967 (when (derived-mode-p 'org-mode) (setq bl nil)))
20968 (when (derived-mode-p 'org-mode)
20969 (easy-menu-change
20970 '("Org") "File List for Agenda"
20971 (append
20972 (list
20973 ["Edit File List" (org-edit-agenda-file-list) t]
20974 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20975 ["Remove Current File from List" org-remove-file t]
20976 ["Cycle through agenda files" org-cycle-agenda-files t]
20977 ["Occur in all agenda files" org-occur-in-agenda-files t]
20978 "--")
20979 (mapcar 'org-file-menu-entry
20980 ;; Prevent initialization from failing.
20981 (ignore-errors (org-agenda-files t)))))))))
20983 ;;;; Documentation
20985 (defun org-require-autoloaded-modules ()
20986 (interactive)
20987 (mapc #'require
20988 '(org-agenda org-archive org-attach org-clock org-colview org-id
20989 org-table org-timer)))
20991 ;;;###autoload
20992 (defun org-reload (&optional uncompiled)
20993 "Reload all Org Lisp files.
20994 With prefix arg UNCOMPILED, load the uncompiled versions."
20995 (interactive "P")
20996 (require 'loadhist)
20997 (let* ((org-dir (org-find-library-dir "org"))
20998 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20999 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21000 (remove-re (format "\\`%s\\'"
21001 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21002 (feats (delete-dups
21003 (mapcar 'file-name-sans-extension
21004 (mapcar 'file-name-nondirectory
21005 (delq nil
21006 (mapcar 'feature-file
21007 features))))))
21008 (lfeat (append
21009 (sort
21010 (setq feats
21011 (delq nil (mapcar
21012 (lambda (f)
21013 (if (and (string-match feature-re f)
21014 (not (string-match remove-re f)))
21015 f nil))
21016 feats)))
21017 'string-lessp)
21018 (list "org-version" "org")))
21019 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21020 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21021 load-uncore load-misses)
21022 (setq load-misses
21023 (delq 't
21024 (mapcar (lambda (f)
21025 (or (org-load-noerror-mustsuffix (concat org-dir f))
21026 (and (string= org-dir contrib-dir)
21027 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21028 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21029 (add-to-list 'load-uncore f 'append)
21032 lfeat)))
21033 (when load-uncore
21034 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21035 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21036 (if load-misses
21037 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21038 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21039 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21041 ;;;###autoload
21042 (defun org-customize ()
21043 "Call the customize function with org as argument."
21044 (interactive)
21045 (org-load-modules-maybe)
21046 (org-require-autoloaded-modules)
21047 (customize-browse 'org))
21049 (defun org-create-customize-menu ()
21050 "Create a full customization menu for Org mode, insert it into the menu."
21051 (interactive)
21052 (org-load-modules-maybe)
21053 (org-require-autoloaded-modules)
21054 (if (fboundp 'customize-menu-create)
21055 (progn
21056 (easy-menu-change
21057 '("Org") "Customize"
21058 `(["Browse Org group" org-customize t]
21059 "--"
21060 ,(customize-menu-create 'org)
21061 ["Set" Custom-set t]
21062 ["Save" Custom-save t]
21063 ["Reset to Current" Custom-reset-current t]
21064 ["Reset to Saved" Custom-reset-saved t]
21065 ["Reset to Standard Settings" Custom-reset-standard t]))
21066 (message "\"Org\"-menu now contains full customization menu"))
21067 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21069 ;;;; Miscellaneous stuff
21071 ;;; Generally useful functions
21073 (defun org-link-display-format (s)
21074 "Replace links in string S with their description.
21075 If there is no description, use the link target."
21076 (save-match-data
21077 (replace-regexp-in-string
21078 org-bracket-link-analytic-regexp
21079 (lambda (m)
21080 (if (match-end 5) (match-string 5 m)
21081 (concat (match-string 1 m) (match-string 3 m))))
21082 s nil t)))
21084 (defun org-toggle-link-display ()
21085 "Toggle the literal or descriptive display of links."
21086 (interactive)
21087 (if org-descriptive-links
21088 (progn (org-remove-from-invisibility-spec '(org-link))
21089 (org-restart-font-lock)
21090 (setq org-descriptive-links nil))
21091 (progn (add-to-invisibility-spec '(org-link))
21092 (org-restart-font-lock)
21093 (setq org-descriptive-links t))))
21095 (defun org-in-clocktable-p ()
21096 "Check if the cursor is in a clocktable."
21097 (let ((pos (point)) start)
21098 (save-excursion
21099 (end-of-line 1)
21100 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21101 (setq start (match-beginning 0))
21102 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21103 (>= (match-end 0) pos)
21104 start))))
21106 (defun org-in-verbatim-emphasis ()
21107 (save-match-data
21108 (and (org-in-regexp org-verbatim-re 2)
21109 (>= (point) (match-beginning 3))
21110 (<= (point) (match-end 4)))))
21112 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21113 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21114 (if (and marker (marker-buffer marker)
21115 (buffer-live-p (marker-buffer marker)))
21116 (progn
21117 (pop-to-buffer-same-window (marker-buffer marker))
21118 (when (or (> marker (point-max)) (< marker (point-min)))
21119 (widen))
21120 (goto-char marker)
21121 (org-show-context 'org-goto))
21122 (if bookmark
21123 (bookmark-jump bookmark)
21124 (error "Cannot find location"))))
21126 (defun org-quote-csv-field (s)
21127 "Quote field for inclusion in CSV material."
21128 (if (string-match "[\",]" s)
21129 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21132 (defun org-force-self-insert (N)
21133 "Needed to enforce self-insert under remapping."
21134 (interactive "p")
21135 (self-insert-command N))
21137 (defun org-fill-template (template alist)
21138 "Find each %key of ALIST in TEMPLATE and replace it."
21139 (let ((case-fold-search nil))
21140 (dolist (entry (sort (copy-sequence alist)
21141 (lambda (a b) (< (length (car a)) (length (car b))))))
21142 (setq template
21143 (replace-regexp-in-string
21144 (concat "%" (regexp-quote (car entry)))
21145 (or (cdr entry) "") template t t)))
21146 template))
21148 (defun org-quote-vert (s)
21149 "Replace \"|\" with \"\\vert\"."
21150 (while (string-match "|" s)
21151 (setq s (replace-match "\\vert" t t s)))
21154 (defun org-uuidgen-p (s)
21155 "Is S an ID created by UUIDGEN?"
21156 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21158 (defun org-in-src-block-p (&optional inside)
21159 "Whether point is in a code source block.
21160 When INSIDE is non-nil, don't consider we are within a src block
21161 when point is at #+BEGIN_SRC or #+END_SRC."
21162 (let ((case-fold-search t))
21163 (or (and (eq (get-char-property (point) 'src-block) t))
21164 (and (not inside)
21165 (save-match-data
21166 (save-excursion
21167 (beginning-of-line)
21168 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21170 (defun org-context ()
21171 "Return a list of contexts of the current cursor position.
21172 If several contexts apply, all are returned.
21173 Each context entry is a list with a symbol naming the context, and
21174 two positions indicating start and end of the context. Possible
21175 contexts are:
21177 :headline anywhere in a headline
21178 :headline-stars on the leading stars in a headline
21179 :todo-keyword on a TODO keyword (including DONE) in a headline
21180 :tags on the TAGS in a headline
21181 :priority on the priority cookie in a headline
21182 :item on the first line of a plain list item
21183 :item-bullet on the bullet/number of a plain list item
21184 :checkbox on the checkbox in a plain list item
21185 :table in an Org table
21186 :table-special on a special filed in a table
21187 :table-table in a table.el table
21188 :clocktable in a clocktable
21189 :src-block in a source block
21190 :link on a hyperlink
21191 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21192 :target on a <<target>>
21193 :radio-target on a <<<radio-target>>>
21194 :latex-fragment on a LaTeX fragment
21195 :latex-preview on a LaTeX fragment with overlaid preview image
21197 This function expects the position to be visible because it uses font-lock
21198 faces as a help to recognize the following contexts: :table-special, :link,
21199 and :keyword."
21200 (let* ((f (get-text-property (point) 'face))
21201 (faces (if (listp f) f (list f)))
21202 (case-fold-search t)
21203 (p (point)) clist o)
21204 ;; First the large context
21205 (cond
21206 ((org-at-heading-p t)
21207 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21208 (when (progn
21209 (beginning-of-line 1)
21210 (looking-at org-todo-line-tags-regexp))
21211 (push (org-point-in-group p 1 :headline-stars) clist)
21212 (push (org-point-in-group p 2 :todo-keyword) clist)
21213 (push (org-point-in-group p 4 :tags) clist))
21214 (goto-char p)
21215 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21216 (when (looking-at "\\[#[A-Z0-9]\\]")
21217 (push (org-point-in-group p 0 :priority) clist)))
21219 ((org-at-item-p)
21220 (push (org-point-in-group p 2 :item-bullet) clist)
21221 (push (list :item (point-at-bol)
21222 (save-excursion (org-end-of-item) (point)))
21223 clist)
21224 (and (org-at-item-checkbox-p)
21225 (push (org-point-in-group p 0 :checkbox) clist)))
21227 ((org-at-table-p)
21228 (push (list :table (org-table-begin) (org-table-end)) clist)
21229 (when (memq 'org-formula faces)
21230 (push (list :table-special
21231 (previous-single-property-change p 'face)
21232 (next-single-property-change p 'face)) clist)))
21233 ((org-at-table-p 'any)
21234 (push (list :table-table) clist)))
21235 (goto-char p)
21237 (let ((case-fold-search t))
21238 ;; New the "medium" contexts: clocktables, source blocks
21239 (cond ((org-in-clocktable-p)
21240 (push (list :clocktable
21241 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21242 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21243 (match-beginning 1))
21244 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21245 (match-end 0))) clist))
21246 ((org-in-src-block-p)
21247 (push (list :src-block
21248 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21249 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21250 (match-beginning 1))
21251 (and (search-forward "#+END_SRC" nil t)
21252 (match-beginning 0))) clist))))
21253 (goto-char p)
21255 ;; Now the small context
21256 (cond
21257 ((org-at-timestamp-p)
21258 (push (org-point-in-group p 0 :timestamp) clist))
21259 ((memq 'org-link faces)
21260 (push (list :link
21261 (previous-single-property-change p 'face)
21262 (next-single-property-change p 'face)) clist))
21263 ((memq 'org-special-keyword faces)
21264 (push (list :keyword
21265 (previous-single-property-change p 'face)
21266 (next-single-property-change p 'face)) clist))
21267 ((org-at-target-p)
21268 (push (org-point-in-group p 0 :target) clist)
21269 (goto-char (1- (match-beginning 0)))
21270 (when (looking-at org-radio-target-regexp)
21271 (push (org-point-in-group p 0 :radio-target) clist))
21272 (goto-char p))
21273 ((setq o (cl-some
21274 (lambda (o)
21275 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21277 (overlays-at (point))))
21278 (push (list :latex-fragment
21279 (overlay-start o) (overlay-end o)) clist)
21280 (push (list :latex-preview
21281 (overlay-start o) (overlay-end o)) clist))
21282 ((org-inside-LaTeX-fragment-p)
21283 ;; FIXME: positions wrong.
21284 (push (list :latex-fragment (point) (point)) clist)))
21286 (setq clist (nreverse (delq nil clist)))
21287 clist))
21289 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21290 "Non-nil when point is between matches of START-RE and END-RE.
21292 Also return a non-nil value when point is on one of the matches.
21294 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21295 buffer positions. Default values are the positions of headlines
21296 surrounding the point.
21298 The functions returns a cons cell whose car (resp. cdr) is the
21299 position before START-RE (resp. after END-RE)."
21300 (save-match-data
21301 (let ((pos (point))
21302 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21303 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21304 beg end)
21305 (save-excursion
21306 ;; Point is on a block when on START-RE or if START-RE can be
21307 ;; found before it...
21308 (and (or (org-in-regexp start-re)
21309 (re-search-backward start-re limit-up t))
21310 (setq beg (match-beginning 0))
21311 ;; ... and END-RE after it...
21312 (goto-char (match-end 0))
21313 (re-search-forward end-re limit-down t)
21314 (> (setq end (match-end 0)) pos)
21315 ;; ... without another START-RE in-between.
21316 (goto-char (match-beginning 0))
21317 (not (re-search-backward start-re (1+ beg) t))
21318 ;; Return value.
21319 (cons beg end))))))
21321 (defun org-in-block-p (names)
21322 "Non-nil when point belongs to a block whose name belongs to NAMES.
21324 NAMES is a list of strings containing names of blocks.
21326 Return first block name matched, or nil. Beware that in case of
21327 nested blocks, the returned name may not belong to the closest
21328 block from point."
21329 (save-match-data
21330 (catch 'exit
21331 (let ((case-fold-search t)
21332 (lim-up (save-excursion (outline-previous-heading)))
21333 (lim-down (save-excursion (outline-next-heading))))
21334 (dolist (name names)
21335 (let ((n (regexp-quote name)))
21336 (when (org-between-regexps-p
21337 (concat "^[ \t]*#\\+begin_" n)
21338 (concat "^[ \t]*#\\+end_" n)
21339 lim-up lim-down)
21340 (throw 'exit n)))))
21341 nil)))
21343 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21344 "Call `multi-occur' with buffers for all agenda files."
21345 (interactive "sOrg-files matching: ")
21346 (let* ((files (org-agenda-files))
21347 (tnames (mapcar #'file-truename files))
21348 (extra org-agenda-text-search-extra-files))
21349 (when (eq (car extra) 'agenda-archives)
21350 (setq extra (cdr extra))
21351 (setq files (org-add-archive-files files)))
21352 (dolist (f extra)
21353 (unless (member (file-truename f) tnames)
21354 (unless (member f files) (setq files (append files (list f))))
21355 (setq tnames (append tnames (list (file-truename f))))))
21356 (multi-occur
21357 (mapcar (lambda (x)
21358 (with-current-buffer
21359 ;; FIXME: Why not just (find-file-noselect x)?
21360 ;; Is it to avoid the "revert buffer" prompt?
21361 (or (get-file-buffer x) (find-file-noselect x))
21362 (widen)
21363 (current-buffer)))
21364 files)
21365 regexp)))
21367 (add-hook 'occur-mode-find-occurrence-hook
21368 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21370 (defun org-occur-link-in-agenda-files ()
21371 "Create a link and search for it in the agendas.
21372 The link is not stored in `org-stored-links', it is just created
21373 for the search purpose."
21374 (interactive)
21375 (let ((link (condition-case nil
21376 (org-store-link nil)
21377 (error "Unable to create a link to here"))))
21378 (org-occur-in-agenda-files (regexp-quote link))))
21380 (defun org-back-over-empty-lines ()
21381 "Move backwards over whitespace, to the beginning of the first empty line.
21382 Returns the number of empty lines passed."
21383 (let ((pos (point)))
21384 (if (cdr (assq 'heading org-blank-before-new-entry))
21385 (skip-chars-backward " \t\n\r")
21386 (unless (eobp)
21387 (forward-line -1)))
21388 (beginning-of-line 2)
21389 (goto-char (min (point) pos))
21390 (count-lines (point) pos)))
21392 (defun org-switch-to-buffer-other-window (&rest args)
21393 "Switch to buffer in a second window on the current frame.
21394 In particular, do not allow pop-up frames.
21395 Returns the newly created buffer."
21396 (org-no-popups
21397 (apply 'switch-to-buffer-other-window args)))
21399 (defun org-replace-escapes (string table)
21400 "Replace %-escapes in STRING with values in TABLE.
21401 TABLE is an association list with keys like \"%a\" and string values.
21402 The sequences in STRING may contain normal field width and padding information,
21403 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21404 so values can contain further %-escapes if they are define later in TABLE."
21405 (let ((tbl (copy-alist table))
21406 (case-fold-search nil)
21407 (pchg 0)
21408 re rpl)
21409 (dolist (e tbl)
21410 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21411 (when (and (cdr e) (string-match re (cdr e)))
21412 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21413 (safe "SREF"))
21414 (add-text-properties 0 3 (list 'sref sref) safe)
21415 (setcdr e (replace-match safe t t (cdr e)))))
21416 (while (string-match re string)
21417 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21418 (cdr e)))
21419 (setq string (replace-match rpl t t string))))
21420 (while (setq pchg (next-property-change pchg string))
21421 (let ((sref (get-text-property pchg 'sref string)))
21422 (when (and sref (string-match "SREF" string pchg))
21423 (setq string (replace-match sref t t string)))))
21424 string))
21426 ;;; TODO: Only called once, from ox-odt which should probably use
21427 ;;; org-export-inline-image-p or something.
21428 (defun org-file-image-p (file)
21429 "Return non-nil if FILE is an image."
21430 (save-match-data
21431 (string-match (image-file-name-regexp) file)))
21433 (defun org-get-cursor-date (&optional with-time)
21434 "Return the date at cursor in as a time.
21435 This works in the calendar and in the agenda, anywhere else it just
21436 returns the current time.
21437 If WITH-TIME is non-nil, returns the time of the event at point (in
21438 the agenda) or the current time of the day."
21439 (let (date day defd tp hod mod)
21440 (when with-time
21441 (setq tp (get-text-property (point) 'time))
21442 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21443 (setq hod (string-to-number (match-string 1 tp))
21444 mod (string-to-number (match-string 2 tp))))
21445 (or tp (let ((now (decode-time)))
21446 (setq hod (nth 2 now)
21447 mod (nth 1 now)))))
21448 (cond
21449 ((eq major-mode 'calendar-mode)
21450 (setq date (calendar-cursor-to-date)
21451 defd (encode-time 0 (or mod 0) (or hod 0)
21452 (nth 1 date) (nth 0 date) (nth 2 date))))
21453 ((eq major-mode 'org-agenda-mode)
21454 (setq day (get-text-property (point) 'day))
21455 (when day
21456 (setq date (calendar-gregorian-from-absolute day)
21457 defd (encode-time 0 (or mod 0) (or hod 0)
21458 (nth 1 date) (nth 0 date) (nth 2 date))))))
21459 (or defd (current-time))))
21461 (defun org-mark-subtree (&optional up)
21462 "Mark the current subtree.
21463 This puts point at the start of the current subtree, and mark at
21464 the end. If a numeric prefix UP is given, move up into the
21465 hierarchy of headlines by UP levels before marking the subtree."
21466 (interactive "P")
21467 (org-with-limited-levels
21468 (cond ((org-at-heading-p) (beginning-of-line))
21469 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21470 (t (outline-previous-visible-heading 1))))
21471 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21472 (if (called-interactively-p 'any)
21473 (call-interactively 'org-mark-element)
21474 (org-mark-element)))
21476 (defun org-file-newer-than-p (file time)
21477 "Non-nil if FILE is newer than TIME.
21478 FILE is a filename, as a string, TIME is a list of integers, as
21479 returned by, e.g., `current-time'."
21480 (and (file-exists-p file)
21481 ;; Only compare times up to whole seconds as some file-systems
21482 ;; (e.g. HFS+) do not retain any finer granularity. As
21483 ;; a consequence, make sure we return non-nil when the two
21484 ;; times are equal.
21485 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21486 (cl-subseq time 0 2)))))
21488 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21489 "Compile a SOURCE file using PROCESS.
21491 PROCESS is either a function or a list of shell commands, as
21492 strings. EXT is a file extension, without the leading dot, as
21493 a string. It is used to check if the process actually succeeded.
21495 PROCESS must create a file with the same base name and directory
21496 as SOURCE, but ending with EXT. The function then returns its
21497 filename. Otherwise, it raises an error. The error message can
21498 then be refined by providing string ERR-MSG, which is appended to
21499 the standard message.
21501 If PROCESS is a function, it is called with a single argument:
21502 the SOURCE file.
21504 If it is a list of commands, each of them is called using
21505 `shell-command'. By default, in each command, %b, %f, %F, %o and
21506 %O are replaced with, respectively, SOURCE base name, name, full
21507 name, directory and absolute output file name. It is possible,
21508 however, to use more place-holders by specifying them in optional
21509 argument SPEC, as an alist following the pattern
21511 (CHARACTER . REPLACEMENT-STRING).
21513 When PROCESS is a list of commands, optional argument LOG-BUF can
21514 be set to a buffer or a buffer name. `shell-command' then uses
21515 it for output."
21516 (let* ((base-name (file-name-base source))
21517 (full-name (file-truename source))
21518 (out-dir (or (file-name-directory source) "./"))
21519 (output (expand-file-name (concat base-name "." ext) out-dir))
21520 (time (current-time))
21521 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21522 (save-window-excursion
21523 (pcase process
21524 ((pred functionp) (funcall process (shell-quote-argument source)))
21525 ((pred consp)
21526 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21527 (spec (append spec
21528 `((?b . ,(shell-quote-argument base-name))
21529 (?f . ,(shell-quote-argument source))
21530 (?F . ,(shell-quote-argument full-name))
21531 (?o . ,(shell-quote-argument out-dir))
21532 (?O . ,(shell-quote-argument output))))))
21533 (dolist (command process)
21534 (shell-command (format-spec command spec) log-buf))
21535 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21536 (_ (error "No valid command to process %S%s" source err-msg))))
21537 ;; Check for process failure. Output file is expected to be
21538 ;; located in the same directory as SOURCE.
21539 (unless (org-file-newer-than-p output time)
21540 (error (format "File %S wasn't produced%s" output err-msg)))
21541 output))
21543 ;;; Indentation
21545 (defvar org-element-greater-elements)
21546 (defun org--get-expected-indentation (element contentsp)
21547 "Expected indentation column for current line, according to ELEMENT.
21548 ELEMENT is an element containing point. CONTENTSP is non-nil
21549 when indentation is to be computed according to contents of
21550 ELEMENT."
21551 (let ((type (org-element-type element))
21552 (start (org-element-property :begin element))
21553 (post-affiliated (org-element-property :post-affiliated element)))
21554 (org-with-wide-buffer
21555 (cond
21556 (contentsp
21557 (cl-case type
21558 ((diary-sexp footnote-definition) 0)
21559 ((headline inlinetask nil)
21560 (if (not org-adapt-indentation) 0
21561 (let ((level (org-current-level)))
21562 (if level (1+ level) 0))))
21563 ((item plain-list) (org-list-item-body-column post-affiliated))
21565 (goto-char start)
21566 (org-get-indentation))))
21567 ((memq type '(headline inlinetask nil))
21568 (if (org-match-line "[ \t]*$")
21569 (org--get-expected-indentation element t)
21571 ((memq type '(diary-sexp footnote-definition)) 0)
21572 ;; First paragraph of a footnote definition or an item.
21573 ;; Indent like parent.
21574 ((< (line-beginning-position) start)
21575 (org--get-expected-indentation
21576 (org-element-property :parent element) t))
21577 ;; At first line: indent according to previous sibling, if any,
21578 ;; ignoring footnote definitions and inline tasks, or parent's
21579 ;; contents.
21580 ((= (line-beginning-position) start)
21581 (catch 'exit
21582 (while t
21583 (if (= (point-min) start) (throw 'exit 0)
21584 (goto-char (1- start))
21585 (let* ((previous (org-element-at-point))
21586 (parent previous))
21587 (while (and parent (<= (org-element-property :end parent) start))
21588 (setq previous parent
21589 parent (org-element-property :parent parent)))
21590 (cond
21591 ((not previous) (throw 'exit 0))
21592 ((> (org-element-property :end previous) start)
21593 (throw 'exit (org--get-expected-indentation previous t)))
21594 ((memq (org-element-type previous)
21595 '(footnote-definition inlinetask))
21596 (setq start (org-element-property :begin previous)))
21597 (t (goto-char (org-element-property :begin previous))
21598 (throw 'exit
21599 (if (bolp) (org-get-indentation)
21600 ;; At first paragraph in an item or
21601 ;; a footnote definition.
21602 (org--get-expected-indentation
21603 (org-element-property :parent previous) t))))))))))
21604 ;; Otherwise, move to the first non-blank line above.
21606 (beginning-of-line)
21607 (let ((pos (point)))
21608 (skip-chars-backward " \r\t\n")
21609 (cond
21610 ;; Two blank lines end a footnote definition or a plain
21611 ;; list. When we indent an empty line after them, the
21612 ;; containing list or footnote definition is over, so it
21613 ;; qualifies as a previous sibling. Therefore, we indent
21614 ;; like its first line.
21615 ((and (memq type '(footnote-definition plain-list))
21616 (> (count-lines (point) pos) 2))
21617 (goto-char start)
21618 (org-get-indentation))
21619 ;; Line above is the first one of a paragraph at the
21620 ;; beginning of an item or a footnote definition. Indent
21621 ;; like parent.
21622 ((< (line-beginning-position) start)
21623 (org--get-expected-indentation
21624 (org-element-property :parent element) t))
21625 ;; Line above is the beginning of an element, i.e., point
21626 ;; was originally on the blank lines between element's start
21627 ;; and contents.
21628 ((= (line-beginning-position) post-affiliated)
21629 (org--get-expected-indentation element t))
21630 ;; POS is after contents in a greater element. Indent like
21631 ;; the beginning of the element.
21632 ((and (memq type org-element-greater-elements)
21633 (let ((cend (org-element-property :contents-end element)))
21634 (and cend (<= cend pos))))
21635 ;; As a special case, if point is at the end of a footnote
21636 ;; definition or an item, indent like the very last element
21637 ;; within. If that last element is an item, indent like
21638 ;; its contents.
21639 (if (memq type '(footnote-definition item plain-list))
21640 (let ((last (org-element-at-point)))
21641 (goto-char pos)
21642 (org--get-expected-indentation
21643 last (eq (org-element-type last) 'item)))
21644 (goto-char start)
21645 (org-get-indentation)))
21646 ;; In any other case, indent like the current line.
21647 (t (org-get-indentation)))))))))
21649 (defun org--align-node-property ()
21650 "Align node property at point.
21651 Alignment is done according to `org-property-format', which see."
21652 (when (save-excursion
21653 (beginning-of-line)
21654 (looking-at org-property-re))
21655 (replace-match
21656 (concat (match-string 4)
21657 (org-trim
21658 (format org-property-format (match-string 1) (match-string 3))))
21659 t t)))
21661 (defun org-indent-line ()
21662 "Indent line depending on context.
21664 Indentation is done according to the following rules:
21666 - Footnote definitions, diary sexps, headlines and inline tasks
21667 have to start at column 0.
21669 - On the very first line of an element, consider, in order, the
21670 next rules until one matches:
21672 1. If there's a sibling element before, ignoring footnote
21673 definitions and inline tasks, indent like its first line.
21675 2. If element has a parent, indent like its contents. More
21676 precisely, if parent is an item, indent after the
21677 description part, if any, or the bullet (see
21678 `org-list-description-max-indent'). Else, indent like
21679 parent's first line.
21681 3. Otherwise, indent relatively to current level, if
21682 `org-adapt-indentation' is non-nil, or to left margin.
21684 - On a blank line at the end of an element, indent according to
21685 the type of the element. More precisely
21687 1. If element is a plain list, an item, or a footnote
21688 definition, indent like the very last element within.
21690 2. If element is a paragraph, indent like its last non blank
21691 line.
21693 3. Otherwise, indent like its very first line.
21695 - In the code part of a source block, use language major mode
21696 to indent current line if `org-src-tab-acts-natively' is
21697 non-nil. If it is nil, do nothing.
21699 - Otherwise, indent like the first non-blank line above.
21701 The function doesn't indent an item as it could break the whole
21702 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21703 `\\[org-shiftmetaright]'.
21705 Also align node properties according to `org-property-format'."
21706 (interactive)
21707 (cond
21708 ((org-at-heading-p) 'noindent)
21710 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21711 (type (org-element-type element)))
21712 (cond ((and (memq type '(plain-list item))
21713 (= (line-beginning-position)
21714 (org-element-property :post-affiliated element)))
21715 'noindent)
21716 ((and (eq type 'latex-environment)
21717 (>= (point) (org-element-property :post-affiliated element))
21718 (< (point) (org-with-wide-buffer
21719 (goto-char (org-element-property :end element))
21720 (skip-chars-backward " \r\t\n")
21721 (line-beginning-position 2))))
21722 'noindent)
21723 ((and (eq type 'src-block)
21724 org-src-tab-acts-natively
21725 (> (line-beginning-position)
21726 (org-element-property :post-affiliated element))
21727 (< (line-beginning-position)
21728 (org-with-wide-buffer
21729 (goto-char (org-element-property :end element))
21730 (skip-chars-backward " \r\t\n")
21731 (line-beginning-position))))
21732 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21734 (let ((column (org--get-expected-indentation element nil)))
21735 ;; Preserve current column.
21736 (if (<= (current-column) (current-indentation))
21737 (indent-line-to column)
21738 (save-excursion (indent-line-to column))))
21739 ;; Align node property. Also preserve current column.
21740 (when (eq type 'node-property)
21741 (let ((column (current-column)))
21742 (org--align-node-property)
21743 (org-move-to-column column)))))))))
21745 (defun org-indent-region (start end)
21746 "Indent each non-blank line in the region.
21747 Called from a program, START and END specify the region to
21748 indent. The function will not indent contents of example blocks,
21749 verse blocks and export blocks as leading white spaces are
21750 assumed to be significant there."
21751 (interactive "r")
21752 (save-excursion
21753 (goto-char start)
21754 (skip-chars-forward " \r\t\n")
21755 (unless (eobp) (beginning-of-line))
21756 (let ((indent-to
21757 (lambda (ind pos)
21758 ;; Set IND as indentation for all lines between point and
21759 ;; POS. Blank lines are ignored. Leave point after POS
21760 ;; once done.
21761 (let ((limit (copy-marker pos)))
21762 (while (< (point) limit)
21763 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21764 (forward-line))
21765 (set-marker limit nil))))
21766 (end (copy-marker end)))
21767 (while (< (point) end)
21768 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21769 (let* ((element (org-element-at-point))
21770 (type (org-element-type element))
21771 (element-end (copy-marker (org-element-property :end element)))
21772 (ind (org--get-expected-indentation element nil)))
21773 (cond
21774 ;; Element indented as a single block. Example blocks
21775 ;; preserving indentation are a special case since the
21776 ;; "contents" must not be indented whereas the block
21777 ;; boundaries can.
21778 ((or (memq type '(export-block latex-environment))
21779 (and (eq type 'example-block)
21780 (not
21781 (or org-src-preserve-indentation
21782 (org-element-property :preserve-indent element)))))
21783 (let ((offset (- ind (org-get-indentation))))
21784 (unless (zerop offset)
21785 (indent-rigidly (org-element-property :begin element)
21786 (org-element-property :end element)
21787 offset)))
21788 (goto-char element-end))
21789 ;; Elements indented line wise. Be sure to exclude
21790 ;; example blocks (preserving indentation) and source
21791 ;; blocks from this category as they are treated
21792 ;; specially later.
21793 ((or (memq type '(paragraph table table-row))
21794 (not (or (org-element-property :contents-begin element)
21795 (memq type '(example-block src-block)))))
21796 (when (eq type 'node-property)
21797 (org--align-node-property)
21798 (beginning-of-line))
21799 (funcall indent-to ind (min element-end end)))
21800 ;; Elements consisting of three parts: before the
21801 ;; contents, the contents, and after the contents. The
21802 ;; contents are treated specially, according to the
21803 ;; element type, or not indented at all. Other parts are
21804 ;; indented as a single block.
21806 (let* ((post (copy-marker
21807 (org-element-property :post-affiliated element)))
21808 (cbeg
21809 (copy-marker
21810 (cond
21811 ((not (org-element-property :contents-begin element))
21812 ;; Fake contents for source blocks.
21813 (org-with-wide-buffer
21814 (goto-char post)
21815 (line-beginning-position 2)))
21816 ((memq type '(footnote-definition item plain-list))
21817 ;; Contents in these elements could start on
21818 ;; the same line as the beginning of the
21819 ;; element. Make sure we start indenting
21820 ;; from the second line.
21821 (org-with-wide-buffer
21822 (goto-char post)
21823 (end-of-line)
21824 (skip-chars-forward " \r\t\n")
21825 (if (eobp) (point) (line-beginning-position))))
21826 (t (org-element-property :contents-begin element)))))
21827 (cend (copy-marker
21828 (or (org-element-property :contents-end element)
21829 ;; Fake contents for source blocks.
21830 (org-with-wide-buffer
21831 (goto-char element-end)
21832 (skip-chars-backward " \r\t\n")
21833 (line-beginning-position)))
21834 t)))
21835 ;; Do not change items indentation individually as it
21836 ;; might break the list as a whole. On the other
21837 ;; hand, when at a plain list, indent it as a whole.
21838 (cond ((eq type 'plain-list)
21839 (let ((offset (- ind (org-get-indentation))))
21840 (unless (zerop offset)
21841 (indent-rigidly (org-element-property :begin element)
21842 (org-element-property :end element)
21843 offset))
21844 (goto-char cbeg)))
21845 ((eq type 'item) (goto-char cbeg))
21846 (t (funcall indent-to ind (min cbeg end))))
21847 (when (< (point) end)
21848 (cl-case type
21849 ((example-block verse-block))
21850 (src-block
21851 ;; In a source block, indent source code
21852 ;; according to language major mode, but only if
21853 ;; `org-src-tab-acts-natively' is non-nil.
21854 (when (and (< (point) end) org-src-tab-acts-natively)
21855 (ignore-errors
21856 (org-babel-do-in-edit-buffer
21857 (indent-region (point-min) (point-max))))))
21858 (t (org-indent-region (point) (min cend end))))
21859 (goto-char (min cend end))
21860 (when (< (point) end)
21861 (funcall indent-to ind (min element-end end))))
21862 (set-marker post nil)
21863 (set-marker cbeg nil)
21864 (set-marker cend nil))))
21865 (set-marker element-end nil))))
21866 (set-marker end nil))))
21868 (defun org-indent-drawer ()
21869 "Indent the drawer at point."
21870 (interactive)
21871 (unless (save-excursion
21872 (beginning-of-line)
21873 (looking-at-p org-drawer-regexp))
21874 (user-error "Not at a drawer"))
21875 (let ((element (org-element-at-point)))
21876 (unless (memq (org-element-type element) '(drawer property-drawer))
21877 (user-error "Not at a drawer"))
21878 (org-with-wide-buffer
21879 (org-indent-region (org-element-property :begin element)
21880 (org-element-property :end element))))
21881 (message "Drawer at point indented"))
21883 (defun org-indent-block ()
21884 "Indent the block at point."
21885 (interactive)
21886 (unless (save-excursion
21887 (beginning-of-line)
21888 (let ((case-fold-search t))
21889 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21890 (user-error "Not at a block"))
21891 (let ((element (org-element-at-point)))
21892 (unless (memq (org-element-type element)
21893 '(comment-block center-block dynamic-block example-block
21894 export-block quote-block special-block
21895 src-block verse-block))
21896 (user-error "Not at a block"))
21897 (org-with-wide-buffer
21898 (org-indent-region (org-element-property :begin element)
21899 (org-element-property :end element))))
21900 (message "Block at point indented"))
21903 ;;; Filling
21905 ;; We use our own fill-paragraph and auto-fill functions.
21907 ;; `org-fill-paragraph' relies on adaptive filling and context
21908 ;; checking. Appropriate `fill-prefix' is computed with
21909 ;; `org-adaptive-fill-function'.
21911 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21912 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21913 ;; `org-adaptive-fill-function' value. Internally,
21914 ;; `org-comment-line-break-function' breaks the line.
21916 ;; `org-setup-filling' installs filling and auto-filling related
21917 ;; variables during `org-mode' initialization.
21919 (defun org-setup-filling ()
21920 (require 'org-element)
21921 ;; Prevent auto-fill from inserting unwanted new items.
21922 (when (boundp 'fill-nobreak-predicate)
21923 (setq-local
21924 fill-nobreak-predicate
21925 (org-uniquify
21926 (append fill-nobreak-predicate
21927 '(org-fill-line-break-nobreak-p
21928 org-fill-n-macro-as-item-nobreak-p
21929 org-fill-paragraph-with-timestamp-nobreak-p)))))
21930 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21931 (setq-local paragraph-start paragraph-ending)
21932 (setq-local paragraph-separate paragraph-ending))
21933 (setq-local fill-paragraph-function 'org-fill-paragraph)
21934 (setq-local auto-fill-inhibit-regexp nil)
21935 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21936 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21937 (setq-local comment-line-break-function 'org-comment-line-break-function))
21939 (defun org-fill-line-break-nobreak-p ()
21940 "Non-nil when a new line at point would create an Org line break."
21941 (save-excursion
21942 (skip-chars-backward "[ \t]")
21943 (skip-chars-backward "\\\\")
21944 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21946 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21947 "Non-nil when a new line at point would split a timestamp."
21948 (and (org-at-timestamp-p 'lax)
21949 (not (looking-at org-ts-regexp-both))))
21951 (defun org-fill-n-macro-as-item-nobreak-p ()
21952 "Non-nil when a new line at point would create a new list."
21953 ;; During export, a "n" macro followed by a dot or a closing
21954 ;; parenthesis can end up being parsed as a new list item.
21955 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21957 (defvar orgtbl-line-start-regexp) ; From org-table.el
21958 (defun org-adaptive-fill-function ()
21959 "Compute a fill prefix for the current line.
21960 Return fill prefix, as a string, or nil if current line isn't
21961 meant to be filled. For convenience, if `adaptive-fill-regexp'
21962 matches in paragraphs or comments, use it."
21963 (org-with-wide-buffer
21964 (unless (org-at-heading-p)
21965 (let* ((p (line-beginning-position))
21966 (element (save-excursion
21967 (beginning-of-line)
21968 (org-element-at-point)))
21969 (type (org-element-type element))
21970 (post-affiliated (org-element-property :post-affiliated element)))
21971 (unless (< p post-affiliated)
21972 (cl-case type
21973 (comment
21974 (save-excursion
21975 (beginning-of-line)
21976 (looking-at "[ \t]*")
21977 (concat (match-string 0) "# ")))
21978 (footnote-definition "")
21979 ((item plain-list)
21980 (make-string (org-list-item-body-column post-affiliated) ?\s))
21981 (paragraph
21982 ;; Fill prefix is usually the same as the current line,
21983 ;; unless the paragraph is at the beginning of an item.
21984 (let ((parent (org-element-property :parent element)))
21985 (save-excursion
21986 (beginning-of-line)
21987 (cond ((eq (org-element-type parent) 'item)
21988 (make-string (org-list-item-body-column
21989 (org-element-property :begin parent))
21990 ?\s))
21991 ((and adaptive-fill-regexp
21992 ;; Locally disable
21993 ;; `adaptive-fill-function' to let
21994 ;; `fill-context-prefix' handle
21995 ;; `adaptive-fill-regexp' variable.
21996 (let (adaptive-fill-function)
21997 (fill-context-prefix
21998 post-affiliated
21999 (org-element-property :end element)))))
22000 ((looking-at "[ \t]+") (match-string 0))
22001 (t "")))))
22002 (comment-block
22003 ;; Only fill contents if P is within block boundaries.
22004 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22005 (forward-line)
22006 (point)))
22007 (cend (save-excursion
22008 (goto-char (org-element-property :end element))
22009 (skip-chars-backward " \r\t\n")
22010 (line-beginning-position))))
22011 (when (and (>= p cbeg) (< p cend))
22012 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22013 (match-string 0)
22014 ""))))))))))
22016 (defun org-fill-element (&optional justify)
22017 "Fill element at point, when applicable.
22019 This function only applies to comment blocks, comments, example
22020 blocks and paragraphs. Also, as a special case, re-align table
22021 when point is at one.
22023 If JUSTIFY is non-nil (interactively, with prefix argument),
22024 justify as well. If `sentence-end-double-space' is non-nil, then
22025 period followed by one space does not end a sentence, so don't
22026 break a line there. The variable `fill-column' controls the
22027 width for filling.
22029 For convenience, when point is at a plain list, an item or
22030 a footnote definition, try to fill the first paragraph within."
22031 (with-syntax-table org-mode-transpose-word-syntax-table
22032 ;; Move to end of line in order to get the first paragraph within
22033 ;; a plain list or a footnote definition.
22034 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22035 ;; First check if point is in a blank line at the beginning of
22036 ;; the buffer. In that case, ignore filling.
22037 (cl-case (org-element-type element)
22038 ;; Use major mode filling function is src blocks.
22039 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22040 ;; Align Org tables, leave table.el tables as-is.
22041 (table-row (org-table-align) t)
22042 (table
22043 (when (eq (org-element-property :type element) 'org)
22044 (save-excursion
22045 (goto-char (org-element-property :post-affiliated element))
22046 (org-table-align)))
22048 (paragraph
22049 ;; Paragraphs may contain `line-break' type objects.
22050 (let ((beg (max (point-min)
22051 (org-element-property :contents-begin element)))
22052 (end (min (point-max)
22053 (org-element-property :contents-end element))))
22054 ;; Do nothing if point is at an affiliated keyword.
22055 (if (< (line-end-position) beg) t
22056 ;; Fill paragraph, taking line breaks into account.
22057 (save-excursion
22058 (goto-char beg)
22059 (let ((cuts (list beg)))
22060 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22061 (when (eq 'line-break
22062 (org-element-type
22063 (save-excursion (backward-char)
22064 (org-element-context))))
22065 (push (point) cuts)))
22066 (dolist (c (delq end cuts))
22067 (fill-region-as-paragraph c end justify)
22068 (setq end c))))
22069 t)))
22070 ;; Contents of `comment-block' type elements should be
22071 ;; filled as plain text, but only if point is within block
22072 ;; markers.
22073 (comment-block
22074 (let* ((case-fold-search t)
22075 (beg (save-excursion
22076 (goto-char (org-element-property :begin element))
22077 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22078 (forward-line)
22079 (point)))
22080 (end (save-excursion
22081 (goto-char (org-element-property :end element))
22082 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22083 (line-beginning-position))))
22084 (if (or (< (point) beg) (> (point) end)) t
22085 (fill-region-as-paragraph
22086 (save-excursion (end-of-line)
22087 (re-search-backward "^[ \t]*$" beg 'move)
22088 (line-beginning-position))
22089 (save-excursion (beginning-of-line)
22090 (re-search-forward "^[ \t]*$" end 'move)
22091 (line-beginning-position))
22092 justify))))
22093 ;; Fill comments.
22094 (comment
22095 (let ((begin (org-element-property :post-affiliated element))
22096 (end (org-element-property :end element)))
22097 (when (and (>= (point) begin) (<= (point) end))
22098 (let ((begin (save-excursion
22099 (end-of-line)
22100 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22101 (progn (forward-line) (point))
22102 begin)))
22103 (end (save-excursion
22104 (end-of-line)
22105 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22106 (1- (line-beginning-position))
22107 (skip-chars-backward " \r\t\n")
22108 (line-end-position)))))
22109 ;; Do not fill comments when at a blank line.
22110 (when (> end begin)
22111 (let ((fill-prefix
22112 (save-excursion
22113 (beginning-of-line)
22114 (looking-at "[ \t]*#")
22115 (let ((comment-prefix (match-string 0)))
22116 (goto-char (match-end 0))
22117 (if (looking-at adaptive-fill-regexp)
22118 (concat comment-prefix (match-string 0))
22119 (concat comment-prefix " "))))))
22120 (save-excursion
22121 (fill-region-as-paragraph begin end justify))))))
22123 ;; Ignore every other element.
22124 (otherwise t)))))
22126 (defun org-fill-paragraph (&optional justify region)
22127 "Fill element at point, when applicable.
22129 This function only applies to comment blocks, comments, example
22130 blocks and paragraphs. Also, as a special case, re-align table
22131 when point is at one.
22133 For convenience, when point is at a plain list, an item or
22134 a footnote definition, try to fill the first paragraph within.
22136 If JUSTIFY is non-nil (interactively, with prefix argument),
22137 justify as well. If `sentence-end-double-space' is non-nil, then
22138 period followed by one space does not end a sentence, so don't
22139 break a line there. The variable `fill-column' controls the
22140 width for filling.
22142 The REGION argument is non-nil if called interactively; in that
22143 case, if Transient Mark mode is enabled and the mark is active,
22144 fill each of the elements in the active region, instead of just
22145 filling the current element."
22146 (interactive (progn
22147 (barf-if-buffer-read-only)
22148 (list (if current-prefix-arg 'full) t)))
22149 (cond
22150 ((and region transient-mark-mode mark-active
22151 (not (eq (region-beginning) (region-end))))
22152 (let ((origin (point-marker))
22153 (start (region-beginning)))
22154 (unwind-protect
22155 (progn
22156 (goto-char (region-end))
22157 (while (> (point) start)
22158 (org-backward-paragraph)
22159 (org-fill-element justify)))
22160 (goto-char origin)
22161 (set-marker origin nil))))
22162 (t (org-fill-element justify))))
22164 (defun org-auto-fill-function ()
22165 "Auto-fill function."
22166 ;; Check if auto-filling is meaningful.
22167 (let ((fc (current-fill-column)))
22168 (when (and fc (> (current-column) fc))
22169 (let* ((fill-prefix (org-adaptive-fill-function))
22170 ;; Enforce empty fill prefix, if required. Otherwise, it
22171 ;; will be computed again.
22172 (adaptive-fill-mode (not (equal fill-prefix ""))))
22173 (when fill-prefix (do-auto-fill))))))
22175 (defun org-comment-line-break-function (&optional soft)
22176 "Break line at point and indent, continuing comment if within one.
22177 The inserted newline is marked hard if variable
22178 `use-hard-newlines' is true, unless optional argument SOFT is
22179 non-nil."
22180 (if soft (insert-and-inherit ?\n) (newline 1))
22181 (save-excursion (forward-char -1) (delete-horizontal-space))
22182 (delete-horizontal-space)
22183 (indent-to-left-margin)
22184 (insert-before-markers-and-inherit fill-prefix))
22187 ;;; Fixed Width Areas
22189 (defun org-toggle-fixed-width ()
22190 "Toggle fixed-width markup.
22192 Add or remove fixed-width markup on current line, whenever it
22193 makes sense. Return an error otherwise.
22195 If a region is active and if it contains only fixed-width areas
22196 or blank lines, remove all fixed-width markup in it. If the
22197 region contains anything else, convert all non-fixed-width lines
22198 to fixed-width ones.
22200 Blank lines at the end of the region are ignored unless the
22201 region only contains such lines."
22202 (interactive)
22203 (if (not (org-region-active-p))
22204 ;; No region:
22206 ;; Remove fixed width marker only in a fixed-with element.
22208 ;; Add fixed width maker in paragraphs, in blank lines after
22209 ;; elements or at the beginning of a headline or an inlinetask,
22210 ;; and before any one-line elements (e.g., a clock).
22211 (progn
22212 (beginning-of-line)
22213 (let* ((element (org-element-at-point))
22214 (type (org-element-type element)))
22215 (cond
22216 ((and (eq type 'fixed-width)
22217 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22218 (replace-match
22219 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22220 ((and (memq type '(babel-call clock comment diary-sexp headline
22221 horizontal-rule keyword paragraph
22222 planning))
22223 (<= (org-element-property :post-affiliated element) (point)))
22224 (skip-chars-forward " \t")
22225 (insert ": "))
22226 ((and (looking-at-p "[ \t]*$")
22227 (or (eq type 'inlinetask)
22228 (save-excursion
22229 (skip-chars-forward " \r\t\n")
22230 (<= (org-element-property :end element) (point)))))
22231 (delete-region (point) (line-end-position))
22232 (org-indent-line)
22233 (insert ": "))
22234 (t (user-error "Cannot insert a fixed-width line here")))))
22235 ;; Region active.
22236 (let* ((begin (save-excursion
22237 (goto-char (region-beginning))
22238 (line-beginning-position)))
22239 (end (copy-marker
22240 (save-excursion
22241 (goto-char (region-end))
22242 (unless (eolp) (beginning-of-line))
22243 (if (save-excursion (re-search-backward "\\S-" begin t))
22244 (progn (skip-chars-backward " \r\t\n") (point))
22245 (point)))))
22246 (all-fixed-width-p
22247 (catch 'not-all-p
22248 (save-excursion
22249 (goto-char begin)
22250 (skip-chars-forward " \r\t\n")
22251 (when (eobp) (throw 'not-all-p nil))
22252 (while (< (point) end)
22253 (let ((element (org-element-at-point)))
22254 (if (eq (org-element-type element) 'fixed-width)
22255 (goto-char (org-element-property :end element))
22256 (throw 'not-all-p nil))))
22257 t))))
22258 (if all-fixed-width-p
22259 (save-excursion
22260 (goto-char begin)
22261 (while (< (point) end)
22262 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22263 (replace-match
22264 "" nil nil nil
22265 (if (= (line-end-position) (match-end 0)) 0 1)))
22266 (forward-line)))
22267 (let ((min-ind (point-max)))
22268 ;; Find minimum indentation across all lines.
22269 (save-excursion
22270 (goto-char begin)
22271 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22272 (setq min-ind 0)
22273 (catch 'zerop
22274 (while (< (point) end)
22275 (unless (looking-at-p "[ \t]*$")
22276 (let ((ind (org-get-indentation)))
22277 (setq min-ind (min min-ind ind))
22278 (when (zerop ind) (throw 'zerop t))))
22279 (forward-line)))))
22280 ;; Loop over all lines and add fixed-width markup everywhere
22281 ;; but in fixed-width lines.
22282 (save-excursion
22283 (goto-char begin)
22284 (while (< (point) end)
22285 (cond
22286 ((org-at-heading-p)
22287 (insert ": ")
22288 (forward-line)
22289 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22290 (insert ":")
22291 (forward-line)))
22292 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22293 (let* ((element (org-element-at-point))
22294 (element-end (org-element-property :end element)))
22295 (if (eq (org-element-type element) 'fixed-width)
22296 (progn (goto-char element-end)
22297 (skip-chars-backward " \r\t\n")
22298 (forward-line))
22299 (let ((limit (min end element-end)))
22300 (while (< (point) limit)
22301 (org-move-to-column min-ind t)
22302 (insert ": ")
22303 (forward-line))))))
22305 (org-move-to-column min-ind t)
22306 (insert ": ")
22307 (forward-line)))))))
22308 (set-marker end nil))))
22311 ;;; Blocks
22313 (defun org-block-map (function &optional start end)
22314 "Call FUNCTION at the head of all source blocks in the current buffer.
22315 Optional arguments START and END can be used to limit the range."
22316 (let ((start (or start (point-min)))
22317 (end (or end (point-max))))
22318 (save-excursion
22319 (goto-char start)
22320 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22321 (save-excursion
22322 (save-match-data
22323 (goto-char (match-beginning 0))
22324 (funcall function)))))))
22326 (defun org-next-block (arg &optional backward block-regexp)
22327 "Jump to the next block.
22329 With a prefix argument ARG, jump forward ARG many blocks.
22331 When BACKWARD is non-nil, jump to the previous block.
22333 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22334 Match data is set according to this regexp when the function
22335 returns.
22337 Return point at beginning of the opening line of found block.
22338 Throw an error if no block is found."
22339 (interactive "p")
22340 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22341 (case-fold-search t)
22342 (search-fn (if backward #'re-search-backward #'re-search-forward))
22343 (count (or arg 1))
22344 (origin (point))
22345 last-element)
22346 (if backward (beginning-of-line) (end-of-line))
22347 (while (and (> count 0) (funcall search-fn re nil t))
22348 (let ((element (save-excursion
22349 (goto-char (match-beginning 0))
22350 (save-match-data (org-element-at-point)))))
22351 (when (and (memq (org-element-type element)
22352 '(center-block comment-block dynamic-block
22353 example-block export-block quote-block
22354 special-block src-block verse-block))
22355 (<= (match-beginning 0)
22356 (org-element-property :post-affiliated element)))
22357 (setq last-element element)
22358 (cl-decf count))))
22359 (if (= count 0)
22360 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22361 (save-match-data (org-show-context)))
22362 (goto-char origin)
22363 (user-error "No %s code blocks" (if backward "previous" "further")))))
22365 (defun org-previous-block (arg &optional block-regexp)
22366 "Jump to the previous block.
22367 With a prefix argument ARG, jump backward ARG many source blocks.
22368 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22369 (interactive "p")
22370 (org-next-block arg t block-regexp))
22373 ;;; Comments
22375 ;; Org comments syntax is quite complex. It requires the entire line
22376 ;; to be just a comment. Also, even with the right syntax at the
22377 ;; beginning of line, some elements (e.g., verse-block or
22378 ;; example-block) don't accept comments. Usual Emacs comment commands
22379 ;; cannot cope with those requirements. Therefore, Org replaces them.
22381 ;; Org still relies on `comment-dwim', but cannot trust
22382 ;; `comment-only-p'. So, `comment-region-function' and
22383 ;; `uncomment-region-function' both point
22384 ;; to`org-comment-or-uncomment-region'. Eventually,
22385 ;; `org-insert-comment' takes care of insertion of comments at the
22386 ;; beginning of line.
22388 ;; `org-setup-comments-handling' install comments related variables
22389 ;; during `org-mode' initialization.
22391 (defun org-setup-comments-handling ()
22392 (interactive)
22393 (setq-local comment-use-syntax nil)
22394 (setq-local comment-start "# ")
22395 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22396 (setq-local comment-insert-comment-function 'org-insert-comment)
22397 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22398 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22400 (defun org-insert-comment ()
22401 "Insert an empty comment above current line.
22402 If the line is empty, insert comment at its beginning. When
22403 point is within a source block, comment according to the related
22404 major mode."
22405 (if (let ((element (org-element-at-point)))
22406 (and (eq (org-element-type element) 'src-block)
22407 (< (save-excursion
22408 (goto-char (org-element-property :post-affiliated element))
22409 (line-end-position))
22410 (point))
22411 (> (save-excursion
22412 (goto-char (org-element-property :end element))
22413 (skip-chars-backward " \r\t\n")
22414 (line-beginning-position))
22415 (point))))
22416 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22417 (beginning-of-line)
22418 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22419 (open-line 1))
22420 (org-indent-line)
22421 (insert "# ")))
22423 (defvar comment-empty-lines) ; From newcomment.el.
22424 (defun org-comment-or-uncomment-region (beg end &rest _)
22425 "Comment or uncomment each non-blank line in the region.
22426 Uncomment each non-blank line between BEG and END if it only
22427 contains commented lines. Otherwise, comment them. If region is
22428 strictly within a source block, use appropriate comment syntax."
22429 (if (let ((element (org-element-at-point)))
22430 (and (eq (org-element-type element) 'src-block)
22431 (< (save-excursion
22432 (goto-char (org-element-property :post-affiliated element))
22433 (line-end-position))
22434 beg)
22435 (>= (save-excursion
22436 (goto-char (org-element-property :end element))
22437 (skip-chars-backward " \r\t\n")
22438 (line-beginning-position))
22439 end)))
22440 ;; Translate region boundaries for the Org buffer to the source
22441 ;; buffer.
22442 (let ((offset (- end beg)))
22443 (save-excursion
22444 (goto-char beg)
22445 (org-babel-do-in-edit-buffer
22446 (comment-or-uncomment-region (point) (+ offset (point))))))
22447 (save-restriction
22448 ;; Restrict region
22449 (narrow-to-region (save-excursion (goto-char beg)
22450 (skip-chars-forward " \r\t\n" end)
22451 (line-beginning-position))
22452 (save-excursion (goto-char end)
22453 (skip-chars-backward " \r\t\n" beg)
22454 (line-end-position)))
22455 (let ((uncommentp
22456 ;; UNCOMMENTP is non-nil when every non blank line between
22457 ;; BEG and END is a comment.
22458 (save-excursion
22459 (goto-char (point-min))
22460 (while (and (not (eobp))
22461 (let ((element (org-element-at-point)))
22462 (and (eq (org-element-type element) 'comment)
22463 (goto-char (min (point-max)
22464 (org-element-property
22465 :end element)))))))
22466 (eobp))))
22467 (if uncommentp
22468 ;; Only blank lines and comments in region: uncomment it.
22469 (save-excursion
22470 (goto-char (point-min))
22471 (while (not (eobp))
22472 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22473 (replace-match "" nil nil nil 1))
22474 (forward-line)))
22475 ;; Comment each line in region.
22476 (let ((min-indent (point-max)))
22477 ;; First find the minimum indentation across all lines.
22478 (save-excursion
22479 (goto-char (point-min))
22480 (while (and (not (eobp)) (not (zerop min-indent)))
22481 (unless (looking-at "[ \t]*$")
22482 (setq min-indent (min min-indent (current-indentation))))
22483 (forward-line)))
22484 ;; Then loop over all lines.
22485 (save-excursion
22486 (goto-char (point-min))
22487 (while (not (eobp))
22488 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22489 ;; Don't get fooled by invisible text (e.g. link path)
22490 ;; when moving to column MIN-INDENT.
22491 (let ((buffer-invisibility-spec nil))
22492 (org-move-to-column min-indent t))
22493 (insert comment-start))
22494 (forward-line)))))))))
22496 (defun org-comment-dwim (_arg)
22497 "Call the comment command you mean.
22498 Call `org-toggle-comment' if on a heading, otherwise call
22499 `comment-dwim', within a source edit buffer if needed."
22500 (interactive "*P")
22501 (cond ((org-at-heading-p)
22502 (call-interactively #'org-toggle-comment))
22503 ((org-in-src-block-p)
22504 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22505 (t (call-interactively #'comment-dwim))))
22508 ;;; Timestamps API
22510 ;; This section contains tools to operate on, or create, timestamp
22511 ;; objects, as returned by, e.g. `org-element-context'.
22513 (defun org-timestamp-from-string (s)
22514 "Convert Org timestamp S, as a string, into a timestamp object.
22515 Return nil if S is not a valid timestamp string."
22516 (when (org-string-nw-p s)
22517 (with-temp-buffer
22518 (save-excursion (insert s))
22519 (org-element-timestamp-parser))))
22521 (defun org-timestamp-from-time (time &optional with-time inactive)
22522 "Convert a time value into a timestamp object.
22524 TIME is an Emacs internal time representation, as returned, e.g.,
22525 by `current-time'.
22527 When optional argument WITH-TIME is non-nil, return a timestamp
22528 object with a time part, i.e., with hours and minutes.
22530 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22531 return an active timestamp."
22532 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22533 (org-element-create 'timestamp
22534 (list :type (if inactive 'inactive 'active)
22535 :year-start year
22536 :month-start month
22537 :day-start day
22538 :hour-start (and with-time hour)
22539 :minute-start (and with-time minute)))))
22541 (defun org-timestamp-to-time (timestamp &optional end)
22542 "Convert TIMESTAMP object into an Emacs internal time value.
22543 Use end of date range or time range when END is non-nil.
22544 Otherwise, use its start."
22545 (apply #'encode-time
22546 (cons 0
22547 (mapcar
22548 (lambda (prop) (or (org-element-property prop timestamp) 0))
22549 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22550 '(:minute-start :hour-start :day-start :month-start
22551 :year-start))))))
22553 (defun org-timestamp-has-time-p (timestamp)
22554 "Non-nil when TIMESTAMP has a time specified."
22555 (org-element-property :hour-start timestamp))
22557 (defun org-timestamp-format (timestamp format &optional end utc)
22558 "Format a TIMESTAMP object into a string.
22560 FORMAT is a format specifier to be passed to
22561 `format-time-string'.
22563 When optional argument END is non-nil, use end of date-range or
22564 time-range, if possible.
22566 When optional argument UTC is non-nil, time is be expressed as
22567 Universal Time."
22568 (format-time-string format (org-timestamp-to-time timestamp end)
22569 (and utc t)))
22571 (defun org-timestamp-split-range (timestamp &optional end)
22572 "Extract a TIMESTAMP object from a date or time range.
22574 END, when non-nil, means extract the end of the range.
22575 Otherwise, extract its start.
22577 Return a new timestamp object."
22578 (let ((type (org-element-property :type timestamp)))
22579 (if (memq type '(active inactive diary)) timestamp
22580 (let ((split-ts (org-element-copy timestamp)))
22581 ;; Set new type.
22582 (org-element-put-property
22583 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22584 ;; Copy start properties over end properties if END is
22585 ;; non-nil. Otherwise, copy end properties over `start' ones.
22586 (let ((p-alist '((:minute-start . :minute-end)
22587 (:hour-start . :hour-end)
22588 (:day-start . :day-end)
22589 (:month-start . :month-end)
22590 (:year-start . :year-end))))
22591 (dolist (p-cell p-alist)
22592 (org-element-put-property
22593 split-ts
22594 (funcall (if end #'car #'cdr) p-cell)
22595 (org-element-property
22596 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22597 ;; Eventually refresh `:raw-value'.
22598 (org-element-put-property split-ts :raw-value nil)
22599 (org-element-put-property
22600 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22602 (defun org-timestamp-translate (timestamp &optional boundary)
22603 "Translate TIMESTAMP object to custom format.
22605 Format string is defined in `org-time-stamp-custom-formats',
22606 which see.
22608 When optional argument BOUNDARY is non-nil, it is either the
22609 symbol `start' or `end'. In this case, only translate the
22610 starting or ending part of TIMESTAMP if it is a date or time
22611 range. Otherwise, translate both parts.
22613 Return timestamp as-is if `org-display-custom-times' is nil or if
22614 it has a `diary' type."
22615 (let ((type (org-element-property :type timestamp)))
22616 (if (or (not org-display-custom-times) (eq type 'diary))
22617 (org-element-interpret-data timestamp)
22618 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22619 org-time-stamp-custom-formats)))
22620 (if (and (not boundary) (memq type '(active-range inactive-range)))
22621 (concat (org-timestamp-format timestamp fmt)
22622 "--"
22623 (org-timestamp-format timestamp fmt t))
22624 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22628 ;;; Other stuff.
22630 (defvar reftex-docstruct-symbol)
22631 (defvar org--rds)
22633 (defun org-reftex-citation ()
22634 "Use reftex-citation to insert a citation into the buffer.
22635 This looks for a line like
22637 #+BIBLIOGRAPHY: foo plain option:-d
22639 and derives from it that foo.bib is the bibliography file relevant
22640 for this document. It then installs the necessary environment for RefTeX
22641 to work in this buffer and calls `reftex-citation' to insert a citation
22642 into the buffer.
22644 Export of such citations to both LaTeX and HTML is handled by the contributed
22645 package ox-bibtex by Taru Karttunen."
22646 (interactive)
22647 (let ((reftex-docstruct-symbol 'org--rds)
22648 org--rds bib)
22649 (org-with-wide-buffer
22650 (let ((case-fold-search t)
22651 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22652 (if (not (save-excursion
22653 (or (re-search-forward re nil t)
22654 (re-search-backward re nil t))))
22655 (user-error "No bibliography defined in file")
22656 (setq bib (concat (match-string 1) ".bib")
22657 org--rds (list (list 'bib bib))))))
22658 (call-interactively 'reftex-citation)))
22660 ;;;; Functions extending outline functionality
22662 (defun org-beginning-of-line (&optional n)
22663 "Go to the beginning of the current visible line.
22665 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22666 tags on the first attempt, and only move to after the tags when
22667 the cursor is already beyond the end of the headline.
22669 With argument N not nil or 1, move forward N - 1 lines first."
22670 (interactive "^p")
22671 (let ((origin (point))
22672 (special (pcase org-special-ctrl-a/e
22673 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22674 deactivate-mark)
22675 ;; First move to a visible line.
22676 (if (bound-and-true-p visual-line-mode)
22677 (beginning-of-visual-line n)
22678 (move-beginning-of-line n)
22679 ;; `move-beginning-of-line' may leave point after invisible
22680 ;; characters if line starts with such of these (e.g., with
22681 ;; a link at column 0). Really move to the beginning of the
22682 ;; current visible line.
22683 (beginning-of-line))
22684 (cond
22685 ;; No special behavior. Point is already at the beginning of
22686 ;; a line, logical or visual.
22687 ((not special))
22688 ;; `beginning-of-visual-line' left point before logical beginning
22689 ;; of line: point is at the beginning of a visual line. Bail
22690 ;; out.
22691 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22692 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22693 ;; At a headline, special position is before the title, but
22694 ;; after any TODO keyword or priority cookie.
22695 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22696 (line-end-position)))
22697 (bol (point)))
22698 (if (eq special 'reversed)
22699 (when (and (= origin bol) (eq last-command this-command))
22700 (goto-char refpos))
22701 (when (or (> origin refpos) (= origin bol))
22702 (goto-char refpos)))))
22703 ((and (looking-at org-list-full-item-re)
22704 (memq (org-element-type (save-match-data (org-element-at-point)))
22705 '(item plain-list)))
22706 ;; Set special position at first white space character after
22707 ;; bullet, and check-box, if any.
22708 (let ((after-bullet
22709 (let ((box (match-end 3)))
22710 (cond ((not box) (match-end 1))
22711 ((eq (char-after box) ?\s) (1+ box))
22712 (t box)))))
22713 (if (eq special 'reversed)
22714 (when (and (= (point) origin) (eq last-command this-command))
22715 (goto-char after-bullet))
22716 (when (or (> origin after-bullet) (= (point) origin))
22717 (goto-char after-bullet)))))
22718 ;; No special context. Point is already at beginning of line.
22719 (t nil))))
22721 (defun org-end-of-line (&optional n)
22722 "Go to the end of the line, but before ellipsis, if any.
22724 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22725 tags on the first attempt, and only move to after the tags when
22726 the cursor is already beyond the end of the headline.
22728 With argument N not nil or 1, move forward N - 1 lines first."
22729 (interactive "^p")
22730 (let ((origin (point))
22731 (special (pcase org-special-ctrl-a/e
22732 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22733 deactivate-mark)
22734 ;; First move to a visible line.
22735 (if (bound-and-true-p visual-line-mode)
22736 (beginning-of-visual-line n)
22737 (move-beginning-of-line n))
22738 (cond
22739 ;; At a headline, with tags.
22740 ((and special
22741 (save-excursion
22742 (beginning-of-line)
22743 (let ((case-fold-search nil))
22744 (looking-at org-complex-heading-regexp)))
22745 (match-end 5))
22746 (let ((tags (save-excursion
22747 (goto-char (match-beginning 5))
22748 (skip-chars-backward " \t")
22749 (point)))
22750 (visual-end (and (bound-and-true-p visual-line-mode)
22751 (save-excursion
22752 (end-of-visual-line)
22753 (point)))))
22754 ;; If `end-of-visual-line' brings us before end of line or
22755 ;; even tags, i.e., the headline spans over multiple visual
22756 ;; lines, move there.
22757 (cond ((and visual-end
22758 (< visual-end tags)
22759 (<= origin visual-end))
22760 (goto-char visual-end))
22761 ((eq special 'reversed)
22762 (if (and (= origin (line-end-position))
22763 (eq this-command last-command))
22764 (goto-char tags)
22765 (end-of-line)))
22767 (if (or (< origin tags) (= origin (line-end-position)))
22768 (goto-char tags)
22769 (end-of-line))))))
22770 ((bound-and-true-p visual-line-mode)
22771 (let ((bol (line-beginning-position)))
22772 (end-of-visual-line)
22773 ;; If `end-of-visual-line' gets us past the ellipsis at the
22774 ;; end of a line, backtrack and use `end-of-line' instead.
22775 (when (/= bol (line-beginning-position))
22776 (goto-char bol)
22777 (end-of-line))))
22778 (t (end-of-line)))))
22780 (defun org-backward-sentence (&optional _arg)
22781 "Go to beginning of sentence, or beginning of table field.
22782 This will call `backward-sentence' or `org-table-beginning-of-field',
22783 depending on context."
22784 (interactive)
22785 (let* ((element (org-element-at-point))
22786 (contents-begin (org-element-property :contents-begin element))
22787 (table (org-element-lineage element '(table) t)))
22788 (if (and table
22789 (> (point) contents-begin)
22790 (<= (point) (org-element-property :contents-end table)))
22791 (call-interactively #'org-table-beginning-of-field)
22792 (save-restriction
22793 (when (and contents-begin
22794 (< (point-min) contents-begin)
22795 (> (point) contents-begin))
22796 (narrow-to-region contents-begin
22797 (org-element-property :contents-end element)))
22798 (call-interactively #'backward-sentence)))))
22800 (defun org-forward-sentence (&optional _arg)
22801 "Go to end of sentence, or end of table field.
22802 This will call `forward-sentence' or `org-table-end-of-field',
22803 depending on context."
22804 (interactive)
22805 (if (and (org-at-heading-p)
22806 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22807 (save-restriction
22808 (narrow-to-region (line-beginning-position) (line-end-position))
22809 (call-interactively #'forward-sentence))
22810 (let* ((element (org-element-at-point))
22811 (contents-end (org-element-property :contents-end element))
22812 (table (org-element-lineage element '(table) t)))
22813 (if (and table
22814 (>= (point) (org-element-property :contents-begin table))
22815 (< (point) contents-end))
22816 (call-interactively #'org-table-end-of-field)
22817 (save-restriction
22818 (when (and contents-end
22819 (> (point-max) contents-end)
22820 ;; Skip blank lines between elements.
22821 (< (org-element-property :end element)
22822 (save-excursion (goto-char contents-end)
22823 (skip-chars-forward " \r\t\n"))))
22824 (narrow-to-region (org-element-property :contents-begin element)
22825 contents-end))
22826 ;; End of heading is considered as the end of a sentence.
22827 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22828 (call-interactively #'forward-sentence)))))))
22830 (defun org-kill-line (&optional _arg)
22831 "Kill line, to tags or end of line."
22832 (interactive)
22833 (cond
22834 ((or (not org-special-ctrl-k)
22835 (bolp)
22836 (not (org-at-heading-p)))
22837 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22838 org-ctrl-k-protect-subtree
22839 (or (eq org-ctrl-k-protect-subtree 'error)
22840 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22841 (user-error "C-k aborted as it would kill a hidden subtree"))
22842 (call-interactively
22843 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22844 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
22845 (kill-region (point) (match-beginning 1))
22846 (org-set-tags nil t))
22847 (t (kill-region (point) (point-at-eol)))))
22849 (defun org-yank (&optional arg)
22850 "Yank. If the kill is a subtree, treat it specially.
22851 This command will look at the current kill and check if is a single
22852 subtree, or a series of subtrees[1]. If it passes the test, and if the
22853 cursor is at the beginning of a line or after the stars of a currently
22854 empty headline, then the yank is handled specially. How exactly depends
22855 on the value of the following variables.
22857 `org-yank-folded-subtrees'
22858 By default, this variable is non-nil, which results in
22859 subtree(s) being folded after insertion, except if doing so
22860 would swallow text after the yanked text.
22862 `org-yank-adjusted-subtrees'
22863 When non-nil (the default value is nil), the subtree will be
22864 promoted or demoted in order to fit into the local outline tree
22865 structure, which means that the level will be adjusted so that it
22866 becomes the smaller one of the two *visible* surrounding headings.
22868 Any prefix to this command will cause `yank' to be called directly with
22869 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22870 will just
22871 plainly yank the text as it is.
22873 \[1] The test checks if the first non-white line is a heading
22874 and if there are no other headings with fewer stars."
22875 (interactive "P")
22876 (org-yank-generic 'yank arg))
22878 (defun org-yank-generic (command arg)
22879 "Perform some yank-like command.
22881 This function implements the behavior described in the `org-yank'
22882 documentation. However, it has been generalized to work for any
22883 interactive command with similar behavior."
22885 ;; pretend to be command COMMAND
22886 (setq this-command command)
22888 (if arg
22889 (call-interactively command)
22891 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22892 (and (org-kill-is-subtree-p)
22893 (or (bolp)
22894 (and (looking-at "[ \t]*$")
22895 (string-match
22896 "\\`\\*+\\'"
22897 (buffer-substring (point-at-bol) (point)))))))
22898 swallowp)
22899 (cond
22900 ((and subtreep org-yank-folded-subtrees)
22901 (let ((beg (point))
22902 end)
22903 (if (and subtreep org-yank-adjusted-subtrees)
22904 (org-paste-subtree nil nil 'for-yank)
22905 (call-interactively command))
22907 (setq end (point))
22908 (goto-char beg)
22909 (when (and (bolp) subtreep
22910 (not (setq swallowp
22911 (org-yank-folding-would-swallow-text beg end))))
22912 (org-with-limited-levels
22913 (or (looking-at org-outline-regexp)
22914 (re-search-forward org-outline-regexp-bol end t))
22915 (while (and (< (point) end) (looking-at org-outline-regexp))
22916 (outline-hide-subtree)
22917 (org-cycle-show-empty-lines 'folded)
22918 (condition-case nil
22919 (outline-forward-same-level 1)
22920 (error (goto-char end))))))
22921 (when swallowp
22922 (message
22923 "Inserted text not folded because that would swallow text"))
22925 (goto-char end)
22926 (skip-chars-forward " \t\n\r")
22927 (beginning-of-line 1)
22928 (push-mark beg 'nomsg)))
22929 ((and subtreep org-yank-adjusted-subtrees)
22930 (let ((beg (point-at-bol)))
22931 (org-paste-subtree nil nil 'for-yank)
22932 (push-mark beg 'nomsg)))
22934 (call-interactively command))))))
22936 (defun org-yank-folding-would-swallow-text (beg end)
22937 "Would hide-subtree at BEG swallow any text after END?"
22938 (let (level)
22939 (org-with-limited-levels
22940 (save-excursion
22941 (goto-char beg)
22942 (when (or (looking-at org-outline-regexp)
22943 (re-search-forward org-outline-regexp-bol end t))
22944 (setq level (org-outline-level)))
22945 (goto-char end)
22946 (skip-chars-forward " \t\r\n\v\f")
22947 (not (or (eobp)
22948 (and (bolp) (looking-at-p org-outline-regexp)
22949 (<= (org-outline-level) level))))))))
22951 (defun org-back-to-heading (&optional invisible-ok)
22952 "Call `outline-back-to-heading', but provide a better error message."
22953 (condition-case nil
22954 (outline-back-to-heading invisible-ok)
22955 (error (error "Before first headline at position %d in buffer %s"
22956 (point) (current-buffer)))))
22958 (defun org-before-first-heading-p ()
22959 "Before first heading?"
22960 (save-excursion
22961 (end-of-line)
22962 (null (re-search-backward org-outline-regexp-bol nil t))))
22964 (defun org-at-heading-p (&optional ignored)
22965 (outline-on-heading-p t))
22967 (defun org-in-commented-heading-p (&optional no-inheritance)
22968 "Non-nil if point is under a commented heading.
22969 This function also checks ancestors of the current headline,
22970 unless optional argument NO-INHERITANCE is non-nil."
22971 (cond
22972 ((org-before-first-heading-p) nil)
22973 ((let ((headline (nth 4 (org-heading-components))))
22974 (and headline
22975 (let ((case-fold-search nil))
22976 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22977 headline)))))
22978 (no-inheritance nil)
22980 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22982 (defun org-at-comment-p nil
22983 "Is cursor in a commented line?"
22984 (save-excursion
22985 (save-match-data
22986 (beginning-of-line)
22987 (looking-at "^[ \t]*# "))))
22989 (defun org-at-drawer-p nil
22990 "Is cursor at a drawer keyword?"
22991 (save-excursion
22992 (move-beginning-of-line 1)
22993 (looking-at org-drawer-regexp)))
22995 (defun org-at-block-p nil
22996 "Is cursor at a block keyword?"
22997 (save-excursion
22998 (move-beginning-of-line 1)
22999 (looking-at org-block-regexp)))
23001 (defun org-point-at-end-of-empty-headline ()
23002 "If point is at the end of an empty headline, return t, else nil.
23003 If the heading only contains a TODO keyword, it is still still considered
23004 empty."
23005 (let ((case-fold-search nil))
23006 (and (looking-at "[ \t]*$")
23007 org-todo-line-regexp
23008 (save-excursion
23009 (beginning-of-line)
23010 (looking-at org-todo-line-regexp)
23011 (string= (match-string 3) "")))))
23013 (defun org-at-heading-or-item-p ()
23014 (or (org-at-heading-p) (org-at-item-p)))
23016 (defun org-at-target-p ()
23017 (or (org-in-regexp org-radio-target-regexp)
23018 (org-in-regexp org-target-regexp)))
23019 ;; Compatibility alias with Org versions < 7.8.03
23020 (defalias 'org-on-target-p 'org-at-target-p)
23022 (defun org-up-heading-all (arg)
23023 "Move to the heading line of which the present line is a subheading.
23024 This function considers both visible and invisible heading lines.
23025 With argument, move up ARG levels."
23026 (outline-up-heading arg t))
23028 (defun org-up-heading-safe ()
23029 "Move to the heading line of which the present line is a subheading.
23030 This version will not throw an error. It will return the level of the
23031 headline found, or nil if no higher level is found.
23033 Also, this function will be a lot faster than `outline-up-heading',
23034 because it relies on stars being the outline starters. This can really
23035 make a significant difference in outlines with very many siblings."
23036 (when (ignore-errors (org-back-to-heading t))
23037 (let ((level-up (1- (funcall outline-level))))
23038 (and (> level-up 0)
23039 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23040 (funcall outline-level)))))
23042 (defun org-first-sibling-p ()
23043 "Is this heading the first child of its parents?"
23044 (interactive)
23045 (let ((re org-outline-regexp-bol)
23046 level l)
23047 (unless (org-at-heading-p t)
23048 (user-error "Not at a heading"))
23049 (setq level (funcall outline-level))
23050 (save-excursion
23051 (if (not (re-search-backward re nil t))
23053 (setq l (funcall outline-level))
23054 (< l level)))))
23056 (defun org-goto-sibling (&optional previous)
23057 "Goto the next sibling, even if it is invisible.
23058 When PREVIOUS is set, go to the previous sibling instead. Returns t
23059 when a sibling was found. When none is found, return nil and don't
23060 move point."
23061 (let ((fun (if previous 're-search-backward 're-search-forward))
23062 (pos (point))
23063 (re org-outline-regexp-bol)
23064 level l)
23065 (when (ignore-errors (org-back-to-heading t))
23066 (setq level (funcall outline-level))
23067 (catch 'exit
23068 (or previous (forward-char 1))
23069 (while (funcall fun re nil t)
23070 (setq l (funcall outline-level))
23071 (when (< l level) (goto-char pos) (throw 'exit nil))
23072 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23073 (goto-char pos)
23074 nil))))
23076 (defun org-show-siblings ()
23077 "Show all siblings of the current headline."
23078 (save-excursion
23079 (while (org-goto-sibling) (org-flag-heading nil)))
23080 (save-excursion
23081 (while (org-goto-sibling 'previous)
23082 (org-flag-heading nil))))
23084 (defun org-goto-first-child ()
23085 "Goto the first child, even if it is invisible.
23086 Return t when a child was found. Otherwise don't move point and
23087 return nil."
23088 (let (level (pos (point)) (re org-outline-regexp-bol))
23089 (when (ignore-errors (org-back-to-heading t))
23090 (setq level (outline-level))
23091 (forward-char 1)
23092 (if (and (re-search-forward re nil t) (> (outline-level) level))
23093 (progn (goto-char (match-beginning 0)) t)
23094 (goto-char pos) nil))))
23096 (defun org-show-hidden-entry ()
23097 "Show an entry where even the heading is hidden."
23098 (save-excursion
23099 (org-show-entry)))
23101 (defun org-flag-heading (flag &optional entry)
23102 "Flag the current heading. FLAG non-nil means make invisible.
23103 When ENTRY is non-nil, show the entire entry."
23104 (save-excursion
23105 (org-back-to-heading t)
23106 ;; Check if we should show the entire entry
23107 (if (not entry)
23108 (org-flag-region
23109 (line-end-position 0) (line-end-position) flag 'outline)
23110 (org-show-entry)
23111 (save-excursion
23112 (and (outline-next-heading)
23113 (org-flag-heading nil))))))
23115 (defun org-get-next-sibling ()
23116 "Move to next heading of the same level, and return point.
23117 If there is no such heading, return nil.
23118 This is like outline-next-sibling, but invisible headings are ok."
23119 (let ((level (funcall outline-level)))
23120 (outline-next-heading)
23121 (while (and (not (eobp)) (> (funcall outline-level) level))
23122 (outline-next-heading))
23123 (unless (or (eobp) (< (funcall outline-level) level))
23124 (point))))
23126 (defun org-get-last-sibling ()
23127 "Move to previous heading of the same level, and return point.
23128 If there is no such heading, return nil."
23129 (let ((opoint (point))
23130 (level (funcall outline-level)))
23131 (outline-previous-heading)
23132 (when (and (/= (point) opoint) (outline-on-heading-p t))
23133 (while (and (> (funcall outline-level) level)
23134 (not (bobp)))
23135 (outline-previous-heading))
23136 (unless (< (funcall outline-level) level)
23137 (point)))))
23139 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23140 "Goto to the end of a subtree."
23141 ;; This contains an exact copy of the original function, but it uses
23142 ;; `org-back-to-heading', to make it work also in invisible
23143 ;; trees. And is uses an invisible-ok argument.
23144 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23145 ;; Furthermore, when used inside Org, finding the end of a large subtree
23146 ;; with many children and grandchildren etc, this can be much faster
23147 ;; than the outline version.
23148 (org-back-to-heading invisible-ok)
23149 (let ((first t)
23150 (level (funcall outline-level)))
23151 (if (and (derived-mode-p 'org-mode) (< level 1000))
23152 ;; A true heading (not a plain list item), in Org
23153 ;; This means we can easily find the end by looking
23154 ;; only for the right number of stars. Using a regexp to do
23155 ;; this is so much faster than using a Lisp loop.
23156 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23157 (forward-char 1)
23158 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23159 ;; something else, do it the slow way
23160 (while (and (not (eobp))
23161 (or first (> (funcall outline-level) level)))
23162 (setq first nil)
23163 (outline-next-heading)))
23164 (unless to-heading
23165 (when (memq (preceding-char) '(?\n ?\^M))
23166 ;; Go to end of line before heading
23167 (forward-char -1)
23168 (when (memq (preceding-char) '(?\n ?\^M))
23169 ;; leave blank line before heading
23170 (forward-char -1)))))
23171 (point))
23173 (defun org-end-of-meta-data (&optional full)
23174 "Skip planning line and properties drawer in current entry.
23175 When optional argument FULL is non-nil, also skip empty lines,
23176 clocking lines and regular drawers at the beginning of the
23177 entry."
23178 (org-back-to-heading t)
23179 (forward-line)
23180 (when (looking-at-p org-planning-line-re) (forward-line))
23181 (when (looking-at org-property-drawer-re)
23182 (goto-char (match-end 0))
23183 (forward-line))
23184 (when (and full (not (org-at-heading-p)))
23185 (catch 'exit
23186 (let ((end (save-excursion (outline-next-heading) (point)))
23187 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23188 (while (not (eobp))
23189 (cond ((looking-at-p org-drawer-regexp)
23190 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23191 (forward-line)
23192 (throw 'exit t)))
23193 ((looking-at-p re) (forward-line))
23194 (t (throw 'exit t))))))))
23196 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23197 "Move forward to the ARG'th subheading at same level as this one.
23198 Stop at the first and last subheadings of a superior heading.
23199 Normally this only looks at visible headings, but when INVISIBLE-OK is
23200 non-nil it will also look at invisible ones."
23201 (interactive "p")
23202 (let ((backward? (and arg (< arg 0))))
23203 (if (org-before-first-heading-p)
23204 (if backward? (goto-char (point-min)) (outline-next-heading))
23205 (org-back-to-heading invisible-ok)
23206 (unless backward? (end-of-line)) ;do not match current headline
23207 (let ((level (- (match-end 0) (match-beginning 0) 1))
23208 (f (if backward? #'re-search-backward #'re-search-forward))
23209 (count (if arg (abs arg) 1))
23210 (result (point)))
23211 (while (and (> count 0)
23212 (funcall f org-outline-regexp-bol nil 'move))
23213 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23214 (cond ((< l level) (setq count 0))
23215 ((and (= l level)
23216 (or invisible-ok
23217 (not (org-invisible-p
23218 (line-beginning-position)))))
23219 (cl-decf count)
23220 (when (= l level) (setq result (point)))))))
23221 (goto-char result))
23222 (beginning-of-line))))
23224 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23225 "Move backward to the ARG'th subheading at same level as this one.
23226 Stop at the first and last subheadings of a superior heading."
23227 (interactive "p")
23228 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23230 (defun org-next-visible-heading (arg)
23231 "Move to the next visible heading.
23233 This function wraps `outline-next-visible-heading' with
23234 `org-with-limited-levels' in order to skip over inline tasks and
23235 respect customization of `org-odd-levels-only'."
23236 (interactive "p")
23237 (org-with-limited-levels
23238 (outline-next-visible-heading arg)))
23240 (defun org-previous-visible-heading (arg)
23241 "Move to the previous visible heading.
23243 This function wraps `outline-previous-visible-heading' with
23244 `org-with-limited-levels' in order to skip over inline tasks and
23245 respect customization of `org-odd-levels-only'."
23246 (interactive "p")
23247 (org-with-limited-levels
23248 (outline-previous-visible-heading arg)))
23250 (defun org-forward-paragraph ()
23251 "Move forward to beginning of next paragraph or equivalent.
23253 The function moves point to the beginning of the next visible
23254 structural element, which can be a paragraph, a table, a list
23255 item, etc. It also provides some special moves for convenience:
23257 - On an affiliated keyword, jump to the beginning of the
23258 relative element.
23259 - On an item or a footnote definition, move to the second
23260 element inside, if any.
23261 - On a table or a property drawer, jump after it.
23262 - On a verse or source block, stop after blank lines."
23263 (interactive)
23264 (unless (eobp)
23265 (let* ((deactivate-mark nil)
23266 (element (org-element-at-point))
23267 (type (org-element-type element))
23268 (post-affiliated (org-element-property :post-affiliated element))
23269 (contents-begin (org-element-property :contents-begin element))
23270 (contents-end (org-element-property :contents-end element))
23271 (end (let ((end (org-element-property :end element)) (parent element))
23272 (while (and (setq parent (org-element-property :parent parent))
23273 (= (org-element-property :contents-end parent) end))
23274 (setq end (org-element-property :end parent)))
23275 end)))
23276 (cond ((not element)
23277 (skip-chars-forward " \r\t\n")
23278 (or (eobp) (beginning-of-line)))
23279 ;; On affiliated keywords, move to element's beginning.
23280 ((< (point) post-affiliated)
23281 (goto-char post-affiliated))
23282 ;; At a table row, move to the end of the table. Similarly,
23283 ;; at a node property, move to the end of the property
23284 ;; drawer.
23285 ((memq type '(node-property table-row))
23286 (goto-char (org-element-property
23287 :end (org-element-property :parent element))))
23288 ((memq type '(property-drawer table)) (goto-char end))
23289 ;; Consider blank lines as separators in verse and source
23290 ;; blocks to ease editing.
23291 ((memq type '(src-block verse-block))
23292 (when (eq type 'src-block)
23293 (setq contents-end
23294 (save-excursion (goto-char end)
23295 (skip-chars-backward " \r\t\n")
23296 (line-beginning-position))))
23297 (beginning-of-line)
23298 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23299 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23300 (goto-char end)
23301 (skip-chars-forward " \r\t\n")
23302 (if (= (point) contents-end) (goto-char end)
23303 (beginning-of-line))))
23304 ;; With no contents, just skip element.
23305 ((not contents-begin) (goto-char end))
23306 ;; If contents are invisible, skip the element altogether.
23307 ((org-invisible-p (line-end-position))
23308 (cl-case type
23309 (headline
23310 (org-with-limited-levels (outline-next-visible-heading 1)))
23311 ;; At a plain list, make sure we move to the next item
23312 ;; instead of skipping the whole list.
23313 (plain-list (forward-char)
23314 (org-forward-paragraph))
23315 (otherwise (goto-char end))))
23316 ((>= (point) contents-end) (goto-char end))
23317 ((>= (point) contents-begin)
23318 ;; This can only happen on paragraphs and plain lists.
23319 (cl-case type
23320 (paragraph (goto-char end))
23321 ;; At a plain list, try to move to second element in
23322 ;; first item, if possible.
23323 (plain-list (end-of-line)
23324 (org-forward-paragraph))))
23325 ;; When contents start on the middle of a line (e.g. in
23326 ;; items and footnote definitions), try to reach first
23327 ;; element starting after current line.
23328 ((> (line-end-position) contents-begin)
23329 (end-of-line)
23330 (org-forward-paragraph))
23331 (t (goto-char contents-begin))))))
23333 (defun org-backward-paragraph ()
23334 "Move backward to start of previous paragraph or equivalent.
23336 The function moves point to the beginning of the current
23337 structural element, which can be a paragraph, a table, a list
23338 item, etc., or to the beginning of the previous visible one if
23339 point is already there. It also provides some special moves for
23340 convenience:
23342 - On an affiliated keyword, jump to the first one.
23343 - On a table or a property drawer, move to its beginning.
23344 - On comment, example, export, src and verse blocks, stop
23345 before blank lines."
23346 (interactive)
23347 (unless (bobp)
23348 (let* ((deactivate-mark nil)
23349 (element (org-element-at-point))
23350 (type (org-element-type element))
23351 (contents-end (org-element-property :contents-end element))
23352 (post-affiliated (org-element-property :post-affiliated element))
23353 (begin (org-element-property :begin element))
23354 (special? ;blocks handled specially
23355 (memq type '(comment-block example-block export-block src-block
23356 verse-block)))
23357 (contents-begin
23358 (if special?
23359 ;; These types have no proper contents. Fake line
23360 ;; below the block opening line as contents beginning.
23361 (save-excursion (goto-char begin) (line-beginning-position 2))
23362 (org-element-property :contents-begin element))))
23363 (cond
23364 ((not element) (goto-char (point-min)))
23365 ((= (point) begin)
23366 (backward-char)
23367 (org-backward-paragraph))
23368 ((<= (point) post-affiliated) (goto-char begin))
23369 ;; Special behavior: on a table or a property drawer, move to
23370 ;; its beginning.
23371 ((memq type '(node-property table-row))
23372 (goto-char (org-element-property
23373 :post-affiliated (org-element-property :parent element))))
23374 (special?
23375 (if (<= (point) contents-begin) (goto-char post-affiliated)
23376 ;; Inside a verse block, see blank lines as paragraph
23377 ;; separators.
23378 (let ((origin (point)))
23379 (skip-chars-backward " \r\t\n" contents-begin)
23380 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23381 (skip-chars-forward " \r\t\n" origin)
23382 (if (= (point) origin) (goto-char contents-begin)
23383 (beginning-of-line))))))
23384 ((eq type 'paragraph) (goto-char contents-begin)
23385 ;; When at first paragraph in an item or a footnote definition,
23386 ;; move directly to beginning of line.
23387 (let ((parent-contents
23388 (org-element-property
23389 :contents-begin (org-element-property :parent element))))
23390 (when (and parent-contents (= parent-contents contents-begin))
23391 (beginning-of-line))))
23392 ;; At the end of a greater element, move to the beginning of
23393 ;; the last element within.
23394 ((and contents-end (>= (point) contents-end))
23395 (goto-char (1- contents-end))
23396 (org-backward-paragraph))
23397 (t (goto-char (or post-affiliated begin))))
23398 ;; Ensure we never leave point invisible.
23399 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23401 (defun org-forward-element ()
23402 "Move forward by one element.
23403 Move to the next element at the same level, when possible."
23404 (interactive)
23405 (cond ((eobp) (user-error "Cannot move further down"))
23406 ((org-with-limited-levels (org-at-heading-p))
23407 (let ((origin (point)))
23408 (goto-char (org-end-of-subtree nil t))
23409 (unless (org-with-limited-levels (org-at-heading-p))
23410 (goto-char origin)
23411 (user-error "Cannot move further down"))))
23413 (let* ((elem (org-element-at-point))
23414 (end (org-element-property :end elem))
23415 (parent (org-element-property :parent elem)))
23416 (cond ((and parent (= (org-element-property :contents-end parent) end))
23417 (goto-char (org-element-property :end parent)))
23418 ((integer-or-marker-p end) (goto-char end))
23419 (t (message "No element at point")))))))
23421 (defun org-backward-element ()
23422 "Move backward by one element.
23423 Move to the previous element at the same level, when possible."
23424 (interactive)
23425 (cond ((bobp) (user-error "Cannot move further up"))
23426 ((org-with-limited-levels (org-at-heading-p))
23427 ;; At a headline, move to the previous one, if any, or stay
23428 ;; here.
23429 (let ((origin (point)))
23430 (org-with-limited-levels (org-backward-heading-same-level 1))
23431 ;; When current headline has no sibling above, move to its
23432 ;; parent.
23433 (when (= (point) origin)
23434 (or (org-with-limited-levels (org-up-heading-safe))
23435 (progn (goto-char origin)
23436 (user-error "Cannot move further up"))))))
23438 (let* ((elem (org-element-at-point))
23439 (beg (org-element-property :begin elem)))
23440 (cond
23441 ;; Move to beginning of current element if point isn't
23442 ;; there already.
23443 ((null beg) (message "No element at point"))
23444 ((/= (point) beg) (goto-char beg))
23445 (t (goto-char beg)
23446 (skip-chars-backward " \r\t\n")
23447 (unless (bobp)
23448 (let ((prev (org-element-at-point)))
23449 (goto-char (org-element-property :begin prev))
23450 (while (and (setq prev (org-element-property :parent prev))
23451 (<= (org-element-property :end prev) beg))
23452 (goto-char (org-element-property :begin prev)))))))))))
23454 (defun org-up-element ()
23455 "Move to upper element."
23456 (interactive)
23457 (if (org-with-limited-levels (org-at-heading-p))
23458 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23459 (let* ((elem (org-element-at-point))
23460 (parent (org-element-property :parent elem)))
23461 (if parent (goto-char (org-element-property :begin parent))
23462 (if (org-with-limited-levels (org-before-first-heading-p))
23463 (user-error "No surrounding element")
23464 (org-with-limited-levels (org-back-to-heading)))))))
23466 (defun org-down-element ()
23467 "Move to inner element."
23468 (interactive)
23469 (let ((element (org-element-at-point)))
23470 (cond
23471 ((memq (org-element-type element) '(plain-list table))
23472 (goto-char (org-element-property :contents-begin element))
23473 (forward-char))
23474 ((memq (org-element-type element) org-element-greater-elements)
23475 ;; If contents are hidden, first disclose them.
23476 (when (org-invisible-p (line-end-position)) (org-cycle))
23477 (goto-char (or (org-element-property :contents-begin element)
23478 (user-error "No content for this element"))))
23479 (t (user-error "No inner element")))))
23481 (defun org-drag-element-backward ()
23482 "Move backward element at point."
23483 (interactive)
23484 (let ((elem (or (org-element-at-point)
23485 (user-error "No element at point"))))
23486 (if (eq (org-element-type elem) 'headline)
23487 ;; Preserve point when moving a whole tree, even if point was
23488 ;; on blank lines below the headline.
23489 (let ((offset (skip-chars-backward " \t\n")))
23490 (unwind-protect (org-move-subtree-up)
23491 (forward-char (- offset))))
23492 (let ((prev-elem
23493 (save-excursion
23494 (goto-char (org-element-property :begin elem))
23495 (skip-chars-backward " \r\t\n")
23496 (unless (bobp)
23497 (let* ((beg (org-element-property :begin elem))
23498 (prev (org-element-at-point))
23499 (up prev))
23500 (while (and (setq up (org-element-property :parent up))
23501 (<= (org-element-property :end up) beg))
23502 (setq prev up))
23503 prev)))))
23504 ;; Error out if no previous element or previous element is
23505 ;; a parent of the current one.
23506 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23507 (user-error "Cannot drag element backward")
23508 (let ((pos (point)))
23509 (org-element-swap-A-B prev-elem elem)
23510 (goto-char (+ (org-element-property :begin prev-elem)
23511 (- pos (org-element-property :begin elem))))))))))
23513 (defun org-drag-element-forward ()
23514 "Move forward element at point."
23515 (interactive)
23516 (let* ((pos (point))
23517 (elem (or (org-element-at-point)
23518 (user-error "No element at point"))))
23519 (when (= (point-max) (org-element-property :end elem))
23520 (user-error "Cannot drag element forward"))
23521 (goto-char (org-element-property :end elem))
23522 (let ((next-elem (org-element-at-point)))
23523 (when (or (org-element-nested-p elem next-elem)
23524 (and (eq (org-element-type next-elem) 'headline)
23525 (not (eq (org-element-type elem) 'headline))))
23526 (goto-char pos)
23527 (user-error "Cannot drag element forward"))
23528 ;; Compute new position of point: it's shifted by NEXT-ELEM
23529 ;; body's length (without final blanks) and by the length of
23530 ;; blanks between ELEM and NEXT-ELEM.
23531 (let ((size-next (- (save-excursion
23532 (goto-char (org-element-property :end next-elem))
23533 (skip-chars-backward " \r\t\n")
23534 (forward-line)
23535 ;; Small correction if buffer doesn't end
23536 ;; with a newline character.
23537 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23538 (org-element-property :begin next-elem)))
23539 (size-blank (- (org-element-property :end elem)
23540 (save-excursion
23541 (goto-char (org-element-property :end elem))
23542 (skip-chars-backward " \r\t\n")
23543 (forward-line)
23544 (point)))))
23545 (org-element-swap-A-B elem next-elem)
23546 (goto-char (+ pos size-next size-blank))))))
23548 (defun org-drag-line-forward (arg)
23549 "Drag the line at point ARG lines forward."
23550 (interactive "p")
23551 (dotimes (_ (abs arg))
23552 (let ((c (current-column)))
23553 (if (< 0 arg)
23554 (progn
23555 (beginning-of-line 2)
23556 (transpose-lines 1)
23557 (beginning-of-line 0))
23558 (transpose-lines 1)
23559 (beginning-of-line -1))
23560 (org-move-to-column c))))
23562 (defun org-drag-line-backward (arg)
23563 "Drag the line at point ARG lines backward."
23564 (interactive "p")
23565 (org-drag-line-forward (- arg)))
23567 (defun org-mark-element ()
23568 "Put point at beginning of this element, mark at end.
23570 Interactively, if this command is repeated or (in Transient Mark
23571 mode) if the mark is active, it marks the next element after the
23572 ones already marked."
23573 (interactive)
23574 (let (deactivate-mark)
23575 (if (and (called-interactively-p 'any)
23576 (or (and (eq last-command this-command) (mark t))
23577 (and transient-mark-mode mark-active)))
23578 (set-mark
23579 (save-excursion
23580 (goto-char (mark))
23581 (goto-char (org-element-property :end (org-element-at-point)))))
23582 (let ((element (org-element-at-point)))
23583 (end-of-line)
23584 (push-mark (org-element-property :end element) t t)
23585 (goto-char (org-element-property :begin element))))))
23587 (defun org-narrow-to-element ()
23588 "Narrow buffer to current element."
23589 (interactive)
23590 (let ((elem (org-element-at-point)))
23591 (cond
23592 ((eq (car elem) 'headline)
23593 (narrow-to-region
23594 (org-element-property :begin elem)
23595 (org-element-property :end elem)))
23596 ((memq (car elem) org-element-greater-elements)
23597 (narrow-to-region
23598 (org-element-property :contents-begin elem)
23599 (org-element-property :contents-end elem)))
23601 (narrow-to-region
23602 (org-element-property :begin elem)
23603 (org-element-property :end elem))))))
23605 (defun org-transpose-element ()
23606 "Transpose current and previous elements, keeping blank lines between.
23607 Point is moved after both elements."
23608 (interactive)
23609 (org-skip-whitespace)
23610 (let ((end (org-element-property :end (org-element-at-point))))
23611 (org-drag-element-backward)
23612 (goto-char end)))
23614 (defun org-unindent-buffer ()
23615 "Un-indent the visible part of the buffer.
23616 Relative indentation (between items, inside blocks, etc.) isn't
23617 modified."
23618 (interactive)
23619 (unless (eq major-mode 'org-mode)
23620 (user-error "Cannot un-indent a buffer not in Org mode"))
23621 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23622 (unindent-tree
23623 (lambda (contents)
23624 (dolist (element (reverse contents))
23625 (if (memq (org-element-type element) '(headline section))
23626 (funcall unindent-tree (org-element-contents element))
23627 (save-excursion
23628 (save-restriction
23629 (narrow-to-region
23630 (org-element-property :begin element)
23631 (org-element-property :end element))
23632 (org-do-remove-indentation))))))))
23633 (funcall unindent-tree (org-element-contents parse-tree))))
23635 (defun org-make-options-regexp (kwds &optional extra)
23636 "Make a regular expression for keyword lines.
23637 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23638 when non-nil, is a regexp matching keywords names."
23639 (concat "^[ \t]*#\\+\\("
23640 (regexp-opt kwds)
23641 (and extra (concat (and kwds "\\|") extra))
23642 "\\):[ \t]*\\(.*\\)"))
23645 ;;; Finish up
23647 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23648 (lambda () (add-hook 'change-major-mode-hook
23649 'org-show-all 'append 'local)))
23651 (provide 'org)
23653 (run-hooks 'org-load-hook)
23655 ;;; org.el ends here