Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob1e0e57e26ed646f4d823aa25625c3458683923af
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 isearch-no-upper-case-p "isearch" (string regexp-flag))
112 (declare-function org-add-archive-files "org-archive" (files))
113 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
114 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
115 (declare-function org-agenda-redo "org-agenda" (&optional all))
116 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
117 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
118 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
121 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
122 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
123 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
125 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
126 (declare-function org-clock-update-time-maybe "org-clock" ())
127 (declare-function org-clocking-buffer "org-clock" ())
128 (declare-function org-clocktable-shift "org-clock" (dir n))
129 (declare-function
130 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
131 (declare-function org-element-at-point "org-element" ())
132 (declare-function org-element-cache-refresh "org-element" (pos))
133 (declare-function org-element-cache-reset "org-element" (&optional all))
134 (declare-function org-element-contents "org-element" (element))
135 (declare-function org-element-context "org-element" (&optional element))
136 (declare-function org-element-copy "org-element" (datum))
137 (declare-function org-element-interpret-data "org-element" (data))
138 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
139 (declare-function org-element-link-parser "org-element" ())
140 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
141 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
142 (declare-function org-element-property "org-element" (property element))
143 (declare-function org-element-put-property "org-element" (element property value))
144 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-update-syntax "org-element" ())
147 (declare-function org-id-find-id-file "org-id" (id))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
150 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
151 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
152 (declare-function org-plot/gnuplot "org-plot" (&optional params))
153 (declare-function org-table-align "org-table" ())
154 (declare-function org-table-begin "org-table" (&optional table-type))
155 (declare-function org-table-beginning-of-field "org-table" (&optional n))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
158 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
159 (declare-function org-table-cut-region "org-table" (beg end))
160 (declare-function org-table-edit-field "org-table" (arg))
161 (declare-function org-table-end "org-table" (&optional table-type))
162 (declare-function org-table-end-of-field "org-table" (&optional n))
163 (declare-function org-table-insert-row "org-table" (&optional arg))
164 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
165 (declare-function org-table-maybe-eval-formula "org-table" ())
166 (declare-function org-table-maybe-recalculate-line "org-table" ())
167 (declare-function org-table-next-row "org-table" ())
168 (declare-function org-table-paste-rectangle "org-table" ())
169 (declare-function org-table-recalculate "org-table" (&optional all noalign))
170 (declare-function
171 org-table-sort-lines "org-table"
172 (&optional with-case sorting-type getkey-func compare-func interactive?))
173 (declare-function org-table-shrink "org-table" (&optional begin end))
174 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
175 (declare-function org-table-wrap-region "org-table" (arg))
176 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
177 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
178 (declare-function orgtbl-mode "org-table" (&optional arg))
179 (declare-function org-export-get-backend "ox" (name))
180 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
181 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
183 (defvar ffap-url-regexp)
184 (defvar org-element-paragraph-separate)
186 ;; load languages based on value of `org-babel-load-languages'
187 (defvar org-babel-load-languages)
189 ;;;###autoload
190 (defun org-babel-do-load-languages (sym value)
191 "Load the languages defined in `org-babel-load-languages'."
192 (set-default sym value)
193 (dolist (pair org-babel-load-languages)
194 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
195 (if active
196 (require (intern (concat "ob-" lang)))
197 (funcall 'fmakunbound
198 (intern (concat "org-babel-execute:" lang)))
199 (funcall 'fmakunbound
200 (intern (concat "org-babel-expand-body:" lang)))))))
202 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
203 ;;;###autoload
204 (defun org-babel-load-file (file &optional compile)
205 "Load Emacs Lisp source code blocks in the Org FILE.
206 This function exports the source code using `org-babel-tangle'
207 and then loads the resulting file using `load-file'. With prefix
208 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
209 file to byte-code before it is loaded."
210 (interactive "fFile to load: \nP")
211 (let* ((age (lambda (file)
212 (float-time
213 (time-subtract (current-time)
214 (nth 5 (or (file-attributes (file-truename file))
215 (file-attributes file)))))))
216 (base-name (file-name-sans-extension file))
217 (exported-file (concat base-name ".el")))
218 ;; tangle if the Org file is newer than the elisp file
219 (unless (and (file-exists-p exported-file)
220 (> (funcall age file) (funcall age exported-file)))
221 ;; Tangle-file traversal returns reversed list of tangled files
222 ;; and we want to evaluate the first target.
223 (setq exported-file
224 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
225 (message "%s %s"
226 (if compile
227 (progn (byte-compile-file exported-file 'load)
228 "Compiled and loaded")
229 (progn (load-file exported-file) "Loaded"))
230 exported-file)))
232 (defcustom org-babel-load-languages '((emacs-lisp . t))
233 "Languages which can be evaluated in Org buffers.
234 This list can be used to load support for any of the languages
235 below, note that each language will depend on a different set of
236 system executables and/or Emacs modes. When a language is
237 \"loaded\", then code blocks in that language can be evaluated
238 with `org-babel-execute-src-block' bound by default to C-c
239 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
240 be set to remove code block evaluation from the C-c C-c
241 keybinding. By default only Emacs Lisp (which has no
242 requirements) is loaded."
243 :group 'org-babel
244 :set 'org-babel-do-load-languages
245 :version "24.1"
246 :type '(alist :tag "Babel Languages"
247 :key-type
248 (choice
249 (const :tag "Awk" awk)
250 (const :tag "C" C)
251 (const :tag "R" R)
252 (const :tag "Asymptote" asymptote)
253 (const :tag "Calc" calc)
254 (const :tag "Clojure" clojure)
255 (const :tag "CSS" css)
256 (const :tag "Ditaa" ditaa)
257 (const :tag "Dot" dot)
258 (const :tag "Ebnf2ps" ebnf2ps)
259 (const :tag "Emacs Lisp" emacs-lisp)
260 (const :tag "Forth" forth)
261 (const :tag "Fortran" fortran)
262 (const :tag "Gnuplot" gnuplot)
263 (const :tag "Haskell" haskell)
264 (const :tag "hledger" hledger)
265 (const :tag "IO" io)
266 (const :tag "J" J)
267 (const :tag "Java" java)
268 (const :tag "Javascript" js)
269 (const :tag "LaTeX" latex)
270 (const :tag "Ledger" ledger)
271 (const :tag "Lilypond" lilypond)
272 (const :tag "Lisp" lisp)
273 (const :tag "Makefile" makefile)
274 (const :tag "Maxima" maxima)
275 (const :tag "Matlab" matlab)
276 (const :tag "Mscgen" mscgen)
277 (const :tag "Ocaml" ocaml)
278 (const :tag "Octave" octave)
279 (const :tag "Org" org)
280 (const :tag "Perl" perl)
281 (const :tag "Pico Lisp" picolisp)
282 (const :tag "PlantUML" plantuml)
283 (const :tag "Python" python)
284 (const :tag "Ruby" ruby)
285 (const :tag "Sass" sass)
286 (const :tag "Scala" scala)
287 (const :tag "Scheme" scheme)
288 (const :tag "Screen" screen)
289 (const :tag "Shell Script" shell)
290 (const :tag "Shen" shen)
291 (const :tag "Sql" sql)
292 (const :tag "Sqlite" sqlite)
293 (const :tag "Stan" stan)
294 (const :tag "Vala" vala))
295 :value-type (boolean :tag "Activate" :value t)))
297 ;;;; Customization variables
298 (defcustom org-clone-delete-id nil
299 "Remove ID property of clones of a subtree.
300 When non-nil, clones of a subtree don't inherit the ID property.
301 Otherwise they inherit the ID property with a new unique
302 identifier."
303 :type 'boolean
304 :version "24.1"
305 :group 'org-id)
307 ;;; Version
308 (org-check-version)
310 ;;;###autoload
311 (defun org-version (&optional here full message)
312 "Show the Org version.
313 Interactively, or when MESSAGE is non-nil, show it in echo area.
314 With prefix argument, or when HERE is non-nil, insert it at point.
315 In non-interactive uses, a reduced version string is output unless
316 FULL is given."
317 (interactive (list current-prefix-arg t (not current-prefix-arg)))
318 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
319 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
320 (load-suffixes (list ".el"))
321 (org-install-dir
322 (ignore-errors (org-find-library-dir "org-loaddefs"))))
323 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
324 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
325 (let* ((load-suffixes save-load-suffixes)
326 (release (org-release))
327 (git-version (org-git-version))
328 (version (format "Org mode version %s (%s @ %s)"
329 release
330 git-version
331 (if org-install-dir
332 (if (string= org-dir org-install-dir)
333 org-install-dir
334 (concat "mixed installation! "
335 org-install-dir
336 " and "
337 org-dir))
338 "org-loaddefs.el can not be found!")))
339 (version1 (if full version release)))
340 (when here (insert version1))
341 (when message (message "%s" version1))
342 version1)))
344 (defconst org-version (org-version))
347 ;;; Syntax Constants
349 ;;;; Block
351 (defconst org-block-regexp
352 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
353 "Regular expression for hiding blocks.")
355 (defconst org-dblock-start-re
356 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
357 "Matches the start line of a dynamic block, with parameters.")
359 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
360 "Matches the end of a dynamic block.")
362 ;;;; Clock and Planning
364 (defconst org-clock-string "CLOCK:"
365 "String used as prefix for timestamps clocking work hours on an item.")
367 (defvar org-closed-string "CLOSED:"
368 "String used as the prefix for timestamps logging closing a TODO entry.")
370 (defvar org-deadline-string "DEADLINE:"
371 "String to mark deadline entries.
372 \\<org-mode-map>
373 A deadline is this string, followed by a time stamp. It must be
374 a word, terminated by a colon. You can insert a schedule keyword
375 and a timestamp with `\\[org-deadline]'.")
377 (defvar org-scheduled-string "SCHEDULED:"
378 "String to mark scheduled TODO entries.
379 \\<org-mode-map>
380 A schedule is this string, followed by a time stamp. It must be
381 a word, terminated by a colon. You can insert a schedule keyword
382 and a timestamp with `\\[org-schedule]'.")
384 (defconst org-ds-keyword-length
385 (+ 2
386 (apply #'max
387 (mapcar #'length
388 (list org-deadline-string org-scheduled-string
389 org-clock-string org-closed-string))))
390 "Maximum length of the DEADLINE and SCHEDULED keywords.")
392 (defconst org-planning-line-re
393 (concat "^[ \t]*"
394 (regexp-opt
395 (list org-closed-string org-deadline-string org-scheduled-string)
397 "Matches a line with planning info.
398 Matched keyword is in group 1.")
400 (defconst org-clock-line-re
401 (concat "^[ \t]*" org-clock-string)
402 "Matches a line with clock info.")
404 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
405 "Matches the DEADLINE keyword.")
407 (defconst org-deadline-time-regexp
408 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
409 "Matches the DEADLINE keyword together with a time stamp.")
411 (defconst org-deadline-time-hour-regexp
412 (concat "\\<" org-deadline-string
413 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
414 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
416 (defconst org-deadline-line-regexp
417 (concat "\\<\\(" org-deadline-string "\\).*")
418 "Matches the DEADLINE keyword and the rest of the line.")
420 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
421 "Matches the SCHEDULED keyword.")
423 (defconst org-scheduled-time-regexp
424 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
425 "Matches the SCHEDULED keyword together with a time stamp.")
427 (defconst org-scheduled-time-hour-regexp
428 (concat "\\<" org-scheduled-string
429 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
430 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
432 (defconst org-closed-time-regexp
433 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
434 "Matches the CLOSED keyword together with a time stamp.")
436 (defconst org-keyword-time-regexp
437 (concat "\\<"
438 (regexp-opt
439 (list org-scheduled-string org-deadline-string org-closed-string
440 org-clock-string)
442 " *[[<]\\([^]>]+\\)[]>]")
443 "Matches any of the 4 keywords, together with the time stamp.")
445 (defconst org-keyword-time-not-clock-regexp
446 (concat
447 "\\<"
448 (regexp-opt
449 (list org-scheduled-string org-deadline-string org-closed-string) t)
450 " *[[<]\\([^]>]+\\)[]>]")
451 "Matches any of the 3 keywords, together with the time stamp.")
453 (defconst org-maybe-keyword-time-regexp
454 (concat "\\(\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string
457 org-clock-string)
459 "\\)?"
460 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
461 "\\|"
462 "<%%([^\r\n>]*>\\)")
463 "Matches a timestamp, possibly preceded by a keyword.")
465 (defconst org-all-time-keywords
466 (mapcar (lambda (w) (substring w 0 -1))
467 (list org-scheduled-string org-deadline-string
468 org-clock-string org-closed-string))
469 "List of time keywords.")
471 ;;;; Drawer
473 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
474 "Matches first or last line of a hidden block.
475 Group 1 contains drawer's name or \"END\".")
477 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
478 "Regular expression matching the first line of a property drawer.")
480 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
481 "Regular expression matching the last line of a property drawer.")
483 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
484 "Regular expression matching the first line of a clock drawer.")
486 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
487 "Regular expression matching the last line of a clock drawer.")
489 (defconst org-property-drawer-re
490 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
491 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
492 "[ \t]*:END:[ \t]*$")
493 "Matches an entire property drawer.")
495 (defconst org-clock-drawer-re
496 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
497 org-clock-drawer-end-re "\\)\n?")
498 "Matches an entire clock drawer.")
500 ;;;; Headline
502 (defconst org-heading-keyword-regexp-format
503 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
504 "Printf format for a regexp matching a headline with some keyword.
505 This regexp will match the headline of any node which has the
506 exact keyword that is put into the format. The keyword isn't in
507 any group by default, but the stars and the body are.")
509 (defconst org-heading-keyword-maybe-regexp-format
510 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
511 "Printf format for a regexp matching a headline, possibly with some keyword.
512 This regexp can match any headline with the specified keyword, or
513 without a keyword. The keyword isn't in any group by default,
514 but the stars and the body are.")
516 (defconst org-archive-tag "ARCHIVE"
517 "The tag that marks a subtree as archived.
518 An archived subtree does not open during visibility cycling, and does
519 not contribute to the agenda listings.")
521 (eval-and-compile
522 (defconst org-comment-string "COMMENT"
523 "Entries starting with this keyword will never be exported.
524 \\<org-mode-map>
525 An entry can be toggled between COMMENT and normal with
526 `\\[org-toggle-comment]'."))
529 ;;;; LaTeX Environments and Fragments
531 (defconst org-latex-regexps
532 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
533 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
534 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
535 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
536 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
537 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
538 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
539 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
540 "Regular expressions for matching embedded LaTeX.")
542 ;;;; Node Property
544 (defconst org-effort-property "Effort"
545 "The property that is being used to keep track of effort estimates.
546 Effort estimates given in this property need to have the format H:MM.")
548 ;;;; Table
550 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
551 "Detect an org-type or table-type table.")
553 (defconst org-table-line-regexp "^[ \t]*|"
554 "Detect an org-type table line.")
556 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
557 "Detect an org-type table line.")
559 (defconst org-table-hline-regexp "^[ \t]*|-"
560 "Detect an org-type table hline.")
562 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
563 "Detect a table-type table hline.")
565 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
566 "Detect the first line outside a table when searching from within it.
567 This works for both table types.")
569 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
570 "Detect a #+TBLFM line.")
572 ;;;; Timestamp
574 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
575 "Regular expression for fast time stamp matching.")
577 (defconst org-ts-regexp-inactive
578 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
579 "Regular expression for fast inactive time stamp matching.")
581 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
582 "Regular expression for fast time stamp matching.")
584 (defconst org-ts-regexp0
585 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
586 "Regular expression matching time strings for analysis.
587 This one does not require the space after the date, so it can be used
588 on a string that terminates immediately after the date.")
590 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
591 "Regular expression matching time strings for analysis.")
593 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
594 "Regular expression matching time stamps, with groups.")
596 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
597 "Regular expression matching time stamps (also [..]), with groups.")
599 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
600 "Regular expression matching a time stamp range.")
602 (defconst org-tr-regexp-both
603 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
604 "Regular expression matching a time stamp range.")
606 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
607 org-ts-regexp "\\)?")
608 "Regular expression matching a time stamp or time stamp range.")
610 (defconst org-tsr-regexp-both
611 (concat org-ts-regexp-both "\\(--?-?"
612 org-ts-regexp-both "\\)?")
613 "Regular expression matching a time stamp or time stamp range.
614 The time stamps may be either active or inactive.")
616 (defconst org-repeat-re
617 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
618 "Regular expression for specifying repeated events.
619 After a match, group 1 contains the repeat expression.")
621 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
622 "Formats for `format-time-string' which are used for time stamps.")
625 ;;; The custom variables
627 (defgroup org nil
628 "Outline-based notes management and organizer."
629 :tag "Org"
630 :group 'outlines
631 :group 'calendar)
633 (defcustom org-mode-hook nil
634 "Mode hook for Org mode, run after the mode was turned on."
635 :group 'org
636 :type 'hook)
638 (defcustom org-load-hook nil
639 "Hook that is run after org.el has been loaded."
640 :group 'org
641 :type 'hook)
643 (defcustom org-log-buffer-setup-hook nil
644 "Hook that is run after an Org log buffer is created."
645 :group 'org
646 :version "24.1"
647 :type 'hook)
649 (defvar org-modules) ; defined below
650 (defvar org-modules-loaded nil
651 "Have the modules been loaded already?")
653 (defun org-load-modules-maybe (&optional force)
654 "Load all extensions listed in `org-modules'."
655 (when (or force (not org-modules-loaded))
656 (dolist (ext org-modules)
657 (condition-case nil (require ext)
658 (error (message "Problems while trying to load feature `%s'" ext))))
659 (setq org-modules-loaded t)))
661 (defun org-set-modules (var value)
662 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
663 (set var value)
664 (when (featurep 'org)
665 (org-load-modules-maybe 'force)
666 (org-element-cache-reset 'all)))
668 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
669 "Modules that should always be loaded together with org.el.
671 If a description starts with <C>, the file is not part of Emacs
672 and loading it will require that you have downloaded and properly
673 installed the Org mode distribution.
675 You can also use this system to load external packages (i.e. neither Org
676 core modules, nor modules from the CONTRIB directory). Just add symbols
677 to the end of the list. If the package is called org-xyz.el, then you need
678 to add the symbol `xyz', and the package must have a call to:
680 (provide \\='org-xyz)
682 For export specific modules, see also `org-export-backends'."
683 :group 'org
684 :set 'org-set-modules
685 :version "24.4"
686 :package-version '(Org . "8.0")
687 :type
688 '(set :greedy t
689 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
690 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
691 (const :tag " crypt: Encryption of subtrees" org-crypt)
692 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
693 (const :tag " docview: Links to doc-view buffers" org-docview)
694 (const :tag " eww: Store link to url of eww" org-eww)
695 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
696 (const :tag " habit: Track your consistency with habits" org-habit)
697 (const :tag " id: Global IDs for identifying entries" org-id)
698 (const :tag " info: Links to Info nodes" org-info)
699 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
700 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
701 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
702 (const :tag " mouse: Additional mouse support" org-mouse)
703 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
704 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
705 (const :tag " tempo: Fast completion for structures" org-tempo)
706 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
708 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
709 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
710 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
711 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
712 (const :tag "C collector: Collect properties into tables" org-collector)
713 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
714 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
715 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
716 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
717 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
718 (const :tag "C eval: Include command output as text" org-eval)
719 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
720 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
721 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
722 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
723 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
724 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
725 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
726 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
727 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
728 (const :tag "C man: Support for links to manpages in Org mode" org-man)
729 (const :tag "C mew: Links to Mew folders/messages" org-mew)
730 (const :tag "C mtags: Support for muse-like tags" org-mtags)
731 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
732 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
733 (const :tag "C registry: A registry for Org links" org-registry)
734 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
735 (const :tag "C secretary: Team management with Org" org-secretary)
736 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
737 (const :tag "C toc: Table of contents for Org buffer" org-toc)
738 (const :tag "C track: Keep up with Org mode development" org-track)
739 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
740 (const :tag "C vm: Links to VM folders/messages" org-vm)
741 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
742 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
743 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
745 (defvar org-export-registered-backends) ; From ox.el.
746 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
747 (declare-function org-export-backend-name "ox" (backend) t)
748 (defcustom org-export-backends '(ascii html icalendar latex odt)
749 "List of export back-ends that should be always available.
751 If a description starts with <C>, the file is not part of Emacs
752 and loading it will require that you have downloaded and properly
753 installed the Org mode distribution.
755 Unlike to `org-modules', libraries in this list will not be
756 loaded along with Org, but only once the export framework is
757 needed.
759 This variable needs to be set before org.el is loaded. If you
760 need to make a change while Emacs is running, use the customize
761 interface or run the following code, where VAL stands for the new
762 value of the variable, after updating it:
764 (progn
765 (setq org-export-registered-backends
766 (cl-remove-if-not
767 (lambda (backend)
768 (let ((name (org-export-backend-name backend)))
769 (or (memq name val)
770 (catch \\='parentp
771 (dolist (b val)
772 (and (org-export-derived-backend-p b name)
773 (throw \\='parentp t)))))))
774 org-export-registered-backends))
775 (let ((new-list (mapcar #\\='org-export-backend-name
776 org-export-registered-backends)))
777 (dolist (backend val)
778 (cond
779 ((not (load (format \"ox-%s\" backend) t t))
780 (message \"Problems while trying to load export back-end \\=`%s\\='\"
781 backend))
782 ((not (memq backend new-list)) (push backend new-list))))
783 (set-default \\='org-export-backends new-list)))
785 Adding a back-end to this list will also pull the back-end it
786 depends on, if any."
787 :group 'org
788 :group 'org-export
789 :version "26.1"
790 :package-version '(Org . "9.0")
791 :initialize 'custom-initialize-set
792 :set (lambda (var val)
793 (if (not (featurep 'ox)) (set-default var val)
794 ;; Any back-end not required anymore (not present in VAL and not
795 ;; a parent of any back-end in the new value) is removed from the
796 ;; list of registered back-ends.
797 (setq org-export-registered-backends
798 (cl-remove-if-not
799 (lambda (backend)
800 (let ((name (org-export-backend-name backend)))
801 (or (memq name val)
802 (catch 'parentp
803 (dolist (b val)
804 (and (org-export-derived-backend-p b name)
805 (throw 'parentp t)))))))
806 org-export-registered-backends))
807 ;; Now build NEW-LIST of both new back-ends and required
808 ;; parents.
809 (let ((new-list (mapcar #'org-export-backend-name
810 org-export-registered-backends)))
811 (dolist (backend val)
812 (cond
813 ((not (load (format "ox-%s" backend) t t))
814 (message "Problems while trying to load export back-end `%s'"
815 backend))
816 ((not (memq backend new-list)) (push backend new-list))))
817 ;; Set VAR to that list with fixed dependencies.
818 (set-default var new-list))))
819 :type '(set :greedy t
820 (const :tag " ascii Export buffer to ASCII format" ascii)
821 (const :tag " beamer Export buffer to Beamer presentation" beamer)
822 (const :tag " html Export buffer to HTML format" html)
823 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
824 (const :tag " latex Export buffer to LaTeX format" latex)
825 (const :tag " man Export buffer to MAN format" man)
826 (const :tag " md Export buffer to Markdown format" md)
827 (const :tag " odt Export buffer to ODT format" odt)
828 (const :tag " org Export buffer to Org format" org)
829 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
830 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
831 (const :tag "C deck Export buffer to deck.js presentations" deck)
832 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
833 (const :tag "C groff Export buffer to Groff format" groff)
834 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
835 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
836 (const :tag "C s5 Export buffer to s5 presentations" s5)
837 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
839 (eval-after-load 'ox
840 '(dolist (backend org-export-backends)
841 (condition-case nil (require (intern (format "ox-%s" backend)))
842 (error (message "Problems while trying to load export back-end `%s'"
843 backend)))))
845 (defcustom org-support-shift-select nil
846 "Non-nil means make shift-cursor commands select text when possible.
847 \\<org-mode-map>\
849 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
850 start selecting a region, or enlarge regions started in this way.
851 In Org mode, in special contexts, these same keys are used for
852 other purposes, important enough to compete with shift selection.
853 Org tries to balance these needs by supporting `shift-select-mode'
854 outside these special contexts, under control of this variable.
856 The default of this variable is nil, to avoid confusing behavior. Shifted
857 cursor keys will then execute Org commands in the following contexts:
858 - on a headline, changing TODO state (left/right) and priority (up/down)
859 - on a time stamp, changing the time
860 - in a plain list item, changing the bullet type
861 - in a property definition line, switching between allowed values
862 - in the BEGIN line of a clock table (changing the time block).
863 Outside these contexts, the commands will throw an error.
865 When this variable is t and the cursor is not in a special
866 context, Org mode will support shift-selection for making and
867 enlarging regions. To make this more effective, the bullet
868 cycling will no longer happen anywhere in an item line, but only
869 if the cursor is exactly on the bullet.
871 If you set this variable to the symbol `always', then the keys
872 will not be special in headlines, property lines, and item lines,
873 to make shift selection work there as well. If this is what you
874 want, you can use the following alternative commands:
875 `\\[org-todo]' and `\\[org-priority]' \
876 to change TODO state and priority,
877 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
878 can be used to switch TODO sets,
879 `\\[org-ctrl-c-minus]' to cycle item bullet types,
880 and properties can be edited by hand or in column view.
882 However, when the cursor is on a timestamp, shift-cursor commands
883 will still edit the time stamp - this is just too good to give up."
884 :group 'org
885 :type '(choice
886 (const :tag "Never" nil)
887 (const :tag "When outside special context" t)
888 (const :tag "Everywhere except timestamps" always)))
890 (defcustom org-loop-over-headlines-in-active-region nil
891 "Shall some commands act upon headlines in the active region?
893 When set to t, some commands will be performed in all headlines
894 within the active region.
896 When set to `start-level', some commands will be performed in all
897 headlines within the active region, provided that these headlines
898 are of the same level than the first one.
900 When set to a string, those commands will be performed on the
901 matching headlines within the active region. Such string must be
902 a tags/property/todo match as it is used in the agenda tags view.
904 The list of commands is: `org-schedule', `org-deadline',
905 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
906 `org-archive-to-archive-sibling'. The archiving commands skip
907 already archived entries."
908 :type '(choice (const :tag "Don't loop" nil)
909 (const :tag "All headlines in active region" t)
910 (const :tag "In active region, headlines at the same level than the first one" start-level)
911 (string :tag "Tags/Property/Todo matcher"))
912 :version "24.1"
913 :group 'org-todo
914 :group 'org-archive)
916 (defcustom org-startup-folded t
917 "Non-nil means entering Org mode will switch to OVERVIEW.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: fold (or `overview', this is equivalent)
923 #+STARTUP: nofold (or `showall', this is equivalent)
924 #+STARTUP: content
925 #+STARTUP: showeverything
927 Set `org-agenda-inhibit-startup' to a non-nil value if you want
928 to ignore this option when Org opens agenda files for the first
929 time."
930 :group 'org-startup
931 :type '(choice
932 (const :tag "nofold: show all" nil)
933 (const :tag "fold: overview" t)
934 (const :tag "content: all headlines" content)
935 (const :tag "show everything, even drawers" showeverything)))
937 (defcustom org-startup-truncated t
938 "Non-nil means entering Org mode will set `truncate-lines'.
939 This is useful since some lines containing links can be very long and
940 uninteresting. Also tables look terrible when wrapped.
942 The variable `org-startup-truncated' allows to configure
943 truncation for Org mode different to the other modes that use the
944 variable `truncate-lines' and as a shortcut instead of putting
945 the variable `truncate-lines' into the `org-mode-hook'. If one
946 wants to configure truncation for Org mode not statically but
947 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
948 the variable `truncate-lines' has to be used because in such a
949 case it is too late to set the variable `org-startup-truncated'."
950 :group 'org-startup
951 :type 'boolean)
953 (defcustom org-startup-indented nil
954 "Non-nil means turn on `org-indent-mode' on startup.
955 This can also be configured on a per-file basis by adding one of
956 the following lines anywhere in the buffer:
958 #+STARTUP: indent
959 #+STARTUP: noindent"
960 :group 'org-structure
961 :type '(choice
962 (const :tag "Not" nil)
963 (const :tag "Globally (slow on startup in large files)" t)))
965 (defcustom org-use-sub-superscripts t
966 "Non-nil means interpret \"_\" and \"^\" for display.
968 If you want to control how Org exports those characters, see
969 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
970 used to be an alias for `org-export-with-sub-superscripts' in
971 Org <8.0, it is not anymore.
973 When this option is turned on, you can use TeX-like syntax for
974 sub- and superscripts within the buffer. Several characters after
975 \"_\" or \"^\" will be considered as a single item - so grouping
976 with {} is normally not needed. For example, the following things
977 will be parsed as single sub- or superscripts:
979 10^24 or 10^tau several digits will be considered 1 item.
980 10^-12 or 10^-tau a leading sign with digits or a word
981 x^2-y^3 will be read as x^2 - y^3, because items are
982 terminated by almost any nonword/nondigit char.
983 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
985 Still, ambiguity is possible. So when in doubt, use {} to enclose
986 the sub/superscript. If you set this variable to the symbol `{}',
987 the braces are *required* in order to trigger interpretations as
988 sub/superscript. This can be helpful in documents that need \"_\"
989 frequently in plain text."
990 :group 'org-startup
991 :version "24.4"
992 :package-version '(Org . "8.0")
993 :type '(choice
994 (const :tag "Always interpret" t)
995 (const :tag "Only with braces" {})
996 (const :tag "Never interpret" nil)))
998 (defcustom org-startup-with-beamer-mode nil
999 "Non-nil means turn on `org-beamer-mode' on startup.
1000 This can also be configured on a per-file basis by adding one of
1001 the following lines anywhere in the buffer:
1003 #+STARTUP: beamer"
1004 :group 'org-startup
1005 :version "24.1"
1006 :type 'boolean)
1008 (defcustom org-startup-align-all-tables nil
1009 "Non-nil means align all tables when visiting a file.
1010 This can also be configured on a per-file basis by adding one of
1011 the following lines anywhere in the buffer:
1012 #+STARTUP: align
1013 #+STARTUP: noalign"
1014 :group 'org-startup
1015 :type 'boolean)
1017 (defcustom org-startup-shrink-all-tables nil
1018 "Non-nil means shrink all table columns with a width cookie.
1019 This can also be configured on a per-file basis by adding one of
1020 the following lines anywhere in the buffer:
1021 #+STARTUP: shrink"
1022 :group 'org-startup
1023 :type 'boolean
1024 :version "27.1"
1025 :package-version '(Org . "9.2")
1026 :safe #'booleanp)
1028 (defcustom org-startup-with-inline-images nil
1029 "Non-nil means show inline images when loading a new Org file.
1030 This can also be configured on a per-file basis by adding one of
1031 the following lines anywhere in the buffer:
1032 #+STARTUP: inlineimages
1033 #+STARTUP: noinlineimages"
1034 :group 'org-startup
1035 :version "24.1"
1036 :type 'boolean)
1038 (defcustom org-startup-with-latex-preview nil
1039 "Non-nil means preview LaTeX fragments when loading a new Org file.
1041 This can also be configured on a per-file basis by adding one of
1042 the following lines anywhere in the buffer:
1043 #+STARTUP: latexpreview
1044 #+STARTUP: nolatexpreview"
1045 :group 'org-startup
1046 :version "24.4"
1047 :package-version '(Org . "8.0")
1048 :type 'boolean)
1050 (defcustom org-insert-mode-line-in-empty-file nil
1051 "Non-nil means insert the first line setting Org mode in empty files.
1052 When the function `org-mode' is called interactively in an empty file, this
1053 normally means that the file name does not automatically trigger Org mode.
1054 To ensure that the file will always be in Org mode in the future, a
1055 line enforcing Org mode will be inserted into the buffer, if this option
1056 has been set."
1057 :group 'org-startup
1058 :type 'boolean)
1060 (defcustom org-replace-disputed-keys nil
1061 "Non-nil means use alternative key bindings for some keys.
1063 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1064 These keys are also used by other packages like Shift Select mode,
1065 CUA mode or Windmove. If you want to use Org mode together with
1066 one of these other modes, or more generally if you would like to
1067 move some Org mode commands to other keys, set this variable and
1068 configure the keys with the variable `org-disputed-keys'.
1070 This option is only relevant at load-time of Org mode, and must be set
1071 *before* org.el is loaded. Changing it requires a restart of Emacs to
1072 become effective."
1073 :group 'org-startup
1074 :type 'boolean)
1076 (defcustom org-use-extra-keys nil
1077 "Non-nil means use extra key sequence definitions for certain commands.
1078 This happens automatically if `window-system' is nil. This
1079 variable lets you do the same manually. You must set it before
1080 loading Org."
1081 :group 'org-startup
1082 :type 'boolean)
1084 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1086 (defcustom org-disputed-keys
1087 '(([(shift up)] . [(meta p)])
1088 ([(shift down)] . [(meta n)])
1089 ([(shift left)] . [(meta -)])
1090 ([(shift right)] . [(meta +)])
1091 ([(control shift right)] . [(meta shift +)])
1092 ([(control shift left)] . [(meta shift -)]))
1093 "Keys for which Org mode and other modes compete.
1094 This is an alist, cars are the default keys, second element specifies
1095 the alternative to use when `org-replace-disputed-keys' is t.
1097 Keys can be specified in any syntax supported by `define-key'.
1098 The value of this option takes effect only at Org mode startup,
1099 therefore you'll have to restart Emacs to apply it after changing."
1100 :group 'org-startup
1101 :type 'alist)
1103 (defun org-key (key)
1104 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1105 Or return the original if not disputed."
1106 (when org-replace-disputed-keys
1107 (let* ((nkey (key-description key))
1108 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1109 org-disputed-keys)))
1110 (setq key (if x (cdr x) key))))
1111 key)
1113 (defun org-defkey (keymap key def)
1114 "Define a key, possibly translated, as returned by `org-key'."
1115 (define-key keymap (org-key key) def))
1117 (defcustom org-ellipsis nil
1118 "The ellipsis to use in the Org mode outline.
1120 When nil, just use the standard three dots. When a non-empty string,
1121 use that string instead.
1123 The change affects only Org mode (which will then use its own display table).
1124 Changing this requires executing `\\[org-mode]' in a buffer to become
1125 effective."
1126 :group 'org-startup
1127 :type '(choice (const :tag "Default" nil)
1128 (string :tag "String" :value "...#"))
1129 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1131 (defvar org-display-table nil
1132 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1134 (defgroup org-keywords nil
1135 "Keywords in Org mode."
1136 :tag "Org Keywords"
1137 :group 'org)
1139 (defcustom org-closed-keep-when-no-todo nil
1140 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1141 :group 'org-todo
1142 :group 'org-keywords
1143 :version "24.4"
1144 :package-version '(Org . "8.0")
1145 :type 'boolean)
1147 (defgroup org-structure nil
1148 "Options concerning the general structure of Org files."
1149 :tag "Org Structure"
1150 :group 'org)
1152 (defgroup org-reveal-location nil
1153 "Options about how to make context of a location visible."
1154 :tag "Org Reveal Location"
1155 :group 'org-structure)
1157 (defcustom org-show-context-detail '((agenda . local)
1158 (bookmark-jump . lineage)
1159 (isearch . lineage)
1160 (default . ancestors))
1161 "Alist between context and visibility span when revealing a location.
1163 \\<org-mode-map>Some actions may move point into invisible
1164 locations. As a consequence, Org always expose a neighborhood
1165 around point. How much is shown depends on the initial action,
1166 or context. Valid contexts are
1168 agenda when exposing an entry from the agenda
1169 org-goto when using the command `org-goto' (`\\[org-goto]')
1170 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1171 tags-tree when constructing a sparse tree based on tags matches
1172 link-search when exposing search matches associated with a link
1173 mark-goto when exposing the jump goal of a mark
1174 bookmark-jump when exposing a bookmark location
1175 isearch when exiting from an incremental search
1176 default default for all contexts not set explicitly
1178 Allowed visibility spans are
1180 minimal show current headline; if point is not on headline,
1181 also show entry
1183 local show current headline, entry and next headline
1185 ancestors show current headline and its direct ancestors; if
1186 point is not on headline, also show entry
1188 lineage show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and first child
1192 tree show current headline, its direct ancestors and all
1193 their children; if point is not on headline, also show
1194 entry and all children
1196 canonical show current headline, its direct ancestors along with
1197 their entries and children; if point is not located on
1198 the headline, also show current entry and all children
1200 As special cases, a nil or t value means show all contexts in
1201 `minimal' or `canonical' view, respectively.
1203 Some views can make displayed information very compact, but also
1204 make it harder to edit the location of the match. In such
1205 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1206 more context."
1207 :group 'org-reveal-location
1208 :version "26.1"
1209 :package-version '(Org . "9.0")
1210 :type '(choice
1211 (const :tag "Canonical" t)
1212 (const :tag "Minimal" nil)
1213 (repeat :greedy t :tag "Individual contexts"
1214 (cons
1215 (choice :tag "Context"
1216 (const agenda)
1217 (const org-goto)
1218 (const occur-tree)
1219 (const tags-tree)
1220 (const link-search)
1221 (const mark-goto)
1222 (const bookmark-jump)
1223 (const isearch)
1224 (const default))
1225 (choice :tag "Detail level"
1226 (const minimal)
1227 (const local)
1228 (const ancestors)
1229 (const lineage)
1230 (const tree)
1231 (const canonical))))))
1233 (defcustom org-indirect-buffer-display 'other-window
1234 "How should indirect tree buffers be displayed?
1236 This applies to indirect buffers created with the commands
1237 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1239 Valid values are:
1240 current-window Display in the current window
1241 other-window Just display in another window.
1242 dedicated-frame Create one new frame, and re-use it each time.
1243 new-frame Make a new frame each time. Note that in this case
1244 previously-made indirect buffers are kept, and you need to
1245 kill these buffers yourself."
1246 :group 'org-structure
1247 :group 'org-agenda-windows
1248 :type '(choice
1249 (const :tag "In current window" current-window)
1250 (const :tag "In current frame, other window" other-window)
1251 (const :tag "Each time a new frame" new-frame)
1252 (const :tag "One dedicated frame" dedicated-frame)))
1254 (defcustom org-use-speed-commands nil
1255 "Non-nil means activate single letter commands at beginning of a headline.
1256 This may also be a function to test for appropriate locations where speed
1257 commands should be active.
1259 For example, to activate speed commands when the point is on any
1260 star at the beginning of the headline, you can do this:
1262 (setq org-use-speed-commands
1263 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1264 :group 'org-structure
1265 :type '(choice
1266 (const :tag "Never" nil)
1267 (const :tag "At beginning of headline stars" t)
1268 (function)))
1270 (defcustom org-speed-commands-user nil
1271 "Alist of additional speed commands.
1272 This list will be checked before `org-speed-commands-default'
1273 when the variable `org-use-speed-commands' is non-nil
1274 and when the cursor is at the beginning of a headline.
1275 The car of each entry is a string with a single letter, which must
1276 be assigned to `self-insert-command' in the global map.
1277 The cdr is either a command to be called interactively, a function
1278 to be called, or a form to be evaluated.
1279 An entry that is just a list with a single string will be interpreted
1280 as a descriptive headline that will be added when listing the speed
1281 commands in the Help buffer using the `?' speed command."
1282 :group 'org-structure
1283 :type '(repeat :value ("k" . ignore)
1284 (choice :value ("k" . ignore)
1285 (list :tag "Descriptive Headline" (string :tag "Headline"))
1286 (cons :tag "Letter and Command"
1287 (string :tag "Command letter")
1288 (choice
1289 (function)
1290 (sexp))))))
1292 (defcustom org-bookmark-names-plist
1293 '(:last-capture "org-capture-last-stored"
1294 :last-refile "org-refile-last-stored"
1295 :last-capture-marker "org-capture-last-stored-marker")
1296 "Names for bookmarks automatically set by some Org commands.
1297 This can provide strings as names for a number of bookmarks Org sets
1298 automatically. The following keys are currently implemented:
1299 :last-capture
1300 :last-capture-marker
1301 :last-refile
1302 When a key does not show up in the property list, the corresponding bookmark
1303 is not set."
1304 :group 'org-structure
1305 :type 'plist)
1307 (defgroup org-cycle nil
1308 "Options concerning visibility cycling in Org mode."
1309 :tag "Org Cycle"
1310 :group 'org-structure)
1312 (defcustom org-cycle-skip-children-state-if-no-children t
1313 "Non-nil means skip CHILDREN state in entries that don't have any."
1314 :group 'org-cycle
1315 :type 'boolean)
1317 (defcustom org-cycle-max-level nil
1318 "Maximum level which should still be subject to visibility cycling.
1319 Levels higher than this will, for cycling, be treated as text, not a headline.
1320 When `org-odd-levels-only' is set, a value of N in this variable actually
1321 means 2N-1 stars as the limiting headline.
1322 When nil, cycle all levels.
1323 Note that the limiting level of cycling is also influenced by
1324 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1325 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1326 than its value."
1327 :group 'org-cycle
1328 :type '(choice
1329 (const :tag "No limit" nil)
1330 (integer :tag "Maximum level")))
1332 (defcustom org-hide-block-startup nil
1333 "Non-nil means entering Org mode will fold all blocks.
1334 This can also be set in on a per-file basis with
1336 #+STARTUP: hideblocks
1337 #+STARTUP: showblocks"
1338 :group 'org-startup
1339 :group 'org-cycle
1340 :type 'boolean)
1342 (defcustom org-cycle-global-at-bob nil
1343 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1345 This makes it possible to do global cycling without having to use `S-TAB'
1346 or `\\[universal-argument] TAB'. For this special case to work, the first \
1347 line of the buffer
1348 must not be a headline -- it may be empty or some other text.
1350 When used in this way, `org-cycle-hook' is disabled temporarily to make
1351 sure the cursor stays at the beginning of the buffer.
1353 When this option is nil, don't do anything special at the beginning of
1354 the buffer."
1355 :group 'org-cycle
1356 :type 'boolean)
1358 (defcustom org-cycle-level-after-item/entry-creation t
1359 "Non-nil means cycle entry level or item indentation in new empty entries.
1361 When the cursor is at the end of an empty headline, i.e., with only stars
1362 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1363 and then all possible ancestor states, before returning to the original state.
1364 This makes data entry extremely fast: M-RET to create a new headline,
1365 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1367 When the cursor is at the end of an empty plain list item, one TAB will
1368 make it a subitem, two or more tabs will back up to make this an item
1369 higher up in the item hierarchy."
1370 :group 'org-cycle
1371 :type 'boolean)
1373 (defcustom org-cycle-emulate-tab t
1374 "Where should `org-cycle' emulate TAB.
1375 nil Never
1376 white Only in completely white lines
1377 whitestart Only at the beginning of lines, before the first non-white char
1378 t Everywhere except in headlines
1379 exc-hl-bol Everywhere except at the start of a headline
1380 If TAB is used in a place where it does not emulate TAB, the current subtree
1381 visibility is cycled."
1382 :group 'org-cycle
1383 :type '(choice (const :tag "Never" nil)
1384 (const :tag "Only in completely white lines" white)
1385 (const :tag "Before first char in a line" whitestart)
1386 (const :tag "Everywhere except in headlines" t)
1387 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1389 (defcustom org-cycle-separator-lines 2
1390 "Number of empty lines needed to keep an empty line between collapsed trees.
1391 If you leave an empty line between the end of a subtree and the following
1392 headline, this empty line is hidden when the subtree is folded.
1393 Org mode will leave (exactly) one empty line visible if the number of
1394 empty lines is equal or larger to the number given in this variable.
1395 So the default 2 means at least 2 empty lines after the end of a subtree
1396 are needed to produce free space between a collapsed subtree and the
1397 following headline.
1399 If the number is negative, and the number of empty lines is at least -N,
1400 all empty lines are shown.
1402 Special case: when 0, never leave empty lines in collapsed view."
1403 :group 'org-cycle
1404 :type 'integer)
1405 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1407 (defcustom org-pre-cycle-hook nil
1408 "Hook that is run before visibility cycling is happening.
1409 The function(s) in this hook must accept a single argument which indicates
1410 the new state that will be set right after running this hook. The
1411 argument is a symbol. Before a global state change, it can have the values
1412 `overview', `content', or `all'. Before a local state change, it can have
1413 the values `folded', `children', or `subtree'."
1414 :group 'org-cycle
1415 :type 'hook)
1417 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1418 org-cycle-show-empty-lines
1419 org-optimize-window-after-visibility-change)
1420 "Hook that is run after `org-cycle' has changed the buffer visibility.
1421 The function(s) in this hook must accept a single argument which indicates
1422 the new state that was set by the most recent `org-cycle' command. The
1423 argument is a symbol. After a global state change, it can have the values
1424 `overview', `contents', or `all'. After a local state change, it can have
1425 the values `folded', `children', or `subtree'."
1426 :group 'org-cycle
1427 :type 'hook
1428 :version "26.1"
1429 :package-version '(Org . "8.3"))
1431 (defgroup org-edit-structure nil
1432 "Options concerning structure editing in Org mode."
1433 :tag "Org Edit Structure"
1434 :group 'org-structure)
1436 (defcustom org-odd-levels-only nil
1437 "Non-nil means skip even levels and only use odd levels for the outline.
1438 This has the effect that two stars are being added/taken away in
1439 promotion/demotion commands. It also influences how levels are
1440 handled by the exporters.
1441 Changing it requires restart of `font-lock-mode' to become effective
1442 for fontification also in regions already fontified.
1443 You may also set this on a per-file basis by adding one of the following
1444 lines to the buffer:
1446 #+STARTUP: odd
1447 #+STARTUP: oddeven"
1448 :group 'org-edit-structure
1449 :group 'org-appearance
1450 :type 'boolean)
1452 (defcustom org-adapt-indentation t
1453 "Non-nil means adapt indentation to outline node level.
1455 When this variable is set, Org assumes that you write outlines by
1456 indenting text in each node to align with the headline (after the
1457 stars). The following issues are influenced by this variable:
1459 - The indentation is increased by one space in a demotion
1460 command, and decreased by one in a promotion command. However,
1461 in the latter case, if shifting some line in the entry body
1462 would alter document structure (e.g., insert a new headline),
1463 indentation is not changed at all.
1465 - Property drawers and planning information is inserted indented
1466 when this variable is set. When nil, they will not be indented.
1468 - TAB indents a line relative to current level. The lines below
1469 a headline will be indented when this variable is set.
1471 Note that this is all about true indentation, by adding and
1472 removing space characters. See also \"org-indent.el\" which does
1473 level-dependent indentation in a virtual way, i.e. at display
1474 time in Emacs."
1475 :group 'org-edit-structure
1476 :type 'boolean
1477 :safe #'booleanp)
1479 (defcustom org-special-ctrl-a/e nil
1480 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1482 When t, `C-a' will bring back the cursor to the beginning of the
1483 headline text, i.e. after the stars and after a possible TODO
1484 keyword. In an item, this will be the position after bullet and
1485 check-box, if any. When the cursor is already at that position,
1486 another `C-a' will bring it to the beginning of the line.
1488 `C-e' will jump to the end of the headline, ignoring the presence
1489 of tags in the headline. A second `C-e' will then jump to the
1490 true end of the line, after any tags. This also means that, when
1491 this variable is non-nil, `C-e' also will never jump beyond the
1492 end of the heading of a folded section, i.e. not after the
1493 ellipses.
1495 When set to the symbol `reversed', the first `C-a' or `C-e' works
1496 normally, going to the true line boundary first. Only a directly
1497 following, identical keypress will bring the cursor to the
1498 special positions.
1500 This may also be a cons cell where the behavior for `C-a' and
1501 `C-e' is set separately."
1502 :group 'org-edit-structure
1503 :type '(choice
1504 (const :tag "off" nil)
1505 (const :tag "on: after stars/bullet and before tags first" t)
1506 (const :tag "reversed: true line boundary first" reversed)
1507 (cons :tag "Set C-a and C-e separately"
1508 (choice :tag "Special C-a"
1509 (const :tag "off" nil)
1510 (const :tag "on: after stars/bullet first" t)
1511 (const :tag "reversed: before stars/bullet first" reversed))
1512 (choice :tag "Special C-e"
1513 (const :tag "off" nil)
1514 (const :tag "on: before tags first" t)
1515 (const :tag "reversed: after tags first" reversed)))))
1516 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1518 (defcustom org-special-ctrl-k nil
1519 "Non-nil means `C-k' will behave specially in headlines.
1520 When nil, `C-k' will call the default `kill-line' command.
1521 When t, the following will happen while the cursor is in the headline:
1523 - When the cursor is at the beginning of a headline, kill the entire
1524 line and possible the folded subtree below the line.
1525 - When in the middle of the headline text, kill the headline up to the tags.
1526 - When after the headline text, kill the tags."
1527 :group 'org-edit-structure
1528 :type 'boolean)
1530 (defcustom org-ctrl-k-protect-subtree nil
1531 "Non-nil means, do not delete a hidden subtree with C-k.
1532 When set to the symbol `error', simply throw an error when C-k is
1533 used to kill (part-of) a headline that has hidden text behind it.
1534 Any other non-nil value will result in a query to the user, if it is
1535 OK to kill that hidden subtree. When nil, kill without remorse."
1536 :group 'org-edit-structure
1537 :version "24.1"
1538 :type '(choice
1539 (const :tag "Do not protect hidden subtrees" nil)
1540 (const :tag "Protect hidden subtrees with a security query" t)
1541 (const :tag "Never kill a hidden subtree with C-k" error)))
1543 (defcustom org-special-ctrl-o t
1544 "Non-nil means, make `C-o' insert a row in tables."
1545 :group 'org-edit-structure
1546 :type 'boolean)
1548 (defcustom org-catch-invisible-edits nil
1549 "Check if in invisible region before inserting or deleting a character.
1550 Valid values are:
1552 nil Do not check, so just do invisible edits.
1553 error Throw an error and do nothing.
1554 show Make point visible, and do the requested edit.
1555 show-and-error Make point visible, then throw an error and abort the edit.
1556 smart Make point visible, and do insertion/deletion if it is
1557 adjacent to visible text and the change feels predictable.
1558 Never delete a previously invisible character or add in the
1559 middle or right after an invisible region. Basically, this
1560 allows insertion and backward-delete right before ellipses.
1561 FIXME: maybe in this case we should not even show?"
1562 :group 'org-edit-structure
1563 :version "24.1"
1564 :type '(choice
1565 (const :tag "Do not check" nil)
1566 (const :tag "Throw error when trying to edit" error)
1567 (const :tag "Unhide, but do not do the edit" show-and-error)
1568 (const :tag "Show invisible part and do the edit" show)
1569 (const :tag "Be smart and do the right thing" smart)))
1571 (defcustom org-yank-folded-subtrees t
1572 "Non-nil means when yanking subtrees, fold them.
1573 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1574 it starts with a heading and all other headings in it are either children
1575 or siblings, then fold all the subtrees. However, do this only if no
1576 text after the yank would be swallowed into a folded tree by this action."
1577 :group 'org-edit-structure
1578 :type 'boolean)
1580 (defcustom org-yank-adjusted-subtrees nil
1581 "Non-nil means when yanking subtrees, adjust the level.
1582 With this setting, `org-paste-subtree' is used to insert the subtree, see
1583 this function for details."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-M-RET-may-split-line '((default . t))
1588 "Non-nil means M-RET will split the line at the cursor position.
1589 When nil, it will go to the end of the line before making a
1590 new line.
1591 You may also set this option in a different way for different
1592 contexts. Valid contexts are:
1594 headline when creating a new headline
1595 item when creating a new item
1596 table in a table field
1597 default the value to be used for all contexts not explicitly
1598 customized"
1599 :group 'org-structure
1600 :group 'org-table
1601 :type '(choice
1602 (const :tag "Always" t)
1603 (const :tag "Never" nil)
1604 (repeat :greedy t :tag "Individual contexts"
1605 (cons
1606 (choice :tag "Context"
1607 (const headline)
1608 (const item)
1609 (const table)
1610 (const default))
1611 (boolean)))))
1614 (defcustom org-insert-heading-respect-content nil
1615 "Non-nil means insert new headings after the current subtree.
1616 \\<org-mode-map>
1617 When nil, the new heading is created directly after the current line.
1618 The commands `\\[org-insert-heading-respect-content]' and \
1619 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1620 for the duration of the command."
1621 :group 'org-structure
1622 :type 'boolean)
1624 (defcustom org-blank-before-new-entry '((heading . auto)
1625 (plain-list-item . auto))
1626 "Should `org-insert-heading' leave a blank line before new heading/item?
1627 The value is an alist, with `heading' and `plain-list-item' as CAR,
1628 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1629 which case Org will look at the surrounding headings/items and try to
1630 make an intelligent decision whether to insert a blank line or not."
1631 :group 'org-edit-structure
1632 :type '(list
1633 (cons (const heading)
1634 (choice (const :tag "Never" nil)
1635 (const :tag "Always" t)
1636 (const :tag "Auto" auto)))
1637 (cons (const plain-list-item)
1638 (choice (const :tag "Never" nil)
1639 (const :tag "Always" t)
1640 (const :tag "Auto" auto)))))
1642 (defcustom org-insert-heading-hook nil
1643 "Hook being run after inserting a new heading."
1644 :group 'org-edit-structure
1645 :type 'hook)
1647 (defcustom org-enable-fixed-width-editor t
1648 "Non-nil means lines starting with \":\" are treated as fixed-width.
1649 This currently only means they are never auto-wrapped.
1650 When nil, such lines will be treated like ordinary lines."
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defgroup org-sparse-trees nil
1655 "Options concerning sparse trees in Org mode."
1656 :tag "Org Sparse Trees"
1657 :group 'org-structure)
1659 (defcustom org-highlight-sparse-tree-matches t
1660 "Non-nil means highlight all matches that define a sparse tree.
1661 The highlights will automatically disappear the next time the buffer is
1662 changed by an edit command."
1663 :group 'org-sparse-trees
1664 :type 'boolean)
1666 (defcustom org-remove-highlights-with-change t
1667 "Non-nil means any change to the buffer will remove temporary highlights.
1668 \\<org-mode-map>\
1669 Such highlights are created by `org-occur' and `org-clock-display'.
1670 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1671 to get rid of the highlights.
1672 The highlights created by `org-toggle-latex-fragment' always need
1673 `\\[org-toggle-latex-fragment]' to be removed."
1674 :group 'org-sparse-trees
1675 :group 'org-time
1676 :type 'boolean)
1678 (defcustom org-occur-case-fold-search t
1679 "Non-nil means `org-occur' should be case-insensitive.
1680 If set to `smart' the search will be case-insensitive only if it
1681 doesn't specify any upper case character."
1682 :group 'org-sparse-trees
1683 :version "26.1"
1684 :type '(choice
1685 (const :tag "Case-sensitive" nil)
1686 (const :tag "Case-insensitive" t)
1687 (const :tag "Case-insensitive for lower case searches only" smart)))
1689 (defcustom org-occur-hook '(org-first-headline-recenter)
1690 "Hook that is run after `org-occur' has constructed a sparse tree.
1691 This can be used to recenter the window to show as much of the structure
1692 as possible."
1693 :group 'org-sparse-trees
1694 :type 'hook)
1696 (defgroup org-table nil
1697 "Options concerning tables in Org mode."
1698 :tag "Org Table"
1699 :group 'org)
1701 (defcustom org-self-insert-cluster-for-undo nil
1702 "Non-nil means cluster self-insert commands for undo when possible.
1703 If this is set, then, like in the Emacs command loop, 20 consecutive
1704 characters will be undone together.
1705 This is configurable, because there is some impact on typing performance."
1706 :group 'org-table
1707 :type 'boolean)
1709 (defcustom org-table-tab-recognizes-table.el t
1710 "Non-nil means TAB will automatically notice a table.el table.
1711 When it sees such a table, it moves point into it and - if necessary -
1712 calls `table-recognize-table'."
1713 :group 'org-table-editing
1714 :type 'boolean)
1716 (defgroup org-link nil
1717 "Options concerning links in Org mode."
1718 :tag "Org Link"
1719 :group 'org)
1721 (defvar-local org-link-abbrev-alist-local nil
1722 "Buffer-local version of `org-link-abbrev-alist', which see.
1723 The value of this is taken from the #+LINK lines.")
1725 (defcustom org-link-parameters
1726 '(("doi" :follow org--open-doi-link)
1727 ("elisp" :follow org--open-elisp-link)
1728 ("file" :complete org-file-complete-link)
1729 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1730 ("help" :follow org--open-help-link)
1731 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1732 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1733 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1734 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1735 ("shell" :follow org--open-shell-link))
1736 "An alist of properties that defines all the links in Org mode.
1737 The key in each association is a string of the link type.
1738 Subsequent optional elements make up a p-list of link properties.
1740 :follow - A function that takes the link path as an argument.
1742 :export - A function that takes the link path, description and
1743 export-backend as arguments.
1745 :store - A function responsible for storing the link. See the
1746 function `org-store-link-functions'.
1748 :complete - A function that inserts a link with completion. The
1749 function takes one optional prefix arg.
1751 :face - A face for the link, or a function that returns a face.
1752 The function takes one argument which is the link path. The
1753 default face is `org-link'.
1755 :mouse-face - The mouse-face. The default is `highlight'.
1757 :display - `full' will not fold the link in descriptive
1758 display. Default is `org-link'.
1760 :help-echo - A string or function that takes (window object position)
1761 as arguments and returns a string.
1763 :keymap - A keymap that is active on the link. The default is
1764 `org-mouse-map'.
1766 :htmlize-link - A function for the htmlize-link. Defaults
1767 to (list :uri \"type:path\")
1769 :activate-func - A function to run at the end of font-lock
1770 activation. The function must accept (link-start link-end path bracketp)
1771 as arguments."
1772 :group 'org-link
1773 :type '(alist :tag "Link display parameters"
1774 :value-type plist)
1775 :version "26.1"
1776 :package-version '(Org . "9.1"))
1778 (defun org-link-get-parameter (type key)
1779 "Get TYPE link property for KEY.
1780 TYPE is a string and KEY is a plist keyword."
1781 (plist-get
1782 (cdr (assoc type org-link-parameters))
1783 key))
1785 (defun org-link-set-parameters (type &rest parameters)
1786 "Set link TYPE properties to PARAMETERS.
1787 PARAMETERS should be :key val pairs."
1788 (let ((data (assoc type org-link-parameters)))
1789 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1790 (push (cons type parameters) org-link-parameters)
1791 (org-make-link-regexps)
1792 (org-element-update-syntax))))
1794 (defun org-link-types ()
1795 "Return a list of known link types."
1796 (mapcar #'car org-link-parameters))
1798 (defcustom org-link-abbrev-alist nil
1799 "Alist of link abbreviations.
1800 The car of each element is a string, to be replaced at the start of a link.
1801 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1802 links in Org buffers can have an optional tag after a double colon, e.g.,
1804 [[linkkey:tag][description]]
1806 The `linkkey' must be a single word, starting with a letter, followed
1807 by letters, numbers, `-' or `_'.
1809 If REPLACE is a string, the tag will simply be appended to create the link.
1810 If the string contains \"%s\", the tag will be inserted there. If the string
1811 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1812 at that point (see the function `url-hexify-string'). If the string contains
1813 the specifier \"%(my-function)\", then the custom function `my-function' will
1814 be invoked: this function takes the tag as its only argument and must return
1815 a string.
1817 REPLACE may also be a function that will be called with the tag as the
1818 only argument to create the link, which should be returned as a string.
1820 See the manual for examples."
1821 :group 'org-link
1822 :type '(repeat
1823 (cons
1824 (string :tag "Protocol")
1825 (choice
1826 (string :tag "Format")
1827 (function)))))
1829 (defcustom org-descriptive-links t
1830 "Non-nil means Org will display descriptive links.
1831 E.g. [[https://orgmode.org][Org website]] will be displayed as
1832 \"Org Website\", hiding the link itself and just displaying its
1833 description. When set to nil, Org will display the full links
1834 literally.
1836 You can interactively set the value of this variable by calling
1837 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1838 :group 'org-link
1839 :type 'boolean)
1841 (defcustom org-link-file-path-type 'adaptive
1842 "How the path name in file links should be stored.
1843 Valid values are:
1845 relative Relative to the current directory, i.e. the directory of the file
1846 into which the link is being inserted.
1847 absolute Absolute path, if possible with ~ for home directory.
1848 noabbrev Absolute path, no abbreviation of home directory.
1849 adaptive Use relative path for files in the current directory and sub-
1850 directories of it. For other files, use an absolute path."
1851 :group 'org-link
1852 :type '(choice
1853 (const relative)
1854 (const absolute)
1855 (const noabbrev)
1856 (const adaptive)))
1858 (defvaralias 'org-activate-links 'org-highlight-links)
1859 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1860 "Types of links that should be highlighted in Org files.
1862 This is a list of symbols, each one of them leading to the
1863 highlighting of a certain link type.
1865 You can still open links that are not highlighted.
1867 In principle, it does not hurt to turn on highlighting for all
1868 link types. There may be a small gain when turning off unused
1869 link types. The types are:
1871 bracket The recommended [[link][description]] or [[link]] links with hiding.
1872 angle Links in angular brackets that may contain whitespace like
1873 <bbdb:Carsten Dominik>.
1874 plain Plain links in normal text, no whitespace, like http://google.com.
1875 radio Text that is matched by a radio target, see manual for details.
1876 tag Tag settings in a headline (link to tag search).
1877 date Time stamps (link to calendar).
1878 footnote Footnote labels.
1880 If you set this variable during an Emacs session, use `org-mode-restart'
1881 in the Org buffer so that the change takes effect."
1882 :group 'org-link
1883 :group 'org-appearance
1884 :type '(set :greedy t
1885 (const :tag "Double bracket links" bracket)
1886 (const :tag "Angular bracket links" angle)
1887 (const :tag "Plain text links" plain)
1888 (const :tag "Radio target matches" radio)
1889 (const :tag "Tags" tag)
1890 (const :tag "Timestamps" date)
1891 (const :tag "Footnotes" footnote)))
1893 (defcustom org-make-link-description-function nil
1894 "Function to use for generating link descriptions from links.
1895 This function must take two parameters: the first one is the
1896 link, the second one is the description generated by
1897 `org-insert-link'. The function should return the description to
1898 use."
1899 :group 'org-link
1900 :type '(choice (const nil) (function)))
1902 (defgroup org-link-store nil
1903 "Options concerning storing links in Org mode."
1904 :tag "Org Store Link"
1905 :group 'org-link)
1907 (defcustom org-url-hexify-p t
1908 "When non-nil, hexify URL when creating a link."
1909 :type 'boolean
1910 :version "24.3"
1911 :group 'org-link-store)
1913 (defcustom org-email-link-description-format "Email %c: %.30s"
1914 "Format of the description part of a link to an email or usenet message.
1915 The following %-escapes will be replaced by corresponding information:
1917 %F full \"From\" field
1918 %f name, taken from \"From\" field, address if no name
1919 %T full \"To\" field
1920 %t first name in \"To\" field, address if no name
1921 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1922 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1923 %s subject
1924 %d date
1925 %m message-id.
1927 You may use normal field width specification between the % and the letter.
1928 This is for example useful to limit the length of the subject.
1930 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1931 :group 'org-link-store
1932 :type 'string)
1934 (defcustom org-from-is-user-regexp
1935 (let (r1 r2)
1936 (when (and user-mail-address (not (string= user-mail-address "")))
1937 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1938 (when (and user-full-name (not (string= user-full-name "")))
1939 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1940 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1941 "Regexp matched against the \"From:\" header of an email or usenet message.
1942 It should match if the message is from the user him/herself."
1943 :group 'org-link-store
1944 :type 'regexp)
1946 (defcustom org-context-in-file-links t
1947 "Non-nil means file links from `org-store-link' contain context.
1948 \\<org-mode-map>
1949 A search string will be added to the file name with :: as separator
1950 and used to find the context when the link is activated by the command
1951 `org-open-at-point'. When this option is t, the entire active region
1952 will be placed in the search string of the file link. If set to a
1953 positive integer, only the first n lines of context will be stored.
1955 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1956 \\[org-store-link]')
1957 negates this setting for the duration of the command."
1958 :group 'org-link-store
1959 :type '(choice boolean integer))
1961 (defcustom org-keep-stored-link-after-insertion nil
1962 "Non-nil means keep link in list for entire session.
1963 \\<org-mode-map>
1964 The command `org-store-link' adds a link pointing to the current
1965 location to an internal list. These links accumulate during a session.
1966 The command `org-insert-link' can be used to insert links into any
1967 Org file (offering completion for all stored links).
1969 When this option is nil, every link which has been inserted once using
1970 `\\[org-insert-link]' will be removed from the list, to make completing the \
1971 unused
1972 links more efficient."
1973 :group 'org-link-store
1974 :type 'boolean)
1976 (defgroup org-link-follow nil
1977 "Options concerning following links in Org mode."
1978 :tag "Org Follow Link"
1979 :group 'org-link)
1981 (defcustom org-link-translation-function nil
1982 "Function to translate links with different syntax to Org syntax.
1983 This can be used to translate links created for example by the Planner
1984 or emacs-wiki packages to Org syntax.
1985 The function must accept two parameters, a TYPE containing the link
1986 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1987 which is everything after the link protocol. It should return a cons
1988 with possibly modified values of type and path.
1989 Org contains a function for this, so if you set this variable to
1990 `org-translate-link-from-planner', you should be able follow many
1991 links created by planner."
1992 :group 'org-link-follow
1993 :type '(choice (const nil) (function)))
1995 (defcustom org-follow-link-hook nil
1996 "Hook that is run after a link has been followed."
1997 :group 'org-link-follow
1998 :type 'hook)
2000 (defcustom org-tab-follows-link nil
2001 "Non-nil means on links TAB will follow the link.
2002 Needs to be set before org.el is loaded.
2003 This really should not be used, it does not make sense, and the
2004 implementation is bad."
2005 :group 'org-link-follow
2006 :type 'boolean)
2008 (defcustom org-return-follows-link nil
2009 "Non-nil means on links RET will follow the link.
2010 In tables, the special behavior of RET has precedence."
2011 :group 'org-link-follow
2012 :type 'boolean)
2014 (defcustom org-mouse-1-follows-link
2015 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2016 "Non-nil means mouse-1 on a link will follow the link.
2017 A longer mouse click will still set point. Needs to be set
2018 before org.el is loaded."
2019 :group 'org-link-follow
2020 :version "26.1"
2021 :package-version '(Org . "8.3")
2022 :type '(choice
2023 (const :tag "A double click follows the link" double)
2024 (const :tag "Unconditionally follow the link with mouse-1" t)
2025 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2027 (defcustom org-mark-ring-length 4
2028 "Number of different positions to be recorded in the ring.
2029 Changing this requires a restart of Emacs to work correctly."
2030 :group 'org-link-follow
2031 :type 'integer)
2033 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2034 "Non-nil means internal fuzzy links can only match headlines.
2036 When nil, the a fuzzy link may point to a target or a named
2037 construct in the document. When set to the special value
2038 `query-to-create', offer to create a new headline when none
2039 matched.
2041 Spaces and statistics cookies are ignored during heading searches."
2042 :group 'org-link-follow
2043 :version "24.1"
2044 :type '(choice
2045 (const :tag "Use fuzzy text search" nil)
2046 (const :tag "Match only exact headline" t)
2047 (const :tag "Match exact headline or query to create it"
2048 query-to-create))
2049 :safe #'symbolp)
2051 (defcustom org-link-frame-setup
2052 '((vm . vm-visit-folder-other-frame)
2053 (vm-imap . vm-visit-imap-folder-other-frame)
2054 (gnus . org-gnus-no-new-news)
2055 (file . find-file-other-window)
2056 (wl . wl-other-frame))
2057 "Setup the frame configuration for following links.
2058 When following a link with Emacs, it may often be useful to display
2059 this link in another window or frame. This variable can be used to
2060 set this up for the different types of links.
2061 For VM, use any of
2062 `vm-visit-folder'
2063 `vm-visit-folder-other-window'
2064 `vm-visit-folder-other-frame'
2065 For Gnus, use any of
2066 `gnus'
2067 `gnus-other-frame'
2068 `org-gnus-no-new-news'
2069 For FILE, use any of
2070 `find-file'
2071 `find-file-other-window'
2072 `find-file-other-frame'
2073 For Wanderlust use any of
2074 `wl'
2075 `wl-other-frame'
2076 For the calendar, use the variable `calendar-setup'.
2077 For BBDB, it is currently only possible to display the matches in
2078 another window."
2079 :group 'org-link-follow
2080 :type '(list
2081 (cons (const vm)
2082 (choice
2083 (const vm-visit-folder)
2084 (const vm-visit-folder-other-window)
2085 (const vm-visit-folder-other-frame)))
2086 (cons (const vm-imap)
2087 (choice
2088 (const vm-visit-imap-folder)
2089 (const vm-visit-imap-folder-other-window)
2090 (const vm-visit-imap-folder-other-frame)))
2091 (cons (const gnus)
2092 (choice
2093 (const gnus)
2094 (const gnus-other-frame)
2095 (const org-gnus-no-new-news)))
2096 (cons (const file)
2097 (choice
2098 (const find-file)
2099 (const find-file-other-window)
2100 (const find-file-other-frame)))
2101 (cons (const wl)
2102 (choice
2103 (const wl)
2104 (const wl-other-frame)))))
2106 (defcustom org-display-internal-link-with-indirect-buffer nil
2107 "Non-nil means use indirect buffer to display infile links.
2108 Activating internal links (from one location in a file to another location
2109 in the same file) normally just jumps to the location. When the link is
2110 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2111 is displayed in
2112 another window. When this option is set, the other window actually displays
2113 an indirect buffer clone of the current buffer, to avoid any visibility
2114 changes to the current buffer."
2115 :group 'org-link-follow
2116 :type 'boolean)
2118 (defcustom org-open-non-existing-files nil
2119 "Non-nil means `org-open-file' will open non-existing files.
2120 When nil, an error will be generated.
2121 This variable applies only to external applications because they
2122 might choke on non-existing files. If the link is to a file that
2123 will be opened in Emacs, the variable is ignored."
2124 :group 'org-link-follow
2125 :type 'boolean)
2127 (defcustom org-open-directory-means-index-dot-org nil
2128 "Non-nil means a link to a directory really means to index.org.
2129 When nil, following a directory link will run dired or open a finder/explorer
2130 window on that directory."
2131 :group 'org-link-follow
2132 :type 'boolean)
2134 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2135 "Non-nil means ask for confirmation before executing shell links.
2136 Shell links can be dangerous: just think about a link
2138 [[shell:rm -rf ~/*][Google Search]]
2140 This link would show up in your Org document as \"Google Search\",
2141 but really it would remove your entire home directory.
2142 Therefore we advise against setting this variable to nil.
2143 Just change it to `y-or-n-p' if you want to confirm with a
2144 single keystroke rather than having to type \"yes\"."
2145 :group 'org-link-follow
2146 :type '(choice
2147 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2148 (const :tag "with y-or-n (faster)" y-or-n-p)
2149 (const :tag "no confirmation (dangerous)" nil)))
2150 (put 'org-confirm-shell-link-function
2151 'safe-local-variable
2152 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2154 (defcustom org-confirm-shell-link-not-regexp ""
2155 "A regexp to skip confirmation for shell links."
2156 :group 'org-link-follow
2157 :version "24.1"
2158 :type 'regexp)
2160 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2161 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2162 Elisp links can be dangerous: just think about a link
2164 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2166 This link would show up in your Org document as \"Google Search\",
2167 but really it would remove your entire home directory.
2168 Therefore we advise against setting this variable to nil.
2169 Just change it to `y-or-n-p' if you want to confirm with a
2170 single keystroke rather than having to type \"yes\"."
2171 :group 'org-link-follow
2172 :type '(choice
2173 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2174 (const :tag "with y-or-n (faster)" y-or-n-p)
2175 (const :tag "no confirmation (dangerous)" nil)))
2176 (put 'org-confirm-shell-link-function
2177 'safe-local-variable
2178 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2180 (defcustom org-confirm-elisp-link-not-regexp ""
2181 "A regexp to skip confirmation for Elisp links."
2182 :group 'org-link-follow
2183 :version "24.1"
2184 :type 'regexp)
2186 (defconst org-file-apps-defaults-gnu
2187 '((remote . emacs)
2188 (system . mailcap)
2189 (t . mailcap))
2190 "Default file applications on a UNIX or GNU/Linux system.
2191 See `org-file-apps'.")
2193 (defconst org-file-apps-defaults-macosx
2194 '((remote . emacs)
2195 (system . "open %s")
2196 ("ps.gz" . "gv %s")
2197 ("eps.gz" . "gv %s")
2198 ("dvi" . "xdvi %s")
2199 ("fig" . "xfig %s")
2200 (t . "open %s"))
2201 "Default file applications on a macOS system.
2202 The system \"open\" is known as a default, but we use X11 applications
2203 for some files for which the OS does not have a good default.
2204 See `org-file-apps'.")
2206 (defconst org-file-apps-defaults-windowsnt
2207 (list '(remote . emacs)
2208 (cons 'system (lambda (file _path)
2209 (with-no-warnings (w32-shell-execute "open" file))))
2210 (cons t (lambda (file _path)
2211 (with-no-warnings (w32-shell-execute "open" file)))))
2212 "Default file applications on a Windows NT system.
2213 The system \"open\" is used for most files.
2214 See `org-file-apps'.")
2216 (defcustom org-file-apps
2217 '((auto-mode . emacs)
2218 ("\\.mm\\'" . default)
2219 ("\\.x?html?\\'" . default)
2220 ("\\.pdf\\'" . default))
2221 "External applications for opening `file:path' items in a document.
2222 \\<org-mode-map>\
2224 Org mode uses system defaults for different file types, but
2225 you can use this variable to set the application for a given file
2226 extension. The entries in this list are cons cells where the car identifies
2227 files and the cdr the corresponding command.
2229 Possible values for the file identifier are:
2231 \"string\" A string as a file identifier can be interpreted in different
2232 ways, depending on its contents:
2234 - Alphanumeric characters only:
2235 Match links with this file extension.
2236 Example: (\"pdf\" . \"evince %s\")
2237 to open PDFs with evince.
2239 - Regular expression: Match links where the
2240 filename matches the regexp. If you want to
2241 use groups here, use shy groups.
2243 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2244 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2245 to open *.html and *.xhtml with firefox.
2247 - Regular expression which contains (non-shy) groups:
2248 Match links where the whole link, including \"::\", and
2249 anything after that, matches the regexp.
2250 In a custom command string, %1, %2, etc. are replaced with
2251 the parts of the link that were matched by the groups.
2252 For backwards compatibility, if a command string is given
2253 that does not use any of the group matches, this case is
2254 handled identically to the second one (i.e. match against
2255 file name only).
2256 In a custom function, you can access the group matches with
2257 (match-string n link).
2259 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2260 \"evince -p %1 %s\")
2261 to open [[file:document.pdf::5]] with evince at page 5.
2263 `directory' Matches a directory
2264 `remote' Matches a remote file, accessible through tramp or efs.
2265 Remote files most likely should be visited through Emacs
2266 because external applications cannot handle such paths.
2267 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2268 so all files Emacs knows how to handle. Using this with
2269 command `emacs' will open most files in Emacs. Beware that this
2270 will also open html files inside Emacs, unless you add
2271 (\"html\" . default) to the list as well.
2272 `system' The system command to open files, like `open' on Windows
2273 and macOS, and mailcap under GNU/Linux. This is the command
2274 that will be selected if you call `org-open-at-point' with a
2275 double prefix argument (`\\[universal-argument] \
2276 \\[universal-argument] \\[org-open-at-point]').
2277 t Default for files not matched by any of the other options.
2279 Possible values for the command are:
2281 `emacs' The file will be visited by the current Emacs process.
2282 `default' Use the default application for this file type, which is the
2283 association for t in the list, most likely in the system-specific
2284 part. This can be used to overrule an unwanted setting in the
2285 system-specific variable.
2286 `system' Use the system command for opening files, like \"open\".
2287 This command is specified by the entry whose car is `system'.
2288 Most likely, the system-specific version of this variable
2289 does define this command, but you can overrule/replace it
2290 here.
2291 `mailcap' Use command specified in the mailcaps.
2292 string A command to be executed by a shell; %s will be replaced
2293 by the path to the file.
2294 function A Lisp function, which will be called with two arguments:
2295 the file path and the original link string, without the
2296 \"file:\" prefix.
2298 For more examples, see the system specific constants
2299 `org-file-apps-defaults-macosx'
2300 `org-file-apps-defaults-windowsnt'
2301 `org-file-apps-defaults-gnu'."
2302 :group 'org-link-follow
2303 :type '(repeat
2304 (cons (choice :value ""
2305 (string :tag "Extension")
2306 (const :tag "System command to open files" system)
2307 (const :tag "Default for unrecognized files" t)
2308 (const :tag "Remote file" remote)
2309 (const :tag "Links to a directory" directory)
2310 (const :tag "Any files that have Emacs modes"
2311 auto-mode))
2312 (choice :value ""
2313 (const :tag "Visit with Emacs" emacs)
2314 (const :tag "Use default" default)
2315 (const :tag "Use the system command" system)
2316 (string :tag "Command")
2317 (function :tag "Function")))))
2319 (defcustom org-doi-server-url "http://dx.doi.org/"
2320 "The URL of the DOI server."
2321 :type 'string
2322 :version "24.3"
2323 :group 'org-link-follow)
2325 (defgroup org-refile nil
2326 "Options concerning refiling entries in Org mode."
2327 :tag "Org Refile"
2328 :group 'org)
2330 (defcustom org-directory "~/org"
2331 "Directory with Org files.
2332 This is just a default location to look for Org files. There is no need
2333 at all to put your files into this directory. It is used in the
2334 following situations:
2336 1. When a capture template specifies a target file that is not an
2337 absolute path. The path will then be interpreted relative to
2338 `org-directory'
2339 2. When the value of variable `org-agenda-files' is a single file, any
2340 relative paths in this file will be taken as relative to
2341 `org-directory'."
2342 :group 'org-refile
2343 :group 'org-capture
2344 :type 'directory)
2346 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2347 "Default target for storing notes.
2348 Used as a fall back file for org-capture.el, for templates that
2349 do not specify a target file."
2350 :group 'org-refile
2351 :group 'org-capture
2352 :type 'file)
2354 (defcustom org-reverse-note-order nil
2355 "Non-nil means store new notes at the beginning of a file or entry.
2356 When nil, new notes will be filed to the end of a file or entry.
2357 This can also be a list with cons cells of regular expressions that
2358 are matched against file names, and values."
2359 :group 'org-capture
2360 :group 'org-refile
2361 :type '(choice
2362 (const :tag "Reverse always" t)
2363 (const :tag "Reverse never" nil)
2364 (repeat :tag "By file name regexp"
2365 (cons regexp boolean))))
2367 (defcustom org-log-refile nil
2368 "Information to record when a task is refiled.
2370 Possible values are:
2372 nil Don't add anything
2373 time Add a time stamp to the task
2374 note Prompt for a note and add it with template `org-log-note-headings'
2376 This option can also be set with on a per-file-basis with
2378 #+STARTUP: nologrefile
2379 #+STARTUP: logrefile
2380 #+STARTUP: lognoterefile
2382 You can have local logging settings for a subtree by setting the LOGGING
2383 property to one or more of these keywords.
2385 When bulk-refiling from the agenda, the value `note' is forbidden and
2386 will temporarily be changed to `time'."
2387 :group 'org-refile
2388 :group 'org-progress
2389 :version "24.1"
2390 :type '(choice
2391 (const :tag "No logging" nil)
2392 (const :tag "Record timestamp" time)
2393 (const :tag "Record timestamp with note." note)))
2395 (defcustom org-refile-targets nil
2396 "Targets for refiling entries with `\\[org-refile]'.
2397 This is a list of cons cells. Each cell contains:
2398 - a specification of the files to be considered, either a list of files,
2399 or a symbol whose function or variable value will be used to retrieve
2400 a file name or a list of file names. If you use `org-agenda-files' for
2401 that, all agenda files will be scanned for targets. Nil means consider
2402 headings in the current buffer.
2403 - A specification of how to find candidate refile targets. This may be
2404 any of:
2405 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2406 This tag has to be present in all target headlines, inheritance will
2407 not be considered.
2408 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2409 todo keyword.
2410 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2411 headlines that are refiling targets.
2412 - a cons cell (:level . N). Any headline of level N is considered a target.
2413 Note that, when `org-odd-levels-only' is set, level corresponds to
2414 order in hierarchy, not to the number of stars.
2415 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2416 Note that, when `org-odd-levels-only' is set, level corresponds to
2417 order in hierarchy, not to the number of stars.
2419 Each element of this list generates a set of possible targets.
2420 The union of these sets is presented (with completion) to
2421 the user by `org-refile'.
2423 You can set the variable `org-refile-target-verify-function' to a function
2424 to verify each headline found by the simple criteria above.
2426 When this variable is nil, all top-level headlines in the current buffer
2427 are used, equivalent to the value `((nil . (:level . 1))'."
2428 :group 'org-refile
2429 :type '(repeat
2430 (cons
2431 (choice :value org-agenda-files
2432 (const :tag "All agenda files" org-agenda-files)
2433 (const :tag "Current buffer" nil)
2434 (function) (variable) (file))
2435 (choice :tag "Identify target headline by"
2436 (cons :tag "Specific tag" (const :value :tag) (string))
2437 (cons :tag "TODO keyword" (const :value :todo) (string))
2438 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2439 (cons :tag "Level number" (const :value :level) (integer))
2440 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2442 (defcustom org-refile-target-verify-function nil
2443 "Function to verify if the headline at point should be a refile target.
2444 The function will be called without arguments, with point at the
2445 beginning of the headline. It should return t and leave point
2446 where it is if the headline is a valid target for refiling.
2448 If the target should not be selected, the function must return nil.
2449 In addition to this, it may move point to a place from where the search
2450 should be continued. For example, the function may decide that the entire
2451 subtree of the current entry should be excluded and move point to the end
2452 of the subtree."
2453 :group 'org-refile
2454 :type '(choice
2455 (const nil)
2456 (function)))
2458 (defcustom org-refile-use-cache nil
2459 "Non-nil means cache refile targets to speed up the process.
2460 \\<org-mode-map>\
2461 The cache for a particular file will be updated automatically when
2462 the buffer has been killed, or when any of the marker used for flagging
2463 refile targets no longer points at a live buffer.
2464 If you have added new entries to a buffer that might themselves be targets,
2465 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2466 if you find that easier, \
2467 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2468 \\[org-refile]'."
2469 :group 'org-refile
2470 :version "24.1"
2471 :type 'boolean)
2473 (defcustom org-refile-use-outline-path nil
2474 "Non-nil means provide refile targets as paths.
2475 So a level 3 headline will be available as level1/level2/level3.
2477 When the value is `file', also include the file name (without directory)
2478 into the path. In this case, you can also stop the completion after
2479 the file name, to get entries inserted as top level in the file.
2481 When `full-file-path', include the full file path.
2483 When `buffer-name', use the buffer name."
2484 :group 'org-refile
2485 :type '(choice
2486 (const :tag "Not" nil)
2487 (const :tag "Yes" t)
2488 (const :tag "Start with file name" file)
2489 (const :tag "Start with full file path" full-file-path)
2490 (const :tag "Start with buffer name" buffer-name)))
2492 (defcustom org-outline-path-complete-in-steps t
2493 "Non-nil means complete the outline path in hierarchical steps.
2494 When Org uses the refile interface to select an outline path (see
2495 `org-refile-use-outline-path'), the completion of the path can be
2496 done in a single go, or it can be done in steps down the headline
2497 hierarchy. Going in steps is probably the best if you do not use
2498 a special completion package like `ido' or `icicles'. However,
2499 when using these packages, going in one step can be very fast,
2500 while still showing the whole path to the entry."
2501 :group 'org-refile
2502 :type 'boolean)
2504 (defcustom org-refile-allow-creating-parent-nodes nil
2505 "Non-nil means allow the creation of new nodes as refile targets.
2506 New nodes are then created by adding \"/new node name\" to the completion
2507 of an existing node. When the value of this variable is `confirm',
2508 new node creation must be confirmed by the user (recommended).
2509 When nil, the completion must match an existing entry.
2511 Note that, if the new heading is not seen by the criteria
2512 listed in `org-refile-targets', multiple instances of the same
2513 heading would be created by trying again to file under the new
2514 heading."
2515 :group 'org-refile
2516 :type '(choice
2517 (const :tag "Never" nil)
2518 (const :tag "Always" t)
2519 (const :tag "Prompt for confirmation" confirm)))
2521 (defcustom org-refile-active-region-within-subtree nil
2522 "Non-nil means also refile active region within a subtree.
2524 By default `org-refile' doesn't allow refiling regions if they
2525 don't contain a set of subtrees, but it might be convenient to
2526 do so sometimes: in that case, the first line of the region is
2527 converted to a headline before refiling."
2528 :group 'org-refile
2529 :version "24.1"
2530 :type 'boolean)
2532 (defgroup org-todo nil
2533 "Options concerning TODO items in Org mode."
2534 :tag "Org TODO"
2535 :group 'org)
2537 (defgroup org-progress nil
2538 "Options concerning Progress logging in Org mode."
2539 :tag "Org Progress"
2540 :group 'org-time)
2542 (defvar org-todo-interpretation-widgets
2543 '((:tag "Sequence (cycling hits every state)" sequence)
2544 (:tag "Type (cycling directly to DONE)" type))
2545 "The available interpretation symbols for customizing `org-todo-keywords'.
2546 Interested libraries should add to this list.")
2548 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2549 "List of TODO entry keyword sequences and their interpretation.
2550 \\<org-mode-map>This is a list of sequences.
2552 Each sequence starts with a symbol, either `sequence' or `type',
2553 indicating if the keywords should be interpreted as a sequence of
2554 action steps, or as different types of TODO items. The first
2555 keywords are states requiring action - these states will select a headline
2556 for inclusion into the global TODO list Org produces. If one of the
2557 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2558 signify that no further action is necessary. If \"|\" is not found,
2559 the last keyword is treated as the only DONE state of the sequence.
2561 The command `\\[org-todo]' cycles an entry through these states, and one
2562 additional state where no keyword is present. For details about this
2563 cycling, see the manual.
2565 TODO keywords and interpretation can also be set on a per-file basis with
2566 the special #+SEQ_TODO and #+TYP_TODO lines.
2568 Each keyword can optionally specify a character for fast state selection
2569 \(in combination with the variable `org-use-fast-todo-selection')
2570 and specifiers for state change logging, using the same syntax that
2571 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2572 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2573 indicates to record a time stamp each time this state is selected.
2575 Each keyword may also specify if a timestamp or a note should be
2576 recorded when entering or leaving the state, by adding additional
2577 characters in the parenthesis after the keyword. This looks like this:
2578 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2579 record only the time of the state change. With X and Y being either
2580 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2581 Y when leaving the state if and only if the *target* state does not
2582 define X. You may omit any of the fast-selection key or X or /Y,
2583 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2585 For backward compatibility, this variable may also be just a list
2586 of keywords. In this case the interpretation (sequence or type) will be
2587 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2588 :group 'org-todo
2589 :group 'org-keywords
2590 :type '(choice
2591 (repeat :tag "Old syntax, just keywords"
2592 (string :tag "Keyword"))
2593 (repeat :tag "New syntax"
2594 (cons
2595 (choice
2596 :tag "Interpretation"
2597 ;;Quick and dirty way to see
2598 ;;`org-todo-interpretations'. This takes the
2599 ;;place of item arguments
2600 :convert-widget
2601 (lambda (widget)
2602 (widget-put widget
2603 :args (mapcar
2604 (lambda (x)
2605 (widget-convert
2606 (cons 'const x)))
2607 org-todo-interpretation-widgets))
2608 widget))
2609 (repeat
2610 (string :tag "Keyword"))))))
2612 (defvar-local org-todo-keywords-1 nil
2613 "All TODO and DONE keywords active in a buffer.")
2614 (defvar org-todo-keywords-for-agenda nil)
2615 (defvar org-done-keywords-for-agenda nil)
2616 (defvar org-todo-keyword-alist-for-agenda nil)
2617 (defvar org-tag-alist-for-agenda nil
2618 "Alist of all tags from all agenda files.")
2619 (defvar org-tag-groups-alist-for-agenda nil
2620 "Alist of all groups tags from all current agenda files.")
2621 (defvar-local org-tag-groups-alist nil)
2622 (defvar org-agenda-contributing-files nil)
2623 (defvar-local org-current-tag-alist nil
2624 "Alist of all tag groups in current buffer.
2625 This variable takes into consideration `org-tag-alist',
2626 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2627 (defvar-local org-not-done-keywords nil)
2628 (defvar-local org-done-keywords nil)
2629 (defvar-local org-todo-heads nil)
2630 (defvar-local org-todo-sets nil)
2631 (defvar-local org-todo-log-states nil)
2632 (defvar-local org-todo-kwd-alist nil)
2633 (defvar-local org-todo-key-alist nil)
2634 (defvar-local org-todo-key-trigger nil)
2636 (defcustom org-todo-interpretation 'sequence
2637 "Controls how TODO keywords are interpreted.
2638 This variable is in principle obsolete and is only used for
2639 backward compatibility, if the interpretation of todo keywords is
2640 not given already in `org-todo-keywords'. See that variable for
2641 more information."
2642 :group 'org-todo
2643 :group 'org-keywords
2644 :type '(choice (const sequence)
2645 (const type)))
2647 (defcustom org-use-fast-todo-selection t
2648 "\\<org-mode-map>\
2649 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2650 This variable describes if and under what circumstances the cycling
2651 mechanism for TODO keywords will be replaced by a single-key, direct
2652 selection scheme.
2654 When nil, fast selection is never used.
2656 When the symbol `prefix', it will be used when `org-todo' is called
2657 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2658 in an Org buffer, and
2659 `\\[universal-argument] t' in an agenda buffer.
2661 When t, fast selection is used by default. In this case, the prefix
2662 argument forces cycling instead.
2664 In all cases, the special interface is only used if access keys have
2665 actually been assigned by the user, i.e. if keywords in the configuration
2666 are followed by a letter in parenthesis, like TODO(t)."
2667 :group 'org-todo
2668 :type '(choice
2669 (const :tag "Never" nil)
2670 (const :tag "By default" t)
2671 (const :tag "Only with C-u C-c C-t" prefix)))
2673 (defcustom org-provide-todo-statistics t
2674 "Non-nil means update todo statistics after insert and toggle.
2675 ALL-HEADLINES means update todo statistics by including headlines
2676 with no TODO keyword as well, counting them as not done.
2677 A list of TODO keywords means the same, but skip keywords that are
2678 not in this list.
2679 When set to a list of two lists, the first list contains keywords
2680 to consider as TODO keywords, the second list contains keywords
2681 to consider as DONE keywords.
2683 When this is set, todo statistics is updated in the parent of the
2684 current entry each time a todo state is changed."
2685 :group 'org-todo
2686 :type '(choice
2687 (const :tag "Yes, only for TODO entries" t)
2688 (const :tag "Yes, including all entries" all-headlines)
2689 (repeat :tag "Yes, for TODOs in this list"
2690 (string :tag "TODO keyword"))
2691 (list :tag "Yes, for TODOs and DONEs in these lists"
2692 (repeat (string :tag "TODO keyword"))
2693 (repeat (string :tag "DONE keyword")))
2694 (other :tag "No TODO statistics" nil)))
2696 (defcustom org-hierarchical-todo-statistics t
2697 "Non-nil means TODO statistics covers just direct children.
2698 When nil, all entries in the subtree are considered.
2699 This has only an effect if `org-provide-todo-statistics' is set.
2700 To set this to nil for only a single subtree, use a COOKIE_DATA
2701 property and include the word \"recursive\" into the value."
2702 :group 'org-todo
2703 :type 'boolean)
2705 (defcustom org-after-todo-state-change-hook nil
2706 "Hook which is run after the state of a TODO item was changed.
2707 The new state (a string with a TODO keyword, or nil) is available in the
2708 Lisp variable `org-state'."
2709 :group 'org-todo
2710 :type 'hook)
2712 (defvar org-blocker-hook nil
2713 "Hook for functions that are allowed to block a state change.
2715 Functions in this hook should not modify the buffer.
2716 Each function gets as its single argument a property list,
2717 see `org-trigger-hook' for more information about this list.
2719 If any of the functions in this hook returns nil, the state change
2720 is blocked.")
2722 (defvar org-trigger-hook nil
2723 "Hook for functions that are triggered by a state change.
2725 Each function gets as its single argument a property list with at
2726 least the following elements:
2728 (:type type-of-change :position pos-at-entry-start
2729 :from old-state :to new-state)
2731 Depending on the type, more properties may be present.
2733 This mechanism is currently implemented for:
2735 TODO state changes
2736 ------------------
2737 :type todo-state-change
2738 :from previous state (keyword as a string), or nil, or a symbol
2739 `todo' or `done', to indicate the general type of state.
2740 :to new state, like in :from")
2742 (defcustom org-enforce-todo-dependencies nil
2743 "Non-nil means undone TODO entries will block switching the parent to DONE.
2744 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2745 be blocked if any prior sibling is not yet done.
2746 Finally, if the parent is blocked because of ordered siblings of its own,
2747 the child will also be blocked."
2748 :set (lambda (var val)
2749 (set var val)
2750 (if val
2751 (add-hook 'org-blocker-hook
2752 'org-block-todo-from-children-or-siblings-or-parent)
2753 (remove-hook 'org-blocker-hook
2754 'org-block-todo-from-children-or-siblings-or-parent)))
2755 :group 'org-todo
2756 :type 'boolean)
2758 (defcustom org-enforce-todo-checkbox-dependencies nil
2759 "Non-nil means unchecked boxes will block switching the parent to DONE.
2760 When this is nil, checkboxes have no influence on switching TODO states.
2761 When non-nil, you first need to check off all check boxes before the TODO
2762 entry can be switched to DONE.
2763 This variable needs to be set before org.el is loaded, and you need to
2764 restart Emacs after a change to make the change effective. The only way
2765 to change is while Emacs is running is through the customize interface."
2766 :set (lambda (var val)
2767 (set var val)
2768 (if val
2769 (add-hook 'org-blocker-hook
2770 'org-block-todo-from-checkboxes)
2771 (remove-hook 'org-blocker-hook
2772 'org-block-todo-from-checkboxes)))
2773 :group 'org-todo
2774 :type 'boolean)
2776 (defcustom org-treat-insert-todo-heading-as-state-change nil
2777 "Non-nil means inserting a TODO heading is treated as state change.
2778 So when the command `\\[org-insert-todo-heading]' is used, state change
2779 logging will apply if appropriate. When nil, the new TODO item will
2780 be inserted directly, and no logging will take place."
2781 :group 'org-todo
2782 :type 'boolean)
2784 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2785 "Non-nil means switching TODO states with S-cursor counts as state change.
2786 This is the default behavior. However, setting this to nil allows a
2787 convenient way to select a TODO state and bypass any logging associated
2788 with that."
2789 :group 'org-todo
2790 :type 'boolean)
2792 (defcustom org-todo-state-tags-triggers nil
2793 "Tag changes that should be triggered by TODO state changes.
2794 This is a list. Each entry is
2796 (state-change (tag . flag) .......)
2798 State-change can be a string with a state, and empty string to indicate the
2799 state that has no TODO keyword, or it can be one of the symbols `todo'
2800 or `done', meaning any not-done or done state, respectively."
2801 :group 'org-todo
2802 :group 'org-tags
2803 :type '(repeat
2804 (cons (choice :tag "When changing to"
2805 (const :tag "Not-done state" todo)
2806 (const :tag "Done state" done)
2807 (string :tag "State"))
2808 (repeat
2809 (cons :tag "Tag action"
2810 (string :tag "Tag")
2811 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2813 (defcustom org-log-done nil
2814 "Information to record when a task moves to the DONE state.
2816 Possible values are:
2818 nil Don't add anything, just change the keyword
2819 time Add a time stamp to the task
2820 note Prompt for a note and add it with template `org-log-note-headings'
2822 This option can also be set with on a per-file-basis with
2824 #+STARTUP: nologdone
2825 #+STARTUP: logdone
2826 #+STARTUP: lognotedone
2828 You can have local logging settings for a subtree by setting the LOGGING
2829 property to one or more of these keywords."
2830 :group 'org-todo
2831 :group 'org-progress
2832 :type '(choice
2833 (const :tag "No logging" nil)
2834 (const :tag "Record CLOSED timestamp" time)
2835 (const :tag "Record CLOSED timestamp with note." note)))
2837 ;; Normalize old uses of org-log-done.
2838 (cond
2839 ((eq org-log-done t) (setq org-log-done 'time))
2840 ((and (listp org-log-done) (memq 'done org-log-done))
2841 (setq org-log-done 'note)))
2843 (defcustom org-log-reschedule nil
2844 "Information to record when the scheduling date of a tasks is modified.
2846 Possible values are:
2848 nil Don't add anything, just change the date
2849 time Add a time stamp to the task
2850 note Prompt for a note and add it with template `org-log-note-headings'
2852 This option can also be set with on a per-file-basis with
2854 #+STARTUP: nologreschedule
2855 #+STARTUP: logreschedule
2856 #+STARTUP: lognotereschedule"
2857 :group 'org-todo
2858 :group 'org-progress
2859 :type '(choice
2860 (const :tag "No logging" nil)
2861 (const :tag "Record timestamp" time)
2862 (const :tag "Record timestamp with note." note)))
2864 (defcustom org-log-redeadline nil
2865 "Information to record when the deadline date of a tasks is modified.
2867 Possible values are:
2869 nil Don't add anything, just change the date
2870 time Add a time stamp to the task
2871 note Prompt for a note and add it with template `org-log-note-headings'
2873 This option can also be set with on a per-file-basis with
2875 #+STARTUP: nologredeadline
2876 #+STARTUP: logredeadline
2877 #+STARTUP: lognoteredeadline
2879 You can have local logging settings for a subtree by setting the LOGGING
2880 property to one or more of these keywords."
2881 :group 'org-todo
2882 :group 'org-progress
2883 :type '(choice
2884 (const :tag "No logging" nil)
2885 (const :tag "Record timestamp" time)
2886 (const :tag "Record timestamp with note." note)))
2888 (defcustom org-log-note-clock-out nil
2889 "Non-nil means record a note when clocking out of an item.
2890 This can also be configured on a per-file basis by adding one of
2891 the following lines anywhere in the buffer:
2893 #+STARTUP: lognoteclock-out
2894 #+STARTUP: nolognoteclock-out"
2895 :group 'org-todo
2896 :group 'org-progress
2897 :type 'boolean)
2899 (defcustom org-log-done-with-time t
2900 "Non-nil means the CLOSED time stamp will contain date and time.
2901 When nil, only the date will be recorded."
2902 :group 'org-progress
2903 :type 'boolean)
2905 (defcustom org-log-note-headings
2906 '((done . "CLOSING NOTE %t")
2907 (state . "State %-12s from %-12S %t")
2908 (note . "Note taken on %t")
2909 (reschedule . "Rescheduled from %S on %t")
2910 (delschedule . "Not scheduled, was %S on %t")
2911 (redeadline . "New deadline from %S on %t")
2912 (deldeadline . "Removed deadline, was %S on %t")
2913 (refile . "Refiled on %t")
2914 (clock-out . ""))
2915 "Headings for notes added to entries.
2917 The value is an alist, with the car being a symbol indicating the
2918 note context, and the cdr is the heading to be used. The heading
2919 may also be the empty string. The following placeholders can be
2920 used:
2922 %t a time stamp.
2923 %T an active time stamp instead the default inactive one
2924 %d a short-format time stamp.
2925 %D an active short-format time stamp.
2926 %s the new TODO state or time stamp (inactive), in double quotes.
2927 %S the old TODO state or time stamp (inactive), in double quotes.
2928 %u the user name.
2929 %U full user name.
2931 In fact, it is not a good idea to change the `state' entry,
2932 because Agenda Log mode depends on the format of these entries."
2933 :group 'org-todo
2934 :group 'org-progress
2935 :type '(list :greedy t
2936 (cons (const :tag "Heading when closing an item" done) string)
2937 (cons (const :tag
2938 "Heading when changing todo state (todo sequence only)"
2939 state) string)
2940 (cons (const :tag "Heading when just taking a note" note) string)
2941 (cons (const :tag "Heading when rescheduling" reschedule) string)
2942 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2943 (cons (const :tag "Heading when changing deadline" redeadline) string)
2944 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2945 (cons (const :tag "Heading when refiling" refile) string)
2946 (cons (const :tag "Heading when clocking out" clock-out) string)))
2948 (unless (assq 'note org-log-note-headings)
2949 (push '(note . "%t") org-log-note-headings))
2951 (defcustom org-log-into-drawer nil
2952 "Non-nil means insert state change notes and time stamps into a drawer.
2953 When nil, state changes notes will be inserted after the headline and
2954 any scheduling and clock lines, but not inside a drawer.
2956 The value of this variable should be the name of the drawer to use.
2957 LOGBOOK is proposed as the default drawer for this purpose, you can
2958 also set this to a string to define the drawer of your choice.
2960 A value of t is also allowed, representing \"LOGBOOK\".
2962 A value of t or nil can also be set with on a per-file-basis with
2964 #+STARTUP: logdrawer
2965 #+STARTUP: nologdrawer
2967 If this variable is set, `org-log-state-notes-insert-after-drawers'
2968 will be ignored.
2970 You can set the property LOG_INTO_DRAWER to overrule this setting for
2971 a subtree.
2973 Do not check directly this variable in a Lisp program. Call
2974 function `org-log-into-drawer' instead."
2975 :group 'org-todo
2976 :group 'org-progress
2977 :type '(choice
2978 (const :tag "Not into a drawer" nil)
2979 (const :tag "LOGBOOK" t)
2980 (string :tag "Other")))
2982 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2984 (defun org-log-into-drawer ()
2985 "Name of the log drawer, as a string, or nil.
2986 This is the value of `org-log-into-drawer'. However, if the
2987 current entry has or inherits a LOG_INTO_DRAWER property, it will
2988 be used instead of the default value."
2989 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2990 (cond ((equal p "nil") nil)
2991 ((equal p "t") "LOGBOOK")
2992 ((stringp p) p)
2993 (p "LOGBOOK")
2994 ((stringp org-log-into-drawer) org-log-into-drawer)
2995 (org-log-into-drawer "LOGBOOK"))))
2997 (defcustom org-log-state-notes-insert-after-drawers nil
2998 "Non-nil means insert state change notes after any drawers in entry.
2999 Only the drawers that *immediately* follow the headline and the
3000 deadline/scheduled line are skipped.
3001 When nil, insert notes right after the heading and perhaps the line
3002 with deadline/scheduling if present.
3004 This variable will have no effect if `org-log-into-drawer' is
3005 set."
3006 :group 'org-todo
3007 :group 'org-progress
3008 :type 'boolean)
3010 (defcustom org-log-states-order-reversed t
3011 "Non-nil means the latest state note will be directly after heading.
3012 When nil, the state change notes will be ordered according to time.
3014 This option can also be set with on a per-file-basis with
3016 #+STARTUP: logstatesreversed
3017 #+STARTUP: nologstatesreversed"
3018 :group 'org-todo
3019 :group 'org-progress
3020 :type 'boolean)
3022 (defcustom org-todo-repeat-to-state nil
3023 "The TODO state to which a repeater should return the repeating task.
3024 By default this is the first task of a TODO sequence or the
3025 previous state of a TYPE_TODO set. But you can specify to use
3026 the previous state in a TODO sequence or a string.
3028 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3029 entry, which has precedence over this option."
3030 :group 'org-todo
3031 :version "24.1"
3032 :type '(choice (const :tag "Use the previous TODO state" t)
3033 (const :tag "Use the head of the TODO sequence" nil)
3034 (string :tag "Use a specific TODO state")))
3036 (defcustom org-log-repeat 'time
3037 "Non-nil means record moving through the DONE state when triggering repeat.
3038 An auto-repeating task is immediately switched back to TODO when
3039 marked DONE. If you are not logging state changes (by adding \"@\"
3040 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3041 record a closing note, there will be no record of the task moving
3042 through DONE. This variable forces taking a note anyway.
3044 nil Don't force a record
3045 time Record a time stamp
3046 note Prompt for a note and add it with template `org-log-note-headings'
3048 This option can also be set with on a per-file-basis with
3050 #+STARTUP: nologrepeat
3051 #+STARTUP: logrepeat
3052 #+STARTUP: lognoterepeat
3054 You can have local logging settings for a subtree by setting the LOGGING
3055 property to one or more of these keywords."
3056 :group 'org-todo
3057 :group 'org-progress
3058 :type '(choice
3059 (const :tag "Don't force a record" nil)
3060 (const :tag "Force recording the DONE state" time)
3061 (const :tag "Force recording a note with the DONE state" note)))
3064 (defgroup org-priorities nil
3065 "Priorities in Org mode."
3066 :tag "Org Priorities"
3067 :group 'org-todo)
3069 (defcustom org-enable-priority-commands t
3070 "Non-nil means priority commands are active.
3071 When nil, these commands will be disabled, so that you never accidentally
3072 set a priority."
3073 :group 'org-priorities
3074 :type 'boolean)
3076 (defcustom org-highest-priority ?A
3077 "The highest priority of TODO items. A character like ?A, ?B etc.
3078 Must have a smaller ASCII number than `org-lowest-priority'."
3079 :group 'org-priorities
3080 :type 'character)
3082 (defcustom org-lowest-priority ?C
3083 "The lowest priority of TODO items. A character like ?A, ?B etc.
3084 Must have a larger ASCII number than `org-highest-priority'."
3085 :group 'org-priorities
3086 :type 'character)
3088 (defcustom org-default-priority ?B
3089 "The default priority of TODO items.
3090 This is the priority an item gets if no explicit priority is given.
3091 When starting to cycle on an empty priority the first step in the cycle
3092 depends on `org-priority-start-cycle-with-default'. The resulting first
3093 step priority must not exceed the range from `org-highest-priority' to
3094 `org-lowest-priority' which means that `org-default-priority' has to be
3095 in this range exclusive or inclusive the range boundaries. Else the
3096 first step refuses to set the default and the second will fall back
3097 to (depending on the command used) the highest or lowest priority."
3098 :group 'org-priorities
3099 :type 'character)
3101 (defcustom org-priority-start-cycle-with-default t
3102 "Non-nil means start with default priority when starting to cycle.
3103 When this is nil, the first step in the cycle will be (depending on the
3104 command used) one higher or lower than the default priority.
3105 See also `org-default-priority'."
3106 :group 'org-priorities
3107 :type 'boolean)
3109 (defcustom org-get-priority-function nil
3110 "Function to extract the priority from a string.
3111 The string is normally the headline. If this is nil Org computes the
3112 priority from the priority cookie like [#A] in the headline. It returns
3113 an integer, increasing by 1000 for each priority level.
3114 The user can set a different function here, which should take a string
3115 as an argument and return the numeric priority."
3116 :group 'org-priorities
3117 :version "24.1"
3118 :type '(choice
3119 (const nil)
3120 (function)))
3122 (defgroup org-time nil
3123 "Options concerning time stamps and deadlines in Org mode."
3124 :tag "Org Time"
3125 :group 'org)
3127 (defcustom org-time-stamp-rounding-minutes '(0 5)
3128 "Number of minutes to round time stamps to.
3129 \\<org-mode-map>\
3130 These are two values, the first applies when first creating a time stamp.
3131 The second applies when changing it with the commands `S-up' and `S-down'.
3132 When changing the time stamp, this means that it will change in steps
3133 of N minutes, as given by the second value.
3135 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3136 numbers should be factors of 60, so for example 5, 10, 15.
3138 When this is larger than 1, you can still force an exact time stamp by using
3139 a double prefix argument to a time stamp command like \
3140 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3141 and by using a prefix arg to `S-up/down' to specify the exact number
3142 of minutes to shift."
3143 :group 'org-time
3144 :get (lambda (var) ; Make sure both elements are there
3145 (if (integerp (default-value var))
3146 (list (default-value var) 5)
3147 (default-value var)))
3148 :type '(list
3149 (integer :tag "when inserting times")
3150 (integer :tag "when modifying times")))
3152 ;; Normalize old customizations of this variable.
3153 (when (integerp org-time-stamp-rounding-minutes)
3154 (setq org-time-stamp-rounding-minutes
3155 (list org-time-stamp-rounding-minutes
3156 org-time-stamp-rounding-minutes)))
3158 (defcustom org-display-custom-times nil
3159 "Non-nil means overlay custom formats over all time stamps.
3160 The formats are defined through the variable `org-time-stamp-custom-formats'.
3161 To turn this on on a per-file basis, insert anywhere in the file:
3162 #+STARTUP: customtime"
3163 :group 'org-time
3164 :set 'set-default
3165 :type 'sexp)
3166 (make-variable-buffer-local 'org-display-custom-times)
3168 (defcustom org-time-stamp-custom-formats
3169 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3170 "Custom formats for time stamps. See `format-time-string' for the syntax.
3171 These are overlaid over the default ISO format if the variable
3172 `org-display-custom-times' is set. Time like %H:%M should be at the
3173 end of the second format. The custom formats are also honored by export
3174 commands, if custom time display is turned on at the time of export."
3175 :group 'org-time
3176 :type 'sexp)
3178 (defun org-time-stamp-format (&optional long inactive)
3179 "Get the right format for a time string."
3180 (let ((f (if long (cdr org-time-stamp-formats)
3181 (car org-time-stamp-formats))))
3182 (if inactive
3183 (concat "[" (substring f 1 -1) "]")
3184 f)))
3186 (defcustom org-deadline-warning-days 14
3187 "Number of days before expiration during which a deadline becomes active.
3188 This variable governs the display in sparse trees and in the agenda.
3189 When 0 or negative, it means use this number (the absolute value of it)
3190 even if a deadline has a different individual lead time specified.
3192 Custom commands can set this variable in the options section."
3193 :group 'org-time
3194 :group 'org-agenda-daily/weekly
3195 :type 'integer)
3197 (defcustom org-scheduled-delay-days 0
3198 "Number of days before a scheduled item becomes active.
3199 This variable governs the display in sparse trees and in the agenda.
3200 The default value (i.e. 0) means: don't delay scheduled item.
3201 When negative, it means use this number (the absolute value of it)
3202 even if a scheduled item has a different individual delay time
3203 specified.
3205 Custom commands can set this variable in the options section."
3206 :group 'org-time
3207 :group 'org-agenda-daily/weekly
3208 :version "24.4"
3209 :package-version '(Org . "8.0")
3210 :type 'integer)
3212 (defcustom org-read-date-prefer-future t
3213 "Non-nil means assume future for incomplete date input from user.
3214 This affects the following situations:
3215 1. The user gives a month but not a year.
3216 For example, if it is April and you enter \"feb 2\", this will be read
3217 as Feb 2, *next* year. \"May 5\", however, will be this year.
3218 2. The user gives a day, but no month.
3219 For example, if today is the 15th, and you enter \"3\", Org will read
3220 this as the third of *next* month. However, if you enter \"17\",
3221 it will be considered as *this* month.
3223 If you set this variable to the symbol `time', then also the following
3224 will work:
3226 3. If the user gives a time.
3227 If the time is before now, it will be interpreted as tomorrow.
3229 Currently none of this works for ISO week specifications.
3231 When this option is nil, the current day, month and year will always be
3232 used as defaults.
3234 See also `org-agenda-jump-prefer-future'."
3235 :group 'org-time
3236 :type '(choice
3237 (const :tag "Never" nil)
3238 (const :tag "Check month and day" t)
3239 (const :tag "Check month, day, and time" time)))
3241 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3242 "Should the agenda jump command prefer the future for incomplete dates?
3243 The default is to do the same as configured in `org-read-date-prefer-future'.
3244 But you can also set a deviating value here.
3245 This may t or nil, or the symbol `org-read-date-prefer-future'."
3246 :group 'org-agenda
3247 :group 'org-time
3248 :version "24.1"
3249 :type '(choice
3250 (const :tag "Use org-read-date-prefer-future"
3251 org-read-date-prefer-future)
3252 (const :tag "Never" nil)
3253 (const :tag "Always" t)))
3255 (defcustom org-read-date-force-compatible-dates t
3256 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3258 Depending on the system Emacs is running on, certain dates cannot
3259 be represented with the type used internally to represent time.
3260 Dates between 1970-1-1 and 2038-1-1 can always be represented
3261 correctly. Some systems allow for earlier dates, some for later,
3262 some for both. One way to find out it to insert any date into an
3263 Org buffer, putting the cursor on the year and hitting S-up and
3264 S-down to test the range.
3266 When this variable is set to t, the date/time prompt will not let
3267 you specify dates outside the 1970-2037 range, so it is certain that
3268 these dates will work in whatever version of Emacs you are
3269 running, and also that you can move a file from one Emacs implementation
3270 to another. WHenever Org is forcing the year for you, it will display
3271 a message and beep.
3273 When this variable is nil, Org will check if the date is
3274 representable in the specific Emacs implementation you are using.
3275 If not, it will force a year, usually the current year, and beep
3276 to remind you. Currently this setting is not recommended because
3277 the likelihood that you will open your Org files in an Emacs that
3278 has limited date range is not negligible.
3280 A workaround for this problem is to use diary sexp dates for time
3281 stamps outside of this range."
3282 :group 'org-time
3283 :version "24.1"
3284 :type 'boolean)
3286 (defcustom org-read-date-display-live t
3287 "Non-nil means display current interpretation of date prompt live.
3288 This display will be in an overlay, in the minibuffer."
3289 :group 'org-time
3290 :type 'boolean)
3292 (defcustom org-read-date-popup-calendar t
3293 "Non-nil means pop up a calendar when prompting for a date.
3294 In the calendar, the date can be selected with mouse-1. However, the
3295 minibuffer will also be active, and you can simply enter the date as well.
3296 When nil, only the minibuffer will be available."
3297 :group 'org-time
3298 :type 'boolean)
3299 (defvaralias 'org-popup-calendar-for-date-prompt
3300 'org-read-date-popup-calendar)
3302 (defcustom org-extend-today-until 0
3303 "The hour when your day really ends. Must be an integer.
3304 This has influence for the following applications:
3305 - When switching the agenda to \"today\". It it is still earlier than
3306 the time given here, the day recognized as TODAY is actually yesterday.
3307 - When a date is read from the user and it is still before the time given
3308 here, the current date and time will be assumed to be yesterday, 23:59.
3309 Also, timestamps inserted in capture templates follow this rule.
3311 IMPORTANT: This is a feature whose implementation is and likely will
3312 remain incomplete. Really, it is only here because past midnight seems to
3313 be the favorite working time of John Wiegley :-)"
3314 :group 'org-time
3315 :type 'integer)
3317 (defcustom org-use-effective-time nil
3318 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3319 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3320 \"effective time\" of any timestamps between midnight and 8am will be
3321 23:59 of the previous day."
3322 :group 'org-time
3323 :version "24.1"
3324 :type 'boolean)
3326 (defcustom org-use-last-clock-out-time-as-effective-time nil
3327 "When non-nil, use the last clock out time for `org-todo'.
3328 Note that this option has precedence over the combined use of
3329 `org-use-effective-time' and `org-extend-today-until'."
3330 :group 'org-time
3331 :version "24.4"
3332 :package-version '(Org . "8.0")
3333 :type 'boolean)
3335 (defcustom org-edit-timestamp-down-means-later nil
3336 "Non-nil means S-down will increase the time in a time stamp.
3337 When nil, S-up will increase."
3338 :group 'org-time
3339 :type 'boolean)
3341 (defcustom org-calendar-follow-timestamp-change t
3342 "Non-nil means make the calendar window follow timestamp changes.
3343 When a timestamp is modified and the calendar window is visible, it will be
3344 moved to the new date."
3345 :group 'org-time
3346 :type 'boolean)
3348 (defgroup org-tags nil
3349 "Options concerning tags in Org mode."
3350 :tag "Org Tags"
3351 :group 'org)
3353 (defcustom org-tag-alist nil
3354 "Default tags available in Org files.
3356 The value of this variable is an alist. Associations either:
3358 (TAG)
3359 (TAG . SELECT)
3360 (SPECIAL)
3362 where TAG is a tag as a string, SELECT is character, used to
3363 select that tag through the fast tag selection interface, and
3364 SPECIAL is one of the following keywords: `:startgroup',
3365 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3366 `:newline'. These keywords are used to define a hierarchy of
3367 tags. See manual for details.
3369 When this variable is nil, Org mode bases tag input on what is
3370 already in the buffer. The value can be overridden locally by
3371 using a TAGS keyword, e.g.,
3373 #+TAGS: tag1 tag2
3375 See also `org-tag-persistent-alist' to sidestep this behavior."
3376 :group 'org-tags
3377 :type '(repeat
3378 (choice
3379 (cons :tag "Tag with key"
3380 (string :tag "Tag name")
3381 (character :tag "Access char"))
3382 (list :tag "Tag" (string :tag "Tag name"))
3383 (const :tag "Start radio group" (:startgroup))
3384 (const :tag "Start tag group, non distinct" (:startgrouptag))
3385 (const :tag "Group tags delimiter" (:grouptags))
3386 (const :tag "End radio group" (:endgroup))
3387 (const :tag "End tag group, non distinct" (:endgrouptag))
3388 (const :tag "New line" (:newline)))))
3390 (defcustom org-tag-persistent-alist nil
3391 "Tags always available in Org files.
3393 The value of this variable is an alist. Associations either:
3395 (TAG)
3396 (TAG . SELECT)
3397 (SPECIAL)
3399 where TAG is a tag as a string, SELECT is a character, used to
3400 select that tag through the fast tag selection interface, and
3401 SPECIAL is one of the following keywords: `:startgroup',
3402 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3403 `:newline'. These keywords are used to define a hierarchy of
3404 tags. See manual for details.
3406 Unlike to `org-tag-alist', tags defined in this variable do not
3407 depend on a local TAGS keyword. Instead, to disable these tags
3408 on a per-file basis, insert anywhere in the file:
3410 #+STARTUP: noptag"
3411 :group 'org-tags
3412 :type '(repeat
3413 (choice
3414 (cons :tag "Tag with key"
3415 (string :tag "Tag name")
3416 (character :tag "Access char"))
3417 (list :tag "Tag" (string :tag "Tag name"))
3418 (const :tag "Start radio group" (:startgroup))
3419 (const :tag "Start tag group, non distinct" (:startgrouptag))
3420 (const :tag "Group tags delimiter" (:grouptags))
3421 (const :tag "End radio group" (:endgroup))
3422 (const :tag "End tag group, non distinct" (:endgrouptag))
3423 (const :tag "New line" (:newline)))))
3425 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3426 "If non-nil, always offer completion for all tags of all agenda files.
3427 Instead of customizing this variable directly, you might want to
3428 set it locally for capture buffers, because there no list of
3429 tags in that file can be created dynamically (there are none).
3431 (add-hook \\='org-capture-mode-hook
3432 (lambda ()
3433 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3434 :group 'org-tags
3435 :version "24.1"
3436 :type 'boolean)
3438 (defvar org-file-tags nil
3439 "List of tags that can be inherited by all entries in the file.
3440 The tags will be inherited if the variable `org-use-tag-inheritance'
3441 says they should be.
3442 This variable is populated from #+FILETAGS lines.")
3444 (defcustom org-use-fast-tag-selection 'auto
3445 "Non-nil means use fast tag selection scheme.
3446 This is a special interface to select and deselect tags with single keys.
3447 When nil, fast selection is never used.
3448 When the symbol `auto', fast selection is used if and only if selection
3449 characters for tags have been configured, either through the variable
3450 `org-tag-alist' or through a #+TAGS line in the buffer.
3451 When t, fast selection is always used and selection keys are assigned
3452 automatically if necessary."
3453 :group 'org-tags
3454 :type '(choice
3455 (const :tag "Always" t)
3456 (const :tag "Never" nil)
3457 (const :tag "When selection characters are configured" auto)))
3459 (defcustom org-fast-tag-selection-single-key nil
3460 "Non-nil means fast tag selection exits after first change.
3461 When nil, you have to press RET to exit it.
3462 During fast tag selection, you can toggle this flag with `C-c'.
3463 This variable can also have the value `expert'. In this case, the window
3464 displaying the tags menu is not even shown, until you press C-c again."
3465 :group 'org-tags
3466 :type '(choice
3467 (const :tag "No" nil)
3468 (const :tag "Yes" t)
3469 (const :tag "Expert" expert)))
3471 (defvar org-fast-tag-selection-include-todo nil
3472 "Non-nil means fast tags selection interface will also offer TODO states.
3473 This is an undocumented feature, you should not rely on it.")
3475 (defcustom org-tags-column -77
3476 "The column to which tags should be indented in a headline.
3477 If this number is positive, it specifies the column. If it is negative,
3478 it means that the tags should be flushright to that column. For example,
3479 -80 works well for a normal 80 character screen.
3480 When 0, place tags directly after headline text, with only one space in
3481 between."
3482 :group 'org-tags
3483 :type 'integer)
3485 (defcustom org-auto-align-tags t
3486 "Non-nil keeps tags aligned when modifying headlines.
3487 Some operations (i.e. demoting) change the length of a headline and
3488 therefore shift the tags around. With this option turned on, after
3489 each such operation the tags are again aligned to `org-tags-column'."
3490 :group 'org-tags
3491 :type 'boolean)
3493 (defcustom org-use-tag-inheritance t
3494 "Non-nil means tags in levels apply also for sublevels.
3495 When nil, only the tags directly given in a specific line apply there.
3496 This may also be a list of tags that should be inherited, or a regexp that
3497 matches tags that should be inherited. Additional control is possible
3498 with the variable `org-tags-exclude-from-inheritance' which gives an
3499 explicit list of tags to be excluded from inheritance, even if the value of
3500 `org-use-tag-inheritance' would select it for inheritance.
3502 If this option is t, a match early-on in a tree can lead to a large
3503 number of matches in the subtree when constructing the agenda or creating
3504 a sparse tree. If you only want to see the first match in a tree during
3505 a search, check out the variable `org-tags-match-list-sublevels'."
3506 :group 'org-tags
3507 :type '(choice
3508 (const :tag "Not" nil)
3509 (const :tag "Always" t)
3510 (repeat :tag "Specific tags" (string :tag "Tag"))
3511 (regexp :tag "Tags matched by regexp")))
3513 (defcustom org-tags-exclude-from-inheritance nil
3514 "List of tags that should never be inherited.
3515 This is a way to exclude a few tags from inheritance. For way to do
3516 the opposite, to actively allow inheritance for selected tags,
3517 see the variable `org-use-tag-inheritance'."
3518 :group 'org-tags
3519 :type '(repeat (string :tag "Tag")))
3521 (defun org-tag-inherit-p (tag)
3522 "Check if TAG is one that should be inherited."
3523 (cond
3524 ((member tag org-tags-exclude-from-inheritance) nil)
3525 ((eq org-use-tag-inheritance t) t)
3526 ((not org-use-tag-inheritance) nil)
3527 ((stringp org-use-tag-inheritance)
3528 (string-match org-use-tag-inheritance tag))
3529 ((listp org-use-tag-inheritance)
3530 (member tag org-use-tag-inheritance))
3531 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3533 (defcustom org-tags-match-list-sublevels t
3534 "Non-nil means list also sublevels of headlines matching a search.
3535 This variable applies to tags/property searches, and also to stuck
3536 projects because this search is based on a tags match as well.
3538 When set to the symbol `indented', sublevels are indented with
3539 leading dots.
3541 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3542 the sublevels of a headline matching a tag search often also match
3543 the same search. Listing all of them can create very long lists.
3544 Setting this variable to nil causes subtrees of a match to be skipped.
3546 This variable is semi-obsolete and probably should always be true. It
3547 is better to limit inheritance to certain tags using the variables
3548 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3549 :group 'org-tags
3550 :type '(choice
3551 (const :tag "No, don't list them" nil)
3552 (const :tag "Yes, do list them" t)
3553 (const :tag "List them, indented with leading dots" indented)))
3555 (defcustom org-tags-sort-function nil
3556 "When set, tags are sorted using this function as a comparator."
3557 :group 'org-tags
3558 :type '(choice
3559 (const :tag "No sorting" nil)
3560 (const :tag "Alphabetical" string<)
3561 (const :tag "Reverse alphabetical" string>)
3562 (function :tag "Custom function" nil)))
3564 (defvar org-tags-history nil
3565 "History of minibuffer reads for tags.")
3566 (defvar org-last-tags-completion-table nil
3567 "The last used completion table for tags.")
3568 (defvar org-after-tags-change-hook nil
3569 "Hook that is run after the tags in a line have changed.")
3571 (defgroup org-properties nil
3572 "Options concerning properties in Org mode."
3573 :tag "Org Properties"
3574 :group 'org)
3576 (defcustom org-property-format "%-10s %s"
3577 "How property key/value pairs should be formatted by `indent-line'.
3578 When `indent-line' hits a property definition, it will format the line
3579 according to this format, mainly to make sure that the values are
3580 lined-up with respect to each other."
3581 :group 'org-properties
3582 :type 'string)
3584 (defcustom org-properties-postprocess-alist nil
3585 "Alist of properties and functions to adjust inserted values.
3586 Elements of this alist must be of the form
3588 ([string] [function])
3590 where [string] must be a property name and [function] must be a
3591 lambda expression: this lambda expression must take one argument,
3592 the value to adjust, and return the new value as a string.
3594 For example, this element will allow the property \"Remaining\"
3595 to be updated wrt the relation between the \"Effort\" property
3596 and the clock summary:
3598 ((\"Remaining\" (lambda(value)
3599 (let ((clocksum (org-clock-sum-current-item))
3600 (effort (org-duration-to-minutes
3601 (org-entry-get (point) \"Effort\"))))
3602 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3603 :group 'org-properties
3604 :version "24.1"
3605 :type '(alist :key-type (string :tag "Property")
3606 :value-type (function :tag "Function")))
3608 (defcustom org-use-property-inheritance nil
3609 "Non-nil means properties apply also for sublevels.
3611 This setting is chiefly used during property searches. Turning it on can
3612 cause significant overhead when doing a search, which is why it is not
3613 on by default.
3615 When nil, only the properties directly given in the current entry count.
3616 When t, every property is inherited. The value may also be a list of
3617 properties that should have inheritance, or a regular expression matching
3618 properties that should be inherited.
3620 However, note that some special properties use inheritance under special
3621 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3622 and the properties ending in \"_ALL\" when they are used as descriptor
3623 for valid values of a property.
3625 Note for programmers:
3626 When querying an entry with `org-entry-get', you can control if inheritance
3627 should be used. By default, `org-entry-get' looks only at the local
3628 properties. You can request inheritance by setting the inherit argument
3629 to t (to force inheritance) or to `selective' (to respect the setting
3630 in this variable)."
3631 :group 'org-properties
3632 :type '(choice
3633 (const :tag "Not" nil)
3634 (const :tag "Always" t)
3635 (repeat :tag "Specific properties" (string :tag "Property"))
3636 (regexp :tag "Properties matched by regexp")))
3638 (defun org-property-inherit-p (property)
3639 "Return a non-nil value if PROPERTY should be inherited."
3640 (cond
3641 ((eq org-use-property-inheritance t) t)
3642 ((not org-use-property-inheritance) nil)
3643 ((stringp org-use-property-inheritance)
3644 (string-match org-use-property-inheritance property))
3645 ((listp org-use-property-inheritance)
3646 (member-ignore-case property org-use-property-inheritance))
3647 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3649 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3650 "The default column format, if no other format has been defined.
3651 This variable can be set on the per-file basis by inserting a line
3653 #+COLUMNS: %25ITEM ....."
3654 :group 'org-properties
3655 :type 'string)
3657 (defcustom org-columns-ellipses ".."
3658 "The ellipses to be used when a field in column view is truncated.
3659 When this is the empty string, as many characters as possible are shown,
3660 but then there will be no visual indication that the field has been truncated.
3661 When this is a string of length N, the last N characters of a truncated
3662 field are replaced by this string. If the column is narrower than the
3663 ellipses string, only part of the ellipses string will be shown."
3664 :group 'org-properties
3665 :type 'string)
3667 (defconst org-global-properties-fixed
3668 '(("VISIBILITY_ALL" . "folded children content all")
3669 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3670 "List of property/value pairs that can be inherited by any entry.
3672 These are fixed values, for the preset properties. The user variable
3673 that can be used to add to this list is `org-global-properties'.
3675 The entries in this list are cons cells where the car is a property
3676 name and cdr is a string with the value. If the value represents
3677 multiple items like an \"_ALL\" property, separate the items by
3678 spaces.")
3680 (defcustom org-global-properties nil
3681 "List of property/value pairs that can be inherited by any entry.
3683 This list will be combined with the constant `org-global-properties-fixed'.
3685 The entries in this list are cons cells where the car is a property
3686 name and cdr is a string with the value.
3688 You can set buffer-local values for the same purpose in the variable
3689 `org-file-properties' this by adding lines like
3691 #+PROPERTY: NAME VALUE"
3692 :group 'org-properties
3693 :type '(repeat
3694 (cons (string :tag "Property")
3695 (string :tag "Value"))))
3697 (defvar-local org-file-properties nil
3698 "List of property/value pairs that can be inherited by any entry.
3699 Valid for the current buffer.
3700 This variable is populated from #+PROPERTY lines.")
3702 (defgroup org-agenda nil
3703 "Options concerning agenda views in Org mode."
3704 :tag "Org Agenda"
3705 :group 'org)
3707 (defvar-local org-category nil
3708 "Variable used by Org files to set a category for agenda display.
3709 Such files should use a file variable to set it, for example
3711 # -*- mode: org; org-category: \"ELisp\"
3713 or contain a special line
3715 #+CATEGORY: ELisp
3717 If the file does not specify a category, then file's base name
3718 is used instead.")
3719 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3721 (defcustom org-agenda-files nil
3722 "The files to be used for agenda display.
3724 If an entry is a directory, all files in that directory that are matched
3725 by `org-agenda-file-regexp' will be part of the file list.
3727 If the value of the variable is not a list but a single file name, then
3728 the list of agenda files is actually stored and maintained in that file,
3729 one agenda file per line. In this file paths can be given relative to
3730 `org-directory'. Tilde expansion and environment variable substitution
3731 are also made.
3733 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3734 and removed with `\\[org-remove-file]'."
3735 :group 'org-agenda
3736 :type '(choice
3737 (repeat :tag "List of files and directories" file)
3738 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3740 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3741 "Regular expression to match files for `org-agenda-files'.
3742 If any element in the list in that variable contains a directory instead
3743 of a normal file, all files in that directory that are matched by this
3744 regular expression will be included."
3745 :group 'org-agenda
3746 :type 'regexp)
3748 (defcustom org-agenda-text-search-extra-files nil
3749 "List of extra files to be searched by text search commands.
3750 These files will be searched in addition to the agenda files by the
3751 commands `org-search-view' (`\\[org-agenda] s') \
3752 and `org-occur-in-agenda-files'.
3753 Note that these files will only be searched for text search commands,
3754 not for the other agenda views like todo lists, tag searches or the weekly
3755 agenda. This variable is intended to list notes and possibly archive files
3756 that should also be searched by these two commands.
3757 In fact, if the first element in the list is the symbol `agenda-archives',
3758 then all archive files of all agenda files will be added to the search
3759 scope."
3760 :group 'org-agenda
3761 :type '(set :greedy t
3762 (const :tag "Agenda Archives" agenda-archives)
3763 (repeat :inline t (file))))
3765 (defvaralias 'org-agenda-multi-occur-extra-files
3766 'org-agenda-text-search-extra-files)
3768 (defcustom org-agenda-skip-unavailable-files nil
3769 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3770 A nil value means to remove them, after a query, from the list."
3771 :group 'org-agenda
3772 :type 'boolean)
3774 (defcustom org-agenda-diary-file 'diary-file
3775 "File to which to add new entries with the `i' key in agenda and calendar.
3776 When this is the symbol `diary-file', the functionality in the Emacs
3777 calendar will be used to add entries to the `diary-file'. But when this
3778 points to a file, `org-agenda-diary-entry' will be used instead."
3779 :group 'org-agenda
3780 :type '(choice
3781 (const :tag "The standard Emacs diary file" diary-file)
3782 (file :tag "Special Org file diary entries")))
3784 (defgroup org-latex nil
3785 "Options for embedding LaTeX code into Org mode."
3786 :tag "Org LaTeX"
3787 :group 'org)
3789 (defcustom org-format-latex-options
3790 '(:foreground default :background default :scale 1.0
3791 :html-foreground "Black" :html-background "Transparent"
3792 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3793 "Options for creating images from LaTeX fragments.
3794 This is a property list with the following properties:
3795 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3796 `default' means use the foreground of the default face.
3797 `auto' means use the foreground from the text face.
3798 :background the background color, or \"Transparent\".
3799 `default' means use the background of the default face.
3800 `auto' means use the background from the text face.
3801 :scale a scaling factor for the size of the images, to get more pixels
3802 :html-foreground, :html-background, :html-scale
3803 the same numbers for HTML export.
3804 :matchers a list indicating which matchers should be used to
3805 find LaTeX fragments. Valid members of this list are:
3806 \"begin\" find environments
3807 \"$1\" find single characters surrounded by $.$
3808 \"$\" find math expressions surrounded by $...$
3809 \"$$\" find math expressions surrounded by $$....$$
3810 \"\\(\" find math expressions surrounded by \\(...\\)
3811 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3812 :group 'org-latex
3813 :type 'plist)
3815 (defcustom org-format-latex-signal-error t
3816 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3817 When nil, just push out a message."
3818 :group 'org-latex
3819 :version "24.1"
3820 :type 'boolean)
3822 (defcustom org-latex-to-mathml-jar-file nil
3823 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3824 Use this to specify additional executable file say a jar file.
3826 When using MathToWeb as the converter, specify the full-path to
3827 your mathtoweb.jar file."
3828 :group 'org-latex
3829 :version "24.1"
3830 :type '(choice
3831 (const :tag "None" nil)
3832 (file :tag "JAR file" :must-match t)))
3834 (defcustom org-latex-to-mathml-convert-command nil
3835 "Command to convert LaTeX fragments to MathML.
3836 Replace format-specifiers in the command as noted below and use
3837 `shell-command' to convert LaTeX to MathML.
3838 %j: Executable file in fully expanded form as specified by
3839 `org-latex-to-mathml-jar-file'.
3840 %I: Input LaTeX file in fully expanded form.
3841 %i: The latex fragment to be converted.
3842 %o: Output MathML file.
3844 This command is used by `org-create-math-formula'.
3846 When using MathToWeb as the converter, set this option to
3847 \"java -jar %j -unicode -force -df %o %I\".
3849 When using LaTeXML set this option to
3850 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3851 :group 'org-latex
3852 :version "24.1"
3853 :type '(choice
3854 (const :tag "None" nil)
3855 (string :tag "\nShell command")))
3857 (defcustom org-preview-latex-default-process 'dvipng
3858 "The default process to convert LaTeX fragments to image files.
3859 All available processes and theirs documents can be found in
3860 `org-preview-latex-process-alist', which see."
3861 :group 'org-latex
3862 :version "26.1"
3863 :package-version '(Org . "9.0")
3864 :type 'symbol)
3866 (defcustom org-preview-latex-process-alist
3867 '((dvipng
3868 :programs ("latex" "dvipng")
3869 :description "dvi > png"
3870 :message "you need to install the programs: latex and dvipng."
3871 :image-input-type "dvi"
3872 :image-output-type "png"
3873 :image-size-adjust (1.0 . 1.0)
3874 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3875 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3876 (dvisvgm
3877 :programs ("latex" "dvisvgm")
3878 :description "dvi > svg"
3879 :message "you need to install the programs: latex and dvisvgm."
3880 :use-xcolor t
3881 :image-input-type "dvi"
3882 :image-output-type "svg"
3883 :image-size-adjust (1.7 . 1.5)
3884 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3885 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3886 (imagemagick
3887 :programs ("latex" "convert")
3888 :description "pdf > png"
3889 :message "you need to install the programs: latex and imagemagick."
3890 :use-xcolor t
3891 :image-input-type "pdf"
3892 :image-output-type "png"
3893 :image-size-adjust (1.0 . 1.0)
3894 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3895 :image-converter
3896 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3897 "Definitions of external processes for LaTeX previewing.
3898 Org mode can use some external commands to generate TeX snippet's images for
3899 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3900 `org-create-formula-image' how to call them.
3902 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3903 PROPERTIES accepts the following attributes:
3905 :programs list of strings, required programs.
3906 :description string, describe the process.
3907 :message string, message it when required programs cannot be found.
3908 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3909 :image-output-type string, output file type of image converter (e.g., \"png\").
3910 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3911 deal with background and foreground color of image.
3912 Otherwise, dvipng style background and foreground color
3913 format are generated. You may then refer to them in
3914 command options with \"%F\" and \"%B\".
3915 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3916 image size showed in buffer and the cdr element is for
3917 HTML file. This option is only useful for process
3918 developers, users should use variable
3919 `org-format-latex-options' instead.
3920 :post-clean list of strings, files matched are to be cleaned up once
3921 the image is generated. When nil, the files with \".dvi\",
3922 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3923 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3924 be cleaned up.
3925 :latex-header list of strings, the LaTeX header of the snippet file.
3926 When nil, the fallback value is used instead, which is
3927 controlled by `org-format-latex-header',
3928 `org-latex-default-packages-alist' and
3929 `org-latex-packages-alist', which see.
3930 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3931 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3932 replaced with values defined below.
3933 :image-converter list of image converter commands strings. Each of them is
3934 given to the shell and supports any of the following
3935 place-holders defined below.
3937 Place-holders used by `:image-converter' and `:latex-compiler':
3939 %f input file name
3940 %b base name of input file
3941 %o base directory of input file
3942 %O absolute output file name
3944 Place-holders only used by `:image-converter':
3946 %F foreground of image
3947 %B background of image
3948 %D dpi, which is used to adjust image size by some processing commands.
3949 %S the image size scale ratio, which is used to adjust image size by some
3950 processing commands."
3951 :group 'org-latex
3952 :version "26.1"
3953 :package-version '(Org . "9.0")
3954 :type '(alist :tag "LaTeX to image backends"
3955 :value-type (plist)))
3957 (defcustom org-preview-latex-image-directory "ltximg/"
3958 "Path to store latex preview images.
3959 A relative path here creates many directories relative to the
3960 processed Org files paths. An absolute path puts all preview
3961 images at the same place."
3962 :group 'org-latex
3963 :version "26.1"
3964 :package-version '(Org . "9.0")
3965 :type 'string)
3967 (defun org-format-latex-mathml-available-p ()
3968 "Return t if `org-latex-to-mathml-convert-command' is usable."
3969 (save-match-data
3970 (when (and (boundp 'org-latex-to-mathml-convert-command)
3971 org-latex-to-mathml-convert-command)
3972 (let ((executable (car (split-string
3973 org-latex-to-mathml-convert-command))))
3974 (when (executable-find executable)
3975 (if (string-match
3976 "%j" org-latex-to-mathml-convert-command)
3977 (file-readable-p org-latex-to-mathml-jar-file)
3978 t))))))
3980 (defcustom org-format-latex-header "\\documentclass{article}
3981 \\usepackage[usenames]{color}
3982 \[PACKAGES]
3983 \[DEFAULT-PACKAGES]
3984 \\pagestyle{empty} % do not remove
3985 % The settings below are copied from fullpage.sty
3986 \\setlength{\\textwidth}{\\paperwidth}
3987 \\addtolength{\\textwidth}{-3cm}
3988 \\setlength{\\oddsidemargin}{1.5cm}
3989 \\addtolength{\\oddsidemargin}{-2.54cm}
3990 \\setlength{\\evensidemargin}{\\oddsidemargin}
3991 \\setlength{\\textheight}{\\paperheight}
3992 \\addtolength{\\textheight}{-\\headheight}
3993 \\addtolength{\\textheight}{-\\headsep}
3994 \\addtolength{\\textheight}{-\\footskip}
3995 \\addtolength{\\textheight}{-3cm}
3996 \\setlength{\\topmargin}{1.5cm}
3997 \\addtolength{\\topmargin}{-2.54cm}"
3998 "The document header used for processing LaTeX fragments.
3999 It is imperative that this header make sure that no page number
4000 appears on the page. The package defined in the variables
4001 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4002 will either replace the placeholder \"[PACKAGES]\" in this
4003 header, or they will be appended."
4004 :group 'org-latex
4005 :type 'string)
4007 (defun org-set-packages-alist (var val)
4008 "Set the packages alist and make sure it has 3 elements per entry."
4009 (set var (mapcar (lambda (x)
4010 (if (and (consp x) (= (length x) 2))
4011 (list (car x) (nth 1 x) t)
4013 val)))
4015 (defun org-get-packages-alist (var)
4016 "Get the packages alist and make sure it has 3 elements per entry."
4017 (mapcar (lambda (x)
4018 (if (and (consp x) (= (length x) 2))
4019 (list (car x) (nth 1 x) t)
4021 (default-value var)))
4023 (defcustom org-latex-default-packages-alist
4024 '(("AUTO" "inputenc" t ("pdflatex"))
4025 ("T1" "fontenc" t ("pdflatex"))
4026 ("" "graphicx" t)
4027 ("" "grffile" t)
4028 ("" "longtable" nil)
4029 ("" "wrapfig" nil)
4030 ("" "rotating" nil)
4031 ("normalem" "ulem" t)
4032 ("" "amsmath" t)
4033 ("" "textcomp" t)
4034 ("" "amssymb" t)
4035 ("" "capt-of" nil)
4036 ("" "hyperref" nil))
4037 "Alist of default packages to be inserted in the header.
4039 Change this only if one of the packages here causes an
4040 incompatibility with another package you are using.
4042 The packages in this list are needed by one part or another of
4043 Org mode to function properly:
4045 - inputenc, fontenc: for basic font and character selection
4046 - graphicx: for including images
4047 - grffile: allow periods and spaces in graphics file names
4048 - longtable: For multipage tables
4049 - wrapfig: for figure placement
4050 - rotating: for sideways figures and tables
4051 - ulem: for underline and strike-through
4052 - amsmath: for subscript and superscript and math environments
4053 - textcomp, amssymb: for various symbols used
4054 for interpreting the entities in `org-entities'. You can skip
4055 some of these packages if you don't use any of their symbols.
4056 - capt-of: for captions outside of floats
4057 - hyperref: for cross references
4059 Therefore you should not modify this variable unless you know
4060 what you are doing. The one reason to change it anyway is that
4061 you might be loading some other package that conflicts with one
4062 of the default packages. Each element is either a cell or
4063 a string.
4065 A cell is of the format
4067 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4069 If SNIPPET-FLAG is non-nil, the package also needs to be included
4070 when compiling LaTeX snippets into images for inclusion into
4071 non-LaTeX output. COMPILERS is a list of compilers that should
4072 include the package, see `org-latex-compiler'. If the document
4073 compiler is not in the list, and the list is non-nil, the package
4074 will not be inserted in the final document.
4076 A string will be inserted as-is in the header of the document."
4077 :group 'org-latex
4078 :group 'org-export-latex
4079 :set 'org-set-packages-alist
4080 :get 'org-get-packages-alist
4081 :version "26.1"
4082 :package-version '(Org . "8.3")
4083 :type '(repeat
4084 (choice
4085 (list :tag "options/package pair"
4086 (string :tag "options")
4087 (string :tag "package")
4088 (boolean :tag "Snippet")
4089 (choice
4090 (const :tag "For all compilers" nil)
4091 (repeat :tag "Allowed compiler" string)))
4092 (string :tag "A line of LaTeX"))))
4094 (defcustom org-latex-packages-alist nil
4095 "Alist of packages to be inserted in every LaTeX header.
4097 These will be inserted after `org-latex-default-packages-alist'.
4098 Each element is either a cell or a string.
4100 A cell is of the format:
4102 (\"options\" \"package\" SNIPPET-FLAG)
4104 SNIPPET-FLAG, when non-nil, indicates that this package is also
4105 needed when turning LaTeX snippets into images for inclusion into
4106 non-LaTeX output.
4108 A string will be inserted as-is in the header of the document.
4110 Make sure that you only list packages here which:
4112 - you want in every file;
4113 - do not conflict with the setup in `org-format-latex-header';
4114 - do not conflict with the default packages in
4115 `org-latex-default-packages-alist'."
4116 :group 'org-latex
4117 :group 'org-export-latex
4118 :set 'org-set-packages-alist
4119 :get 'org-get-packages-alist
4120 :type '(repeat
4121 (choice
4122 (list :tag "options/package pair"
4123 (string :tag "options")
4124 (string :tag "package")
4125 (boolean :tag "Snippet"))
4126 (string :tag "A line of LaTeX"))))
4128 (defgroup org-appearance nil
4129 "Settings for Org mode appearance."
4130 :tag "Org Appearance"
4131 :group 'org)
4133 (defcustom org-level-color-stars-only nil
4134 "Non-nil means fontify only the stars in each headline.
4135 When nil, the entire headline is fontified.
4136 Changing it requires restart of `font-lock-mode' to become effective
4137 also in regions already fontified."
4138 :group 'org-appearance
4139 :type 'boolean)
4141 (defcustom org-hide-leading-stars nil
4142 "Non-nil means hide the first N-1 stars in a headline.
4143 This works by using the face `org-hide' for these stars. This
4144 face is white for a light background, and black for a dark
4145 background. You may have to customize the face `org-hide' to
4146 make this work.
4147 Changing it requires restart of `font-lock-mode' to become effective
4148 also in regions already fontified.
4149 You may also set this on a per-file basis by adding one of the following
4150 lines to the buffer:
4152 #+STARTUP: hidestars
4153 #+STARTUP: showstars"
4154 :group 'org-appearance
4155 :type 'boolean)
4157 (defcustom org-hidden-keywords nil
4158 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4159 For example, a value \\='(title) for this list makes the document's title
4160 appear in the buffer without the initial \"#+TITLE:\" part."
4161 :group 'org-appearance
4162 :version "24.1"
4163 :type '(set (const :tag "#+AUTHOR" author)
4164 (const :tag "#+DATE" date)
4165 (const :tag "#+EMAIL" email)
4166 (const :tag "#+TITLE" title)))
4168 (defcustom org-custom-properties nil
4169 "List of properties (as strings) with a special meaning.
4170 The default use of these custom properties is to let the user
4171 hide them with `org-toggle-custom-properties-visibility'."
4172 :group 'org-properties
4173 :group 'org-appearance
4174 :version "24.3"
4175 :type '(repeat (string :tag "Property Name")))
4177 (defcustom org-fontify-done-headline nil
4178 "Non-nil means change the face of a headline if it is marked DONE.
4179 Normally, only the TODO/DONE keyword indicates the state of a headline.
4180 When this is non-nil, the headline after the keyword is set to the
4181 `org-headline-done' as an additional indication."
4182 :group 'org-appearance
4183 :type 'boolean)
4185 (defcustom org-fontify-emphasized-text t
4186 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4187 Changing this variable requires a restart of Emacs to take effect."
4188 :group 'org-appearance
4189 :type 'boolean)
4191 (defcustom org-fontify-whole-heading-line nil
4192 "Non-nil means fontify the whole line for headings.
4193 This is useful when setting a background color for the
4194 org-level-* faces."
4195 :group 'org-appearance
4196 :type 'boolean)
4198 (defcustom org-highlight-latex-and-related nil
4199 "Non-nil means highlight LaTeX related syntax in the buffer.
4200 When non nil, the value should be a list containing any of the
4201 following symbols:
4202 `latex' Highlight LaTeX snippets and environments.
4203 `script' Highlight subscript and superscript.
4204 `entities' Highlight entities."
4205 :group 'org-appearance
4206 :version "24.4"
4207 :package-version '(Org . "8.0")
4208 :type '(choice
4209 (const :tag "No highlighting" nil)
4210 (set :greedy t :tag "Highlight"
4211 (const :tag "LaTeX snippets and environments" latex)
4212 (const :tag "Subscript and superscript" script)
4213 (const :tag "Entities" entities))))
4215 (defcustom org-hide-emphasis-markers nil
4216 "Non-nil mean font-lock should hide the emphasis marker characters."
4217 :group 'org-appearance
4218 :type 'boolean)
4220 (defcustom org-hide-macro-markers nil
4221 "Non-nil mean font-lock should hide the brackets marking macro calls."
4222 :group 'org-appearance
4223 :type 'boolean)
4225 (defcustom org-pretty-entities nil
4226 "Non-nil means show entities as UTF8 characters.
4227 When nil, the \\name form remains in the buffer."
4228 :group 'org-appearance
4229 :version "24.1"
4230 :type 'boolean)
4232 (defcustom org-pretty-entities-include-sub-superscripts t
4233 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4234 :group 'org-appearance
4235 :version "24.1"
4236 :type 'boolean)
4238 (defvar org-emph-re nil
4239 "Regular expression for matching emphasis.
4240 After a match, the match groups contain these elements:
4241 0 The match of the full regular expression, including the characters
4242 before and after the proper match
4243 1 The character before the proper match, or empty at beginning of line
4244 2 The proper match, including the leading and trailing markers
4245 3 The leading marker like * or /, indicating the type of highlighting
4246 4 The text between the emphasis markers, not including the markers
4247 5 The character after the match, empty at the end of a line")
4249 (defvar org-verbatim-re nil
4250 "Regular expression for matching verbatim text.")
4252 (defvar org-emphasis-regexp-components) ; defined just below
4253 (defvar org-emphasis-alist) ; defined just below
4254 (defun org-set-emph-re (var val)
4255 "Set variable and compute the emphasis regular expression."
4256 (set var val)
4257 (when (and (boundp 'org-emphasis-alist)
4258 (boundp 'org-emphasis-regexp-components)
4259 org-emphasis-alist org-emphasis-regexp-components)
4260 (pcase-let*
4261 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4262 (body (if (<= nl 0) body
4263 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4264 (template
4265 (format (concat "\\([%s]\\|^\\)" ;before markers
4266 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4267 "\\([%s]\\|$\\)") ;after markers
4268 pre border border body border post)))
4269 (setq org-emph-re (format template "*/_+"))
4270 (setq org-verbatim-re (format template "=~")))))
4272 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4273 ;; set this option proved cumbersome. See this message/thread:
4274 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4275 (defvar org-emphasis-regexp-components
4276 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4277 "Components used to build the regular expression for emphasis.
4278 This is a list with five entries. Terminology: In an emphasis string
4279 like \" *strong word* \", we call the initial space PREMATCH, the final
4280 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4281 and \"trong wor\" is the body. The different components in this variable
4282 specify what is allowed/forbidden in each part:
4284 pre Chars allowed as prematch. Beginning of line will be allowed too.
4285 post Chars allowed as postmatch. End of line will be allowed too.
4286 border The chars *forbidden* as border characters.
4287 body-regexp A regexp like \".\" to match a body character. Don't use
4288 non-shy groups here, and don't allow newline here.
4289 newline The maximum number of newlines allowed in an emphasis exp.
4291 You need to reload Org or to restart Emacs after setting this.")
4293 (defcustom org-emphasis-alist
4294 '(("*" bold)
4295 ("/" italic)
4296 ("_" underline)
4297 ("=" org-verbatim verbatim)
4298 ("~" org-code verbatim)
4299 ("+" (:strike-through t)))
4300 "Alist of characters and faces to emphasize text.
4301 Text starting and ending with a special character will be emphasized,
4302 for example *bold*, _underlined_ and /italic/. This variable sets the
4303 marker characters and the face to be used by font-lock for highlighting
4304 in Org buffers.
4306 You need to reload Org or to restart Emacs after customizing this."
4307 :group 'org-appearance
4308 :set 'org-set-emph-re
4309 :version "24.4"
4310 :package-version '(Org . "8.0")
4311 :type '(repeat
4312 (list
4313 (string :tag "Marker character")
4314 (choice
4315 (face :tag "Font-lock-face")
4316 (plist :tag "Face property list"))
4317 (option (const verbatim)))))
4319 (defvar org-protecting-blocks '("src" "example" "export")
4320 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4321 This is needed for font-lock setup.")
4323 ;;; Functions and variables from their packages
4324 ;; Declared here to avoid compiler warnings
4325 (defvar mark-active)
4327 ;; Various packages
4328 (declare-function calc-eval "calc" (str &optional separator &rest args))
4329 (declare-function calendar-forward-day "cal-move" (arg))
4330 (declare-function calendar-goto-date "cal-move" (date))
4331 (declare-function calendar-goto-today "cal-move" ())
4332 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4333 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4334 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4335 (declare-function cdlatex-tab "ext:cdlatex" ())
4336 (declare-function dired-get-filename
4337 "dired"
4338 (&optional localp no-error-if-not-filep))
4339 (declare-function iswitchb-read-buffer
4340 "iswitchb"
4341 (prompt &optional
4342 default require-match _predicate start matches-set))
4343 (declare-function org-agenda-change-all-lines
4344 "org-agenda"
4345 (newhead hdmarker &optional fixface just-this))
4346 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4347 "org-agenda"
4348 (&optional end))
4349 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4350 (declare-function org-agenda-format-item
4351 "org-agenda"
4352 (extra txt &optional level category tags dotime
4353 remove-re habitp))
4354 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4355 (declare-function org-agenda-save-markers-for-cut-and-paste
4356 "org-agenda"
4357 (beg end))
4358 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4359 (declare-function org-agenda-skip "org-agenda" ())
4360 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4361 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4362 (declare-function org-indent-mode "org-indent" (&optional arg))
4363 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4364 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4365 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4366 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4367 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4368 (declare-function parse-time-string "parse-time" (string))
4370 (defvar align-mode-rules-list)
4371 (defvar calc-embedded-close-formula)
4372 (defvar calc-embedded-open-formula)
4373 (defvar calc-embedded-open-mode)
4374 (defvar font-lock-unfontify-region-function)
4375 (defvar iswitchb-temp-buflist)
4376 (defvar org-agenda-tags-todo-honor-ignore-options)
4377 (defvar remember-data-file)
4378 (defvar texmathp-why)
4380 ;;;###autoload
4381 (defun turn-on-orgtbl ()
4382 "Unconditionally turn on `orgtbl-mode'."
4383 (require 'org-table)
4384 (orgtbl-mode 1))
4386 (defun org-at-table-p (&optional table-type)
4387 "Non-nil if the cursor is inside an Org table.
4388 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4389 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4390 (or (not (derived-mode-p 'org-mode))
4391 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4392 (and e (or table-type
4393 (eq 'org (org-element-property :type e))))))))
4395 (defun org-at-table.el-p ()
4396 "Non-nil when point is at a table.el table."
4397 (and (org-match-line "[ \t]*[|+]")
4398 (let ((element (org-element-at-point)))
4399 (and (eq (org-element-type element) 'table)
4400 (eq (org-element-property :type element) 'table.el)))))
4402 (defun org-at-table-hline-p ()
4403 "Non-nil when point is inside a hline in a table.
4404 Assume point is already in a table."
4405 (org-match-line org-table-hline-regexp))
4407 (defun org-table-map-tables (function &optional quietly)
4408 "Apply FUNCTION to the start of all tables in the buffer."
4409 (org-with-wide-buffer
4410 (goto-char (point-min))
4411 (while (re-search-forward org-table-any-line-regexp nil t)
4412 (unless quietly
4413 (message "Mapping tables: %d%%"
4414 (floor (* 100.0 (point)) (buffer-size))))
4415 (beginning-of-line 1)
4416 (when (and (looking-at org-table-line-regexp)
4417 ;; Exclude tables in src/example/verbatim/clocktable blocks
4418 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4419 (save-excursion (funcall function))
4420 (or (looking-at org-table-line-regexp)
4421 (forward-char 1)))
4422 (re-search-forward org-table-any-border-regexp nil 1)))
4423 (unless quietly (message "Mapping tables: done")))
4425 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4426 (declare-function org-clock-update-mode-line "org-clock" ())
4427 (declare-function org-resolve-clocks "org-clock"
4428 (&optional also-non-dangling-p prompt last-valid))
4430 (defun org-at-TBLFM-p (&optional pos)
4431 "Non-nil when point (or POS) is in #+TBLFM line."
4432 (save-excursion
4433 (goto-char (or pos (point)))
4434 (beginning-of-line)
4435 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4436 (eq (org-element-type (org-element-at-point)) 'table))))
4438 (defvar org-clock-start-time)
4439 (defvar org-clock-marker (make-marker)
4440 "Marker recording the last clock-in.")
4441 (defvar org-clock-hd-marker (make-marker)
4442 "Marker recording the last clock-in, but the headline position.")
4443 (defvar org-clock-heading ""
4444 "The heading of the current clock entry.")
4445 (defun org-clock-is-active ()
4446 "Return the buffer where the clock is currently running.
4447 Return nil if no clock is running."
4448 (marker-buffer org-clock-marker))
4450 (defun org-check-running-clock ()
4451 "Check if the current buffer contains the running clock.
4452 If yes, offer to stop it and to save the buffer with the changes."
4453 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4454 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4455 (buffer-name))))
4456 (org-clock-out)
4457 (when (y-or-n-p "Save changed buffer?")
4458 (save-buffer))))
4460 (defun org-clocktable-try-shift (dir n)
4461 "Check if this line starts a clock table, if yes, shift the time block."
4462 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4463 (org-clocktable-shift dir n)))
4465 ;;;###autoload
4466 (defun org-clock-persistence-insinuate ()
4467 "Set up hooks for clock persistence."
4468 (require 'org-clock)
4469 (add-hook 'org-mode-hook 'org-clock-load)
4470 (add-hook 'kill-emacs-hook 'org-clock-save))
4472 (defgroup org-archive nil
4473 "Options concerning archiving in Org mode."
4474 :tag "Org Archive"
4475 :group 'org-structure)
4477 (defcustom org-archive-location "%s_archive::"
4478 "The location where subtrees should be archived.
4480 The value of this variable is a string, consisting of two parts,
4481 separated by a double-colon. The first part is a filename and
4482 the second part is a headline.
4484 When the filename is omitted, archiving happens in the same file.
4485 %s in the filename will be replaced by the current file
4486 name (without the directory part). Archiving to a different file
4487 is useful to keep archived entries from contributing to the
4488 Org Agenda.
4490 The archived entries will be filed as subtrees of the specified
4491 headline. When the headline is omitted, the subtrees are simply
4492 filed away at the end of the file, as top-level entries. Also in
4493 the heading you can use %s to represent the file name, this can be
4494 useful when using the same archive for a number of different files.
4496 Here are a few examples:
4497 \"%s_archive::\"
4498 If the current file is Projects.org, archive in file
4499 Projects.org_archive, as top-level trees. This is the default.
4501 \"::* Archived Tasks\"
4502 Archive in the current file, under the top-level headline
4503 \"* Archived Tasks\".
4505 \"~/org/archive.org::\"
4506 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4508 \"~/org/archive.org::* From %s\"
4509 Archive in file ~/org/archive.org (absolute path), under headlines
4510 \"From FILENAME\" where file name is the current file name.
4512 \"~/org/datetree.org::datetree/* Finished Tasks\"
4513 The \"datetree/\" string is special, signifying to archive
4514 items to the datetree. Items are placed in either the CLOSED
4515 date of the item, or the current date if there is no CLOSED date.
4516 The heading will be a subentry to the current date. There doesn't
4517 need to be a heading, but there always needs to be a slash after
4518 datetree. For example, to store archived items directly in the
4519 datetree, use \"~/org/datetree.org::datetree/\".
4521 \"basement::** Finished Tasks\"
4522 Archive in file ./basement (relative path), as level 3 trees
4523 below the level 2 heading \"** Finished Tasks\".
4525 You may set this option on a per-file basis by adding to the buffer a
4526 line like
4528 #+ARCHIVE: basement::** Finished Tasks
4530 You may also define it locally for a subtree by setting an ARCHIVE property
4531 in the entry. If such a property is found in an entry, or anywhere up
4532 the hierarchy, it will be used."
4533 :group 'org-archive
4534 :type 'string)
4536 (defcustom org-agenda-skip-archived-trees t
4537 "Non-nil means the agenda will skip any items located in archived trees.
4538 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4539 variable is no longer recommended, you should leave it at the value t.
4540 Instead, use the key `v' to cycle the archives-mode in the agenda."
4541 :group 'org-archive
4542 :group 'org-agenda-skip
4543 :type 'boolean)
4545 (defcustom org-columns-skip-archived-trees t
4546 "Non-nil means ignore archived trees when creating column view."
4547 :group 'org-archive
4548 :group 'org-properties
4549 :type 'boolean)
4551 (defcustom org-cycle-open-archived-trees nil
4552 "Non-nil means `org-cycle' will open archived trees.
4553 An archived tree is a tree marked with the tag ARCHIVE.
4554 When nil, archived trees will stay folded. You can still open them with
4555 normal outline commands like `show-all', but not with the cycling commands."
4556 :group 'org-archive
4557 :group 'org-cycle
4558 :type 'boolean)
4560 (defcustom org-sparse-tree-open-archived-trees nil
4561 "Non-nil means sparse tree construction shows matches in archived trees.
4562 When nil, matches in these trees are highlighted, but the trees are kept in
4563 collapsed state."
4564 :group 'org-archive
4565 :group 'org-sparse-trees
4566 :type 'boolean)
4568 (defcustom org-sparse-tree-default-date-type nil
4569 "The default date type when building a sparse tree.
4570 When this is nil, a date is a scheduled or a deadline timestamp.
4571 Otherwise, these types are allowed:
4573 all: all timestamps
4574 active: only active timestamps (<...>)
4575 inactive: only inactive timestamps ([...])
4576 scheduled: only scheduled timestamps
4577 deadline: only deadline timestamps"
4578 :type '(choice (const :tag "Scheduled or deadline" nil)
4579 (const :tag "All timestamps" all)
4580 (const :tag "Only active timestamps" active)
4581 (const :tag "Only inactive timestamps" inactive)
4582 (const :tag "Only scheduled timestamps" scheduled)
4583 (const :tag "Only deadline timestamps" deadline)
4584 (const :tag "Only closed timestamps" closed))
4585 :version "26.1"
4586 :package-version '(Org . "8.3")
4587 :group 'org-sparse-trees)
4589 (defun org-cycle-hide-archived-subtrees (state)
4590 "Re-hide all archived subtrees after a visibility state change.
4591 STATE should be one of the symbols listed in the docstring of
4592 `org-cycle-hook'."
4593 (when (and (not org-cycle-open-archived-trees)
4594 (not (memq state '(overview folded))))
4595 (save-excursion
4596 (let* ((globalp (memq state '(contents all)))
4597 (beg (if globalp (point-min) (point)))
4598 (end (if globalp (point-max) (org-end-of-subtree t))))
4599 (org-hide-archived-subtrees beg end)
4600 (goto-char beg)
4601 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4602 (message "%s" (substitute-command-keys
4603 "Subtree is archived and stays closed. Use \
4604 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4606 (defun org-force-cycle-archived ()
4607 "Cycle subtree even if it is archived."
4608 (interactive)
4609 (setq this-command 'org-cycle)
4610 (let ((org-cycle-open-archived-trees t))
4611 (call-interactively 'org-cycle)))
4613 (defun org-hide-archived-subtrees (beg end)
4614 "Re-hide all archived subtrees after a visibility state change."
4615 (org-with-wide-buffer
4616 (let ((case-fold-search nil)
4617 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4618 (goto-char beg)
4619 ;; Include headline point is currently on.
4620 (beginning-of-line)
4621 (while (and (< (point) end) (re-search-forward re end t))
4622 (when (member org-archive-tag (org-get-tags))
4623 (org-flag-subtree t)
4624 (org-end-of-subtree t))))))
4626 (defun org-flag-subtree (flag)
4627 (save-excursion
4628 (org-back-to-heading t)
4629 (org-flag-region (line-end-position)
4630 (progn (org-end-of-subtree t) (point))
4631 flag
4632 'outline)))
4634 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4636 ;; Declare Column View Code
4638 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4639 (declare-function org-columns-compute "org-colview" (property))
4641 ;; Declare ID code
4643 (declare-function org-id-store-link "org-id")
4644 (declare-function org-id-locations-load "org-id")
4645 (declare-function org-id-locations-save "org-id")
4646 (defvar org-id-track-globally)
4648 ;;; Variables for pre-computed regular expressions, all buffer local
4650 (defvar-local org-todo-regexp nil
4651 "Matches any of the TODO state keywords.
4652 Since TODO keywords are case-sensitive, `case-fold-search' is
4653 expected to be bound to nil when matching against this regexp.")
4655 (defvar-local org-not-done-regexp nil
4656 "Matches any of the TODO state keywords except the last one.
4657 Since TODO keywords are case-sensitive, `case-fold-search' is
4658 expected to be bound to nil when matching against this regexp.")
4660 (defvar-local org-not-done-heading-regexp nil
4661 "Matches a TODO headline that is not done.
4662 Since TODO keywords are case-sensitive, `case-fold-search' is
4663 expected to be bound to nil when matching against this regexp.")
4665 (defvar-local org-todo-line-regexp nil
4666 "Matches a headline and puts TODO state into group 2 if present.
4667 Since TODO keywords are case-sensitive, `case-fold-search' is
4668 expected to be bound to nil when matching against this regexp.")
4670 (defvar-local org-complex-heading-regexp nil
4671 "Matches a headline and puts everything into groups:
4673 group 1: Stars
4674 group 2: The TODO keyword, maybe
4675 group 3: Priority cookie
4676 group 4: True headline
4677 group 5: Tags
4679 Since TODO keywords are case-sensitive, `case-fold-search' is
4680 expected to be bound to nil when matching against this regexp.")
4682 (defvar-local org-complex-heading-regexp-format nil
4683 "Printf format to make regexp to match an exact headline.
4684 This regexp will match the headline of any node which has the
4685 exact headline text that is put into the format, but may have any
4686 TODO state, priority and tags.")
4688 (defvar-local org-todo-line-tags-regexp nil
4689 "Matches a headline and puts TODO state into group 2 if present.
4690 Also put tags into group 4 if tags are present.")
4692 (defconst org-plain-time-of-day-regexp
4693 (concat
4694 "\\(\\<[012]?[0-9]"
4695 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4696 "\\(--?"
4697 "\\(\\<[012]?[0-9]"
4698 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4699 "\\)?")
4700 "Regular expression to match a plain time or time range.
4701 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4702 groups carry important information:
4703 0 the full match
4704 1 the first time, range or not
4705 8 the second time, if it is a range.")
4707 (defconst org-plain-time-extension-regexp
4708 (concat
4709 "\\(\\<[012]?[0-9]"
4710 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4711 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4712 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4713 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4714 groups carry important information:
4715 0 the full match
4716 7 hours of duration
4717 9 minutes of duration")
4719 (defconst org-stamp-time-of-day-regexp
4720 (concat
4721 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4722 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4723 "\\(--?"
4724 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4725 "Regular expression to match a timestamp time or time range.
4726 After a match, the following groups carry important information:
4727 0 the full match
4728 1 date plus weekday, for back referencing to make sure both times are on the same day
4729 2 the first time, range or not
4730 4 the second time, if it is a range.")
4732 (defconst org-startup-options
4733 '(("fold" org-startup-folded t)
4734 ("overview" org-startup-folded t)
4735 ("nofold" org-startup-folded nil)
4736 ("showall" org-startup-folded nil)
4737 ("showeverything" org-startup-folded showeverything)
4738 ("content" org-startup-folded content)
4739 ("indent" org-startup-indented t)
4740 ("noindent" org-startup-indented nil)
4741 ("hidestars" org-hide-leading-stars t)
4742 ("showstars" org-hide-leading-stars nil)
4743 ("odd" org-odd-levels-only t)
4744 ("oddeven" org-odd-levels-only nil)
4745 ("align" org-startup-align-all-tables t)
4746 ("noalign" org-startup-align-all-tables nil)
4747 ("shrink" org-startup-shrink-all-tables t)
4748 ("inlineimages" org-startup-with-inline-images t)
4749 ("noinlineimages" org-startup-with-inline-images nil)
4750 ("latexpreview" org-startup-with-latex-preview t)
4751 ("nolatexpreview" org-startup-with-latex-preview nil)
4752 ("customtime" org-display-custom-times t)
4753 ("logdone" org-log-done time)
4754 ("lognotedone" org-log-done note)
4755 ("nologdone" org-log-done nil)
4756 ("lognoteclock-out" org-log-note-clock-out t)
4757 ("nolognoteclock-out" org-log-note-clock-out nil)
4758 ("logrepeat" org-log-repeat state)
4759 ("lognoterepeat" org-log-repeat note)
4760 ("logdrawer" org-log-into-drawer t)
4761 ("nologdrawer" org-log-into-drawer nil)
4762 ("logstatesreversed" org-log-states-order-reversed t)
4763 ("nologstatesreversed" org-log-states-order-reversed nil)
4764 ("nologrepeat" org-log-repeat nil)
4765 ("logreschedule" org-log-reschedule time)
4766 ("lognotereschedule" org-log-reschedule note)
4767 ("nologreschedule" org-log-reschedule nil)
4768 ("logredeadline" org-log-redeadline time)
4769 ("lognoteredeadline" org-log-redeadline note)
4770 ("nologredeadline" org-log-redeadline nil)
4771 ("logrefile" org-log-refile time)
4772 ("lognoterefile" org-log-refile note)
4773 ("nologrefile" org-log-refile nil)
4774 ("fninline" org-footnote-define-inline t)
4775 ("nofninline" org-footnote-define-inline nil)
4776 ("fnlocal" org-footnote-section nil)
4777 ("fnauto" org-footnote-auto-label t)
4778 ("fnprompt" org-footnote-auto-label nil)
4779 ("fnconfirm" org-footnote-auto-label confirm)
4780 ("fnplain" org-footnote-auto-label plain)
4781 ("fnadjust" org-footnote-auto-adjust t)
4782 ("nofnadjust" org-footnote-auto-adjust nil)
4783 ("constcgs" constants-unit-system cgs)
4784 ("constSI" constants-unit-system SI)
4785 ("noptag" org-tag-persistent-alist nil)
4786 ("hideblocks" org-hide-block-startup t)
4787 ("nohideblocks" org-hide-block-startup nil)
4788 ("beamer" org-startup-with-beamer-mode t)
4789 ("entitiespretty" org-pretty-entities t)
4790 ("entitiesplain" org-pretty-entities nil))
4791 "Variable associated with STARTUP options for Org.
4792 Each element is a list of three items: the startup options (as written
4793 in the #+STARTUP line), the corresponding variable, and the value to set
4794 this variable to if the option is found. An optional forth element PUSH
4795 means to push this value onto the list in the variable.")
4797 (defcustom org-group-tags t
4798 "When non-nil (the default), use group tags.
4799 This can be turned on/off through `org-toggle-tags-groups'."
4800 :group 'org-tags
4801 :group 'org-startup
4802 :type 'boolean)
4804 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4806 (defun org-toggle-tags-groups ()
4807 "Toggle support for group tags.
4808 Support for group tags is controlled by the option
4809 `org-group-tags', which is non-nil by default."
4810 (interactive)
4811 (setq org-group-tags (not org-group-tags))
4812 (cond ((and (derived-mode-p 'org-agenda-mode)
4813 org-group-tags)
4814 (org-agenda-redo))
4815 ((derived-mode-p 'org-mode)
4816 (let ((org-inhibit-startup t)) (org-mode))))
4817 (message "Groups tags support has been turned %s"
4818 (if org-group-tags "on" "off")))
4820 (defun org-set-regexps-and-options (&optional tags-only)
4821 "Precompute regular expressions used in the current buffer.
4822 When optional argument TAGS-ONLY is non-nil, only compute tags
4823 related expressions."
4824 (when (derived-mode-p 'org-mode)
4825 (let ((alist (org--setup-collect-keywords
4826 (org-make-options-regexp
4827 (append '("FILETAGS" "TAGS" "SETUPFILE")
4828 (and (not tags-only)
4829 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4830 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4831 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4832 ;; Startup options. Get this early since it does change
4833 ;; behavior for other options (e.g., tags).
4834 (let ((startup (cdr (assq 'startup alist))))
4835 (dolist (option startup)
4836 (let ((entry (assoc-string option org-startup-options t)))
4837 (when entry
4838 (let ((var (nth 1 entry))
4839 (val (nth 2 entry)))
4840 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4841 (unless (listp (symbol-value var))
4842 (set (make-local-variable var) nil))
4843 (add-to-list var val)))))))
4844 (setq-local org-file-tags
4845 (mapcar #'org-add-prop-inherited
4846 (cdr (assq 'filetags alist))))
4847 (setq org-current-tag-alist
4848 (append org-tag-persistent-alist
4849 (let ((tags (cdr (assq 'tags alist))))
4850 (if tags (org-tag-string-to-alist tags)
4851 org-tag-alist))))
4852 (setq org-tag-groups-alist
4853 (org-tag-alist-to-groups org-current-tag-alist))
4854 (unless tags-only
4855 ;; File properties.
4856 (setq-local org-file-properties (cdr (assq 'property alist)))
4857 ;; Archive location.
4858 (let ((archive (cdr (assq 'archive alist))))
4859 (when archive (setq-local org-archive-location archive)))
4860 ;; Category.
4861 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4862 (when cat
4863 (setq-local org-category (intern cat))
4864 (setq-local org-file-properties
4865 (org--update-property-plist
4866 "CATEGORY" cat org-file-properties))))
4867 ;; Columns.
4868 (let ((column (cdr (assq 'columns alist))))
4869 (when column (setq-local org-columns-default-format column)))
4870 ;; Constants.
4871 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4872 ;; Link abbreviations.
4873 (let ((links (cdr (assq 'link alist))))
4874 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4875 ;; Priorities.
4876 (let ((priorities (cdr (assq 'priorities alist))))
4877 (when priorities
4878 (setq-local org-highest-priority (nth 0 priorities))
4879 (setq-local org-lowest-priority (nth 1 priorities))
4880 (setq-local org-default-priority (nth 2 priorities))))
4881 ;; Scripts.
4882 (let ((scripts (assq 'scripts alist)))
4883 (when scripts
4884 (setq-local org-use-sub-superscripts (cdr scripts))))
4885 ;; TODO keywords.
4886 (setq-local org-todo-kwd-alist nil)
4887 (setq-local org-todo-key-alist nil)
4888 (setq-local org-todo-key-trigger nil)
4889 (setq-local org-todo-keywords-1 nil)
4890 (setq-local org-done-keywords nil)
4891 (setq-local org-todo-heads nil)
4892 (setq-local org-todo-sets nil)
4893 (setq-local org-todo-log-states nil)
4894 (let ((todo-sequences
4895 (or (nreverse (cdr (assq 'todo alist)))
4896 (let ((d (default-value 'org-todo-keywords)))
4897 (if (not (stringp (car d))) d
4898 ;; XXX: Backward compatibility code.
4899 (list (cons org-todo-interpretation d)))))))
4900 (dolist (sequence todo-sequences)
4901 (let* ((sequence (or (run-hook-with-args-until-success
4902 'org-todo-setup-filter-hook sequence)
4903 sequence))
4904 (sequence-type (car sequence))
4905 (keywords (cdr sequence))
4906 (sep (member "|" keywords))
4907 names alist)
4908 (dolist (k (remove "|" keywords))
4909 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4911 (error "Invalid TODO keyword %s" k))
4912 (let ((name (match-string 1 k))
4913 (key (match-string 2 k))
4914 (log (org-extract-log-state-settings k)))
4915 (push name names)
4916 (push (cons name (and key (string-to-char key))) alist)
4917 (when log (push log org-todo-log-states))))
4918 (let* ((names (nreverse names))
4919 (done (if sep (org-remove-keyword-keys (cdr sep))
4920 (last names)))
4921 (head (car names))
4922 (tail (list sequence-type head (car done) (org-last done))))
4923 (add-to-list 'org-todo-heads head 'append)
4924 (push names org-todo-sets)
4925 (setq org-done-keywords (append org-done-keywords done nil))
4926 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4927 (setq org-todo-key-alist
4928 (append org-todo-key-alist
4929 (and alist
4930 (append '((:startgroup))
4931 (nreverse alist)
4932 '((:endgroup))))))
4933 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4934 (setq org-todo-sets (nreverse org-todo-sets)
4935 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4936 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4937 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4938 ;; Compute the regular expressions and other local variables.
4939 ;; Using `org-outline-regexp-bol' would complicate them much,
4940 ;; because of the fixed white space at the end of that string.
4941 (unless org-done-keywords
4942 (setq org-done-keywords
4943 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4944 (setq org-not-done-keywords
4945 (org-delete-all org-done-keywords
4946 (copy-sequence org-todo-keywords-1))
4947 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4948 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4949 org-not-done-heading-regexp
4950 (format org-heading-keyword-regexp-format org-not-done-regexp)
4951 org-todo-line-regexp
4952 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4953 org-complex-heading-regexp
4954 (concat "^\\(\\*+\\)"
4955 "\\(?: +" org-todo-regexp "\\)?"
4956 "\\(?: +\\(\\[#.\\]\\)\\)?"
4957 "\\(?: +\\(.*?\\)\\)??"
4958 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4959 "[ \t]*$")
4960 org-complex-heading-regexp-format
4961 (concat "^\\(\\*+\\)"
4962 "\\(?: +" org-todo-regexp "\\)?"
4963 "\\(?: +\\(\\[#.\\]\\)\\)?"
4964 "\\(?: +"
4965 ;; Stats cookies can be stuck to body.
4966 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4967 "\\(%s\\)"
4968 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4969 "\\)"
4970 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
4971 "[ \t]*$")
4972 org-todo-line-tags-regexp
4973 (concat "^\\(\\*+\\)"
4974 "\\(?: +" org-todo-regexp "\\)?"
4975 "\\(?: +\\(.*?\\)\\)??"
4976 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
4977 "[ \t]*$"))
4978 (org-compute-latex-and-related-regexp)))))
4980 (defun org--setup-collect-keywords (regexp &optional files alist)
4981 "Return setup keywords values as an alist.
4983 REGEXP matches a subset of setup keywords. FILES is a list of
4984 file names already visited. It is used to avoid circular setup
4985 files. ALIST, when non-nil, is the alist computed so far.
4987 Return value contains the following keys: `archive', `category',
4988 `columns', `constants', `filetags', `link', `priorities',
4989 `property', `scripts', `startup', `tags' and `todo'."
4990 (org-with-wide-buffer
4991 (goto-char (point-min))
4992 (let ((case-fold-search t))
4993 (while (re-search-forward regexp nil t)
4994 (let ((element (org-element-at-point)))
4995 (when (eq (org-element-type element) 'keyword)
4996 (let ((key (org-element-property :key element))
4997 (value (org-element-property :value element)))
4998 (cond
4999 ((equal key "ARCHIVE")
5000 (when (org-string-nw-p value)
5001 (push (cons 'archive value) alist)))
5002 ((equal key "CATEGORY") (push (cons 'category value) alist))
5003 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5004 ((equal key "CONSTANTS")
5005 (let* ((constants (assq 'constants alist))
5006 (store (cdr constants)))
5007 (dolist (pair (split-string value))
5008 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5009 pair)
5010 (let* ((name (match-string 1 pair))
5011 (value (match-string 2 pair))
5012 (old (assoc name store)))
5013 (if old (setcdr old value)
5014 (push (cons name value) store)))))
5015 (if constants (setcdr constants store)
5016 (push (cons 'constants store) alist))))
5017 ((equal key "FILETAGS")
5018 (when (org-string-nw-p value)
5019 (let ((old (assq 'filetags alist))
5020 (new (apply #'nconc
5021 (mapcar (lambda (x) (org-split-string x ":"))
5022 (split-string value)))))
5023 (if old (setcdr old (append new (cdr old)))
5024 (push (cons 'filetags new) alist)))))
5025 ((equal key "LINK")
5026 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5027 (let ((links (assq 'link alist))
5028 (pair (cons (match-string-no-properties 1 value)
5029 (match-string-no-properties 2 value))))
5030 (if links (push pair (cdr links))
5031 (push (list 'link pair) alist)))))
5032 ((equal key "OPTIONS")
5033 (when (and (org-string-nw-p value)
5034 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5035 (push (cons 'scripts (read (match-string 1 value))) alist)))
5036 ((equal key "PRIORITIES")
5037 (push (cons 'priorities
5038 (let ((prio (split-string value)))
5039 (if (< (length prio) 3) '(?A ?C ?B)
5040 (mapcar #'string-to-char prio))))
5041 alist))
5042 ((equal key "PROPERTY")
5043 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5044 (let* ((property (assq 'property alist))
5045 (value (org--update-property-plist
5046 (match-string-no-properties 1 value)
5047 (match-string-no-properties 2 value)
5048 (cdr property))))
5049 (if property (setcdr property value)
5050 (push (cons 'property value) alist)))))
5051 ((equal key "STARTUP")
5052 (let ((startup (assq 'startup alist)))
5053 (if startup
5054 (setcdr startup
5055 (append (cdr startup) (split-string value)))
5056 (push (cons 'startup (split-string value)) alist))))
5057 ((equal key "TAGS")
5058 (let ((tag-cell (assq 'tags alist)))
5059 (if tag-cell
5060 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5061 (push (cons 'tags value) alist))))
5062 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5063 (let ((todo (assq 'todo alist))
5064 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5065 (split-string value))))
5066 (if todo (push value (cdr todo))
5067 (push (list 'todo value) alist))))
5068 ((equal key "SETUPFILE")
5069 (unless buffer-read-only ; Do not check in Gnus messages.
5070 (let ((f (and (org-string-nw-p value)
5071 (expand-file-name
5072 (org-unbracket-string "\"" "\"" value)))))
5073 (when (and f (file-readable-p f) (not (member f files)))
5074 (with-temp-buffer
5075 (setq default-directory (file-name-directory f))
5076 (insert-file-contents f)
5077 (setq alist
5078 ;; Fake Org mode to benefit from cache
5079 ;; without recurring needlessly.
5080 (let ((major-mode 'org-mode))
5081 (org--setup-collect-keywords
5082 regexp (cons f files) alist)))))))))))))))
5083 alist)
5085 (defun org-tag-string-to-alist (s)
5086 "Return tag alist associated to string S.
5087 S is a value for TAGS keyword or produced with
5088 `org-tag-alist-to-string'. Return value is an alist suitable for
5089 `org-tag-alist' or `org-tag-persistent-alist'."
5090 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5091 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5092 "\\|{.+?}\\)" ; regular expression
5093 "\\(?:(\\(.\\))\\)?\\'"))
5094 alist group-flag)
5095 (dolist (tokens lines (cdr (nreverse alist)))
5096 (push '(:newline) alist)
5097 (while tokens
5098 (let ((token (pop tokens)))
5099 (pcase token
5100 ("{"
5101 (push '(:startgroup) alist)
5102 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5103 ("}"
5104 (push '(:endgroup) alist)
5105 (setq group-flag nil))
5106 ("["
5107 (push '(:startgrouptag) alist)
5108 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5109 ("]"
5110 (push '(:endgrouptag) alist)
5111 (setq group-flag nil))
5112 (":"
5113 (push '(:grouptags) alist))
5114 ((guard (string-match tag-re token))
5115 (let ((tag (match-string 1 token))
5116 (key (and (match-beginning 2)
5117 (string-to-char (match-string 2 token)))))
5118 ;; Push all tags in groups, no matter if they already
5119 ;; appear somewhere else in the list.
5120 (when (or group-flag (not (assoc tag alist)))
5121 (push (cons tag key) alist))))))))))
5123 (defun org-tag-alist-to-string (alist &optional skip-key)
5124 "Return tag string associated to ALIST.
5126 ALIST is an alist, as defined in `org-tag-alist' or
5127 `org-tag-persistent-alist', or produced with
5128 `org-tag-string-to-alist'.
5130 Return value is a string suitable as a value for \"TAGS\"
5131 keyword.
5133 When optional argument SKIP-KEY is non-nil, skip selection keys
5134 next to tags."
5135 (mapconcat (lambda (token)
5136 (pcase token
5137 (`(:startgroup) "{")
5138 (`(:endgroup) "}")
5139 (`(:startgrouptag) "[")
5140 (`(:endgrouptag) "]")
5141 (`(:grouptags) ":")
5142 (`(:newline) "\\n")
5143 ((and
5144 (guard (not skip-key))
5145 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5146 (format "%s(%c)" tag key))
5147 (`(,(and tag (pred stringp)) . ,_) tag)
5148 (_ (user-error "Invalid tag token: %S" token))))
5149 alist
5150 " "))
5152 (defun org-tag-alist-to-groups (alist)
5153 "Return group alist from tag ALIST.
5154 ALIST is an alist, as defined in `org-tag-alist' or
5155 `org-tag-persistent-alist', or produced with
5156 `org-tag-string-to-alist'. Return value is an alist following
5157 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5158 a string, summarizing TAGS, as a list of strings."
5159 (let (groups group-status current-group)
5160 (dolist (token alist (nreverse groups))
5161 (pcase token
5162 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5163 (`(,(or :endgroup :endgrouptag))
5164 (when (eq group-status 'append)
5165 (push (nreverse current-group) groups))
5166 (setq group-status nil))
5167 (`(:grouptags) (setq group-status 'append))
5168 ((and `(,tag . ,_) (guard group-status))
5169 (if (eq group-status 'append) (push tag current-group)
5170 (setq current-group (list tag))))
5171 (_ nil)))))
5173 (defvar org--file-cache (make-hash-table :test #'equal)
5174 "Hash table to store contents of files referenced via a URL.
5175 This is the cache of file URLs read using `org-file-contents'.")
5177 (defun org-reset-file-cache ()
5178 "Reset the cache of files downloaded by `org-file-contents'."
5179 (clrhash org--file-cache))
5181 (defun org-file-url-p (file)
5182 "Non-nil if FILE is a URL."
5183 (require 'ffap)
5184 (string-match-p ffap-url-regexp file))
5186 (defun org-file-contents (file &optional noerror nocache)
5187 "Return the contents of FILE, as a string.
5189 FILE can be a file name or URL.
5191 If FILE is a URL, download the contents. If the URL contents are
5192 already cached in the `org--file-cache' hash table, the download step
5193 is skipped.
5195 If NOERROR is non-nil, ignore the error when unable to read the FILE
5196 from file or URL.
5198 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5199 is available. This option applies only if FILE is a URL."
5200 (let* ((is-url (org-file-url-p file))
5201 (cache (and is-url
5202 (not nocache)
5203 (gethash file org--file-cache))))
5204 (cond
5205 (cache)
5206 (is-url
5207 (with-current-buffer (url-retrieve-synchronously file)
5208 (goto-char (point-min))
5209 ;; Move point to after the url-retrieve header.
5210 (search-forward "\n\n" nil :move)
5211 ;; Search for the success code only in the url-retrieve header.
5212 (if (save-excursion
5213 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5214 ;; Update the cache `org--file-cache' and return contents.
5215 (puthash file
5216 (buffer-substring-no-properties (point) (point-max))
5217 org--file-cache)
5218 (funcall (if noerror #'message #'user-error)
5219 "Unable to fetch file from %S"
5220 file))))
5222 (with-temp-buffer
5223 (condition-case nil
5224 (progn
5225 (insert-file-contents file)
5226 (buffer-string))
5227 (file-error
5228 (funcall (if noerror #'message #'user-error)
5229 "Unable to read file %S"
5230 file))))))))
5232 (defun org-extract-log-state-settings (x)
5233 "Extract the log state setting from a TODO keyword string.
5234 This will extract info from a string like \"WAIT(w@/!)\"."
5235 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5236 (let ((kw (match-string 1 x))
5237 (log1 (and (match-end 3) (match-string 3 x)))
5238 (log2 (and (match-end 4) (match-string 4 x))))
5239 (and (or log1 log2)
5240 (list kw
5241 (and log1 (if (equal log1 "!") 'time 'note))
5242 (and log2 (if (equal log2 "!") 'time 'note)))))))
5244 (defun org-remove-keyword-keys (list)
5245 "Remove a pair of parenthesis at the end of each string in LIST."
5246 (mapcar (lambda (x)
5247 (if (string-match "(.*)$" x)
5248 (substring x 0 (match-beginning 0))
5250 list))
5252 (defun org-assign-fast-keys (alist)
5253 "Assign fast keys to a keyword-key alist.
5254 Respect keys that are already there."
5255 (let (new e (alt ?0))
5256 (while (setq e (pop alist))
5257 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5258 (cdr e)) ;; Key already assigned.
5259 (push e new)
5260 (let ((clist (string-to-list (downcase (car e))))
5261 (used (append new alist)))
5262 (when (= (car clist) ?@)
5263 (pop clist))
5264 (while (and clist (rassoc (car clist) used))
5265 (pop clist))
5266 (unless clist
5267 (while (rassoc alt used)
5268 (cl-incf alt)))
5269 (push (cons (car e) (or (car clist) alt)) new))))
5270 (nreverse new)))
5272 ;;; Some variables used in various places
5274 (defvar org-window-configuration nil
5275 "Used in various places to store a window configuration.")
5276 (defvar org-selected-window nil
5277 "Used in various places to store a window configuration.")
5278 (defvar org-finish-function nil
5279 "Function to be called when `C-c C-c' is used.
5280 This is for getting out of special buffers like capture.")
5281 (defvar org-last-state)
5283 ;; Defined somewhere in this file, but used before definition.
5284 (defvar org-entities) ;; defined in org-entities.el
5285 (defvar org-struct-menu)
5286 (defvar org-org-menu)
5287 (defvar org-tbl-menu)
5289 ;;;; Define the Org mode
5291 ;; We use a before-change function to check if a table might need
5292 ;; an update.
5293 (defvar org-table-may-need-update t
5294 "Indicates that a table might need an update.
5295 This variable is set by `org-before-change-function'.
5296 `org-table-align' sets it back to nil.")
5297 (defun org-before-change-function (_beg _end)
5298 "Every change indicates that a table might need an update."
5299 (setq org-table-may-need-update t))
5300 (defvar org-mode-map)
5301 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5302 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5303 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5304 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5305 (defvar org-table-buffer-is-an nil)
5307 (defvar bidi-paragraph-direction)
5308 (defvar buffer-face-mode-face)
5310 (require 'outline)
5312 ;; Other stuff we need.
5313 (require 'time-date)
5314 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5315 (require 'easymenu)
5316 (autoload 'easy-menu-add "easymenu")
5317 (require 'overlay)
5319 ;; (require 'org-macs) moved higher up in the file before it is first used
5320 (require 'org-entities)
5321 ;; (require 'org-compat) moved higher up in the file before it is first used
5322 (require 'org-faces)
5323 (require 'org-list)
5324 (require 'org-pcomplete)
5325 (require 'org-src)
5326 (require 'org-footnote)
5327 (require 'org-macro)
5329 ;; babel
5330 (require 'ob)
5332 ;;;###autoload
5333 (define-derived-mode org-mode outline-mode "Org"
5334 "Outline-based notes management and organizer, alias
5335 \"Carsten's outline-mode for keeping track of everything.\"
5337 Org mode develops organizational tasks around a NOTES file which
5338 contains information about projects as plain text. Org mode is
5339 implemented on top of Outline mode, which is ideal to keep the content
5340 of large files well structured. It supports ToDo items, deadlines and
5341 time stamps, which magically appear in the diary listing of the Emacs
5342 calendar. Tables are easily created with a built-in table editor.
5343 Plain text URL-like links connect to websites, emails (VM), Usenet
5344 messages (Gnus), BBDB entries, and any files related to the project.
5345 For printing and sharing of notes, an Org file (or a part of it)
5346 can be exported as a structured ASCII or HTML file.
5348 The following commands are available:
5350 \\{org-mode-map}"
5352 ;; Get rid of Outline menus, they are not needed
5353 ;; Need to do this here because define-derived-mode sets up
5354 ;; the keymap so late. Still, it is a waste to call this each time
5355 ;; we switch another buffer into Org mode.
5356 (define-key org-mode-map [menu-bar headings] 'undefined)
5357 (define-key org-mode-map [menu-bar hide] 'undefined)
5358 (define-key org-mode-map [menu-bar show] 'undefined)
5360 (org-load-modules-maybe)
5361 (org-install-agenda-files-menu)
5362 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5363 (add-to-invisibility-spec '(org-hide-block . t))
5364 (add-to-invisibility-spec '(org-hide-drawer . t))
5365 (setq-local outline-regexp org-outline-regexp)
5366 (setq-local outline-level 'org-outline-level)
5367 (setq bidi-paragraph-direction 'left-to-right)
5368 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5369 (unless org-display-table
5370 (setq org-display-table (make-display-table)))
5371 (set-display-table-slot
5372 org-display-table 4
5373 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5374 org-ellipsis)))
5375 (setq buffer-display-table org-display-table))
5376 (org-set-regexps-and-options)
5377 (org-set-font-lock-defaults)
5378 (when (and org-tag-faces (not org-tags-special-faces-re))
5379 ;; tag faces set outside customize.... force initialization.
5380 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5381 ;; Calc embedded
5382 (setq-local calc-embedded-open-mode "# ")
5383 ;; Modify a few syntax entries
5384 (modify-syntax-entry ?@ "w")
5385 (modify-syntax-entry ?\" "\"")
5386 (modify-syntax-entry ?\\ "_")
5387 (modify-syntax-entry ?~ "_")
5388 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5389 ;; Activate before-change-function
5390 (setq-local org-table-may-need-update t)
5391 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5392 ;; Check for running clock before killing a buffer
5393 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5394 ;; Initialize macros templates.
5395 (org-macro-initialize-templates)
5396 ;; Initialize radio targets.
5397 (org-update-radio-target-regexp)
5398 ;; Indentation.
5399 (setq-local indent-line-function 'org-indent-line)
5400 (setq-local indent-region-function 'org-indent-region)
5401 ;; Filling and auto-filling.
5402 (org-setup-filling)
5403 ;; Comments.
5404 (org-setup-comments-handling)
5405 ;; Initialize cache.
5406 (org-element-cache-reset)
5407 ;; Beginning/end of defun
5408 (setq-local beginning-of-defun-function 'org-backward-element)
5409 (setq-local end-of-defun-function
5410 (lambda ()
5411 (if (not (org-at-heading-p))
5412 (org-forward-element)
5413 (org-forward-element)
5414 (forward-char -1))))
5415 ;; Next error for sparse trees
5416 (setq-local next-error-function 'org-occur-next-match)
5417 ;; Make sure dependence stuff works reliably, even for users who set it
5418 ;; too late :-(
5419 (if org-enforce-todo-dependencies
5420 (add-hook 'org-blocker-hook
5421 'org-block-todo-from-children-or-siblings-or-parent)
5422 (remove-hook 'org-blocker-hook
5423 'org-block-todo-from-children-or-siblings-or-parent))
5424 (if org-enforce-todo-checkbox-dependencies
5425 (add-hook 'org-blocker-hook
5426 'org-block-todo-from-checkboxes)
5427 (remove-hook 'org-blocker-hook
5428 'org-block-todo-from-checkboxes))
5430 ;; Align options lines
5431 (setq-local
5432 align-mode-rules-list
5433 '((org-in-buffer-settings
5434 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5435 (modes . '(org-mode)))))
5437 ;; Imenu
5438 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5440 ;; Make isearch reveal context
5441 (setq-local outline-isearch-open-invisible-function
5442 (lambda (&rest _) (org-show-context 'isearch)))
5444 ;; Setup the pcomplete hooks
5445 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5446 (setq-local pcomplete-command-name-function 'org-command-at-point)
5447 (setq-local pcomplete-default-completion-function 'ignore)
5448 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5449 (setq-local pcomplete-termination-string "")
5450 (setq-local buffer-face-mode-face 'org-default)
5452 ;; If empty file that did not turn on Org mode automatically, make
5453 ;; it to.
5454 (when (and org-insert-mode-line-in-empty-file
5455 (called-interactively-p 'any)
5456 (= (point-min) (point-max)))
5457 (insert "# -*- mode: org -*-\n\n"))
5458 (unless org-inhibit-startup
5459 (org-unmodified
5460 (when org-startup-with-beamer-mode (org-beamer-mode))
5461 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5462 (org-table-map-tables
5463 (cond ((and org-startup-align-all-tables
5464 org-startup-shrink-all-tables)
5465 (lambda () (org-table-align) (org-table-shrink)))
5466 (org-startup-align-all-tables #'org-table-align)
5467 (t #'org-table-shrink))
5469 (when org-startup-with-inline-images (org-display-inline-images))
5470 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5471 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5472 (when org-startup-truncated (setq truncate-lines t))
5473 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5474 (org-refresh-effort-properties)))
5475 ;; Try to set `org-hide' face correctly.
5476 (let ((foreground (org-find-invisible-foreground)))
5477 (when foreground
5478 (set-face-foreground 'org-hide foreground))))
5480 ;; Update `customize-package-emacs-version-alist'
5481 (add-to-list 'customize-package-emacs-version-alist
5482 '(Org ("8.0" . "24.4")
5483 ("8.1" . "24.4")
5484 ("8.2" . "24.4")
5485 ("8.2.7" . "24.4")
5486 ("8.3" . "26.1")
5487 ("9.0" . "26.1")
5488 ("9.1" . "26.1")
5489 ("9.2" . "27.1")))
5491 (defvar org-mode-transpose-word-syntax-table
5492 (let ((st (make-syntax-table text-mode-syntax-table)))
5493 (dolist (c org-emphasis-alist st)
5494 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5496 (when (fboundp 'abbrev-table-put)
5497 (abbrev-table-put org-mode-abbrev-table
5498 :parents (list text-mode-abbrev-table)))
5500 (defun org-find-invisible-foreground ()
5501 (let ((candidates (remove
5502 "unspecified-bg"
5503 (nconc
5504 (list (face-background 'default)
5505 (face-background 'org-default))
5506 (mapcar
5507 (lambda (alist)
5508 (when (boundp alist)
5509 (cdr (assq 'background-color (symbol-value alist)))))
5510 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5511 (list (face-foreground 'org-hide))))))
5512 (car (remove nil candidates))))
5514 (defun org-current-time (&optional rounding-minutes past)
5515 "Current time, possibly rounded to ROUNDING-MINUTES.
5516 When ROUNDING-MINUTES is not an integer, fall back on the car of
5517 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5518 the rounding returns a past time."
5519 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5520 (car org-time-stamp-rounding-minutes)))
5521 (time (decode-time)) res)
5522 (if (< r 1)
5523 (current-time)
5524 (setq res
5525 (apply 'encode-time
5526 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5527 (nthcdr 2 time))))
5528 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5529 (seconds-to-time (- (float-time res) (* r 60)))
5530 res))))
5532 (defun org-today ()
5533 "Return today date, considering `org-extend-today-until'."
5534 (time-to-days
5535 (time-subtract (current-time)
5536 (list 0 (* 3600 org-extend-today-until) 0))))
5538 ;;;; Font-Lock stuff, including the activators
5540 (defvar org-mouse-map (make-sparse-keymap))
5541 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5542 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5543 (when org-mouse-1-follows-link
5544 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5545 (when org-tab-follows-link
5546 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5547 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5549 (require 'font-lock)
5551 (defconst org-non-link-chars "]\t\n\r<>")
5552 (defvar org-link-types-re nil
5553 "Matches a link that has a url-like prefix like \"http:\"")
5554 (defvar org-link-re-with-space nil
5555 "Matches a link with spaces, optional angular brackets around it.")
5556 (defvar org-link-re-with-space2 nil
5557 "Matches a link with spaces, optional angular brackets around it.")
5558 (defvar org-link-re-with-space3 nil
5559 "Matches a link with spaces, only for internal part in bracket links.")
5560 (defvar org-angle-link-re nil
5561 "Matches link with angular brackets, spaces are allowed.")
5562 (defvar org-plain-link-re nil
5563 "Matches plain link, without spaces.")
5564 (defvar org-bracket-link-regexp nil
5565 "Matches a link in double brackets.")
5566 (defvar org-bracket-link-analytic-regexp nil
5567 "Regular expression used to analyze links.
5568 Here is what the match groups contain after a match:
5569 1: http:
5570 2: http
5571 3: path
5572 4: [desc]
5573 5: desc")
5574 (defvar org-bracket-link-analytic-regexp++ nil
5575 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5576 (defvar org-any-link-re nil
5577 "Regular expression matching any link.")
5579 (defconst org-match-sexp-depth 3
5580 "Number of stacked braces for sub/superscript matching.")
5582 (defun org-create-multibrace-regexp (left right n)
5583 "Create a regular expression which will match a balanced sexp.
5584 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5585 as single character strings.
5586 The regexp returned will match the entire expression including the
5587 delimiters. It will also define a single group which contains the
5588 match except for the outermost delimiters. The maximum depth of
5589 stacked delimiters is N. Escaping delimiters is not possible."
5590 (let* ((nothing (concat "[^" left right "]*?"))
5591 (or "\\|")
5592 (re nothing)
5593 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5594 (while (> n 1)
5595 (setq n (1- n)
5596 re (concat re or next)
5597 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5598 (concat left "\\(" re "\\)" right)))
5600 (defconst org-match-substring-regexp
5601 (concat
5602 "\\(\\S-\\)\\([_^]\\)\\("
5603 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5604 "\\|"
5605 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5606 "\\|"
5607 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5608 "The regular expression matching a sub- or superscript.")
5610 (defconst org-match-substring-with-braces-regexp
5611 (concat
5612 "\\(\\S-\\)\\([_^]\\)"
5613 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5614 "The regular expression matching a sub- or superscript, forcing braces.")
5616 (defun org-make-link-regexps ()
5617 "Update the link regular expressions.
5618 This should be called after the variable `org-link-parameters' has changed."
5619 (let ((types-re (regexp-opt (org-link-types) t)))
5620 (setq org-link-types-re
5621 (concat "\\`" types-re ":")
5622 org-link-re-with-space
5623 (concat "<?" types-re ":"
5624 "\\([^" org-non-link-chars " ]"
5625 "[^" org-non-link-chars "]*"
5626 "[^" org-non-link-chars " ]\\)>?")
5627 org-link-re-with-space2
5628 (concat "<?" types-re ":"
5629 "\\([^" org-non-link-chars " ]"
5630 "[^\t\n\r]*"
5631 "[^" org-non-link-chars " ]\\)>?")
5632 org-link-re-with-space3
5633 (concat "<?" types-re ":"
5634 "\\([^" org-non-link-chars " ]"
5635 "[^\t\n\r]*\\)")
5636 org-angle-link-re
5637 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5638 types-re)
5639 org-plain-link-re
5640 (concat
5641 "\\<" types-re ":"
5642 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5643 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5644 org-bracket-link-regexp
5645 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5646 org-bracket-link-analytic-regexp
5647 (concat
5648 "\\[\\["
5649 "\\(" types-re ":\\)?"
5650 "\\([^]]+\\)"
5651 "\\]"
5652 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5653 "\\]")
5654 org-bracket-link-analytic-regexp++
5655 (concat
5656 "\\[\\["
5657 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5658 "\\([^]]+\\)"
5659 "\\]"
5660 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5661 "\\]")
5662 org-any-link-re
5663 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5664 org-angle-link-re "\\)\\|\\("
5665 org-plain-link-re "\\)"))))
5667 (org-make-link-regexps)
5669 (defvar org-emph-face nil)
5671 (defun org-do-emphasis-faces (limit)
5672 "Run through the buffer and emphasize strings."
5673 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5674 (car org-emphasis-regexp-components))))
5675 (catch :exit
5676 (while (re-search-forward quick-re limit t)
5677 (let* ((marker (match-string 2))
5678 (verbatim? (member marker '("~" "="))))
5679 (when (save-excursion
5680 (goto-char (match-beginning 0))
5681 (and
5682 ;; Do not match table hlines.
5683 (not (and (equal marker "+")
5684 (org-match-line
5685 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5686 ;; Do not match headline stars. Do not consider
5687 ;; stars of a headline as closing marker for bold
5688 ;; markup either.
5689 (not (and (equal marker "*")
5690 (save-excursion
5691 (forward-char)
5692 (skip-chars-backward "*")
5693 (looking-at-p org-outline-regexp-bol))))
5694 ;; Match full emphasis markup regexp.
5695 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5696 ;; Do not span over paragraph boundaries.
5697 (not (string-match-p org-element-paragraph-separate
5698 (match-string 2)))
5699 ;; Do not span over cells in table rows.
5700 (not (and (save-match-data (org-match-line "[ \t]*|"))
5701 (string-match-p "|" (match-string 4))))))
5702 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5703 (font-lock-prepend-text-property
5704 (match-beginning 2) (match-end 2) 'face face)
5705 (when verbatim?
5706 (org-remove-flyspell-overlays-in
5707 (match-beginning 0) (match-end 0)))
5708 (add-text-properties (match-beginning 2) (match-end 2)
5709 '(font-lock-multiline t org-emphasis t))
5710 (when org-hide-emphasis-markers
5711 (add-text-properties (match-end 4) (match-beginning 5)
5712 '(invisible org-link))
5713 (add-text-properties (match-beginning 3) (match-end 3)
5714 '(invisible org-link)))
5715 (throw :exit t))))))))
5717 (defun org-emphasize (&optional char)
5718 "Insert or change an emphasis, i.e. a font like bold or italic.
5719 If there is an active region, change that region to a new emphasis.
5720 If there is no region, just insert the marker characters and position
5721 the cursor between them.
5722 CHAR should be the marker character. If it is a space, it means to
5723 remove the emphasis of the selected region.
5724 If CHAR is not given (for example in an interactive call) it will be
5725 prompted for."
5726 (interactive)
5727 (let ((erc org-emphasis-regexp-components)
5728 (string "") beg end move s)
5729 (if (org-region-active-p)
5730 (setq beg (region-beginning)
5731 end (region-end)
5732 string (buffer-substring beg end))
5733 (setq move t))
5735 (unless char
5736 (message "Emphasis marker or tag: [%s]"
5737 (mapconcat #'car org-emphasis-alist ""))
5738 (setq char (read-char-exclusive)))
5739 (if (equal char ?\s)
5740 (setq s ""
5741 move nil)
5742 (unless (assoc (char-to-string char) org-emphasis-alist)
5743 (user-error "No such emphasis marker: \"%c\"" char))
5744 (setq s (char-to-string char)))
5745 (while (and (> (length string) 1)
5746 (equal (substring string 0 1) (substring string -1))
5747 (assoc (substring string 0 1) org-emphasis-alist))
5748 (setq string (substring string 1 -1)))
5749 (setq string (concat s string s))
5750 (when beg (delete-region beg end))
5751 (unless (or (bolp)
5752 (string-match (concat "[" (nth 0 erc) "\n]")
5753 (char-to-string (char-before (point)))))
5754 (insert " "))
5755 (unless (or (eobp)
5756 (string-match (concat "[" (nth 1 erc) "\n]")
5757 (char-to-string (char-after (point)))))
5758 (insert " ") (backward-char 1))
5759 (insert string)
5760 (and move (backward-char 1))))
5762 (defconst org-nonsticky-props
5763 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5765 (defsubst org-rear-nonsticky-at (pos)
5766 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5768 (defun org-activate-links (limit)
5769 "Add link properties to links.
5770 This includes angle, plain, and bracket links."
5771 (catch :exit
5772 (while (re-search-forward org-any-link-re limit t)
5773 (let* ((start (match-beginning 0))
5774 (end (match-end 0))
5775 (style (cond ((eq ?< (char-after start)) 'angle)
5776 ((eq ?\[ (char-after (1+ start))) 'bracket)
5777 (t 'plain))))
5778 (when (and (memq style org-highlight-links)
5779 ;; Do not confuse plain links with tags.
5780 (not (and (eq style 'plain)
5781 (let ((face (get-text-property
5782 (max (1- start) (point-min)) 'face)))
5783 (if (consp face) (memq 'org-tag face)
5784 (eq 'org-tag face))))))
5785 (let* ((link-object (save-excursion
5786 (goto-char start)
5787 (save-match-data (org-element-link-parser))))
5788 (link (org-element-property :raw-link link-object))
5789 (type (org-element-property :type link-object))
5790 (path (org-element-property :path link-object))
5791 (properties ;for link's visible part
5792 (list
5793 'face (pcase (org-link-get-parameter type :face)
5794 ((and (pred functionp) face) (funcall face path))
5795 ((and (pred facep) face) face)
5796 ((and (pred consp) face) face) ;anonymous
5797 (_ 'org-link))
5798 'mouse-face (or (org-link-get-parameter type :mouse-face)
5799 'highlight)
5800 'keymap (or (org-link-get-parameter type :keymap)
5801 org-mouse-map)
5802 'help-echo (pcase (org-link-get-parameter type :help-echo)
5803 ((and (pred stringp) echo) echo)
5804 ((and (pred functionp) echo) echo)
5805 (_ (concat "LINK: " link)))
5806 'htmlize-link (pcase (org-link-get-parameter type
5807 :htmlize-link)
5808 ((and (pred functionp) f) (funcall f))
5809 (_ `(:uri ,link)))
5810 'font-lock-multiline t)))
5811 (org-remove-flyspell-overlays-in start end)
5812 (org-rear-nonsticky-at end)
5813 (if (not (eq 'bracket style))
5814 (add-text-properties start end properties)
5815 ;; Handle invisible parts in bracket links.
5816 (remove-text-properties start end '(invisible nil))
5817 (let ((hidden
5818 (append `(invisible
5819 ,(or (org-link-get-parameter type :display)
5820 'org-link))
5821 properties))
5822 (visible-start (or (match-beginning 4) (match-beginning 2)))
5823 (visible-end (or (match-end 4) (match-end 2))))
5824 (add-text-properties start visible-start hidden)
5825 (add-text-properties visible-start visible-end properties)
5826 (add-text-properties visible-end end hidden)
5827 (org-rear-nonsticky-at visible-start)
5828 (org-rear-nonsticky-at visible-end)))
5829 (let ((f (org-link-get-parameter type :activate-func)))
5830 (when (functionp f)
5831 (funcall f start end path (eq style 'bracket))))
5832 (throw :exit t))))) ;signal success
5833 nil))
5835 (defun org-activate-code (limit)
5836 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5837 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5838 (remove-text-properties (match-beginning 0) (match-end 0)
5839 '(display t invisible t intangible t))
5842 (defcustom org-src-fontify-natively t
5843 "When non-nil, fontify code in code blocks.
5844 See also the `org-block' face."
5845 :type 'boolean
5846 :version "26.1"
5847 :package-version '(Org . "8.3")
5848 :group 'org-appearance
5849 :group 'org-babel)
5851 (defcustom org-allow-promoting-top-level-subtree nil
5852 "When non-nil, allow promoting a top level subtree.
5853 The leading star of the top level headline will be replaced
5854 by a #."
5855 :type 'boolean
5856 :version "24.1"
5857 :group 'org-appearance)
5859 (defun org-fontify-meta-lines-and-blocks (limit)
5860 (condition-case nil
5861 (org-fontify-meta-lines-and-blocks-1 limit)
5862 (error (message "Org mode fontification error in %S at %d"
5863 (current-buffer)
5864 (line-number-at-pos)))))
5866 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5867 "Fontify #+ lines and blocks."
5868 (let ((case-fold-search t))
5869 (when (re-search-forward
5870 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5871 limit t)
5872 (let ((beg (match-beginning 0))
5873 (block-start (match-end 0))
5874 (block-end nil)
5875 (lang (match-string 7))
5876 (beg1 (line-beginning-position 2))
5877 (dc1 (downcase (match-string 2)))
5878 (dc3 (downcase (match-string 3)))
5879 end end1 quoting block-type)
5880 (cond
5881 ((and (match-end 4) (equal dc3 "+begin"))
5882 ;; Truly a block
5883 (setq block-type (downcase (match-string 5))
5884 quoting (member block-type org-protecting-blocks))
5885 (when (re-search-forward
5886 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5887 nil t) ;; on purpose, we look further than LIMIT
5888 (setq end (min (point-max) (match-end 0))
5889 end1 (min (point-max) (1- (match-beginning 0))))
5890 (setq block-end (match-beginning 0))
5891 (when quoting
5892 (org-remove-flyspell-overlays-in beg1 end1)
5893 (remove-text-properties beg end
5894 '(display t invisible t intangible t)))
5895 (add-text-properties
5896 beg end '(font-lock-fontified t font-lock-multiline t))
5897 (add-text-properties beg beg1 '(face org-meta-line))
5898 (org-remove-flyspell-overlays-in beg beg1)
5899 (add-text-properties ; For end_src
5900 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5901 (org-remove-flyspell-overlays-in end1 end)
5902 (cond
5903 ((and lang (not (string= lang "")) org-src-fontify-natively)
5904 (org-src-font-lock-fontify-block lang block-start block-end)
5905 (add-text-properties beg1 block-end '(src-block t)))
5906 (quoting
5907 (add-text-properties beg1 (min (point-max) (1+ end1))
5908 (list 'face
5909 (list :inherit
5910 (let ((face-name
5911 (intern (format "org-block-%s" lang))))
5912 (append (and (facep face-name) (list face-name))
5913 '(org-block))))))) ; end of source block
5914 ((not org-fontify-quote-and-verse-blocks))
5915 ((string= block-type "quote")
5916 (add-face-text-property
5917 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5918 ((string= block-type "verse")
5919 (add-face-text-property
5920 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5921 (add-text-properties beg beg1 '(face org-block-begin-line))
5922 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5923 '(face org-block-end-line))
5925 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5926 (org-remove-flyspell-overlays-in
5927 (match-beginning 0)
5928 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5929 (add-text-properties
5930 beg (match-end 3)
5931 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5932 '(font-lock-fontified t invisible t)
5933 '(font-lock-fontified t face org-document-info-keyword)))
5934 (add-text-properties
5935 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5936 (if (string-equal dc1 "+title:")
5937 '(font-lock-fontified t face org-document-title)
5938 '(font-lock-fontified t face org-document-info))))
5939 ((string-prefix-p "+caption" dc1)
5940 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5941 (remove-text-properties (match-beginning 0) (match-end 0)
5942 '(display t invisible t intangible t))
5943 ;; Handle short captions.
5944 (save-excursion
5945 (beginning-of-line)
5946 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5947 (add-text-properties (line-beginning-position) (match-end 1)
5948 '(font-lock-fontified t face org-meta-line))
5949 (add-text-properties (match-end 0) (line-end-position)
5950 '(font-lock-fontified t face org-block))
5952 ((member dc3 '(" " ""))
5953 (org-remove-flyspell-overlays-in beg (match-end 0))
5954 (add-text-properties
5955 beg (match-end 0)
5956 '(font-lock-fontified t face font-lock-comment-face)))
5957 (t ;; just any other in-buffer setting, but not indented
5958 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5959 (remove-text-properties (match-beginning 0) (match-end 0)
5960 '(display t invisible t intangible t))
5961 (add-text-properties beg (match-end 0)
5962 '(font-lock-fontified t face org-meta-line))
5963 t))))))
5965 (defun org-fontify-drawers (limit)
5966 "Fontify drawers."
5967 (when (re-search-forward org-drawer-regexp limit t)
5968 (add-text-properties
5969 (match-beginning 0) (match-end 0)
5970 '(font-lock-fontified t face org-special-keyword))
5971 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5974 (defun org-fontify-macros (limit)
5975 "Fontify macros."
5976 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
5977 (let ((begin (match-beginning 0))
5978 (opening-end (match-beginning 1)))
5979 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
5980 (match-string 1))
5981 (let ((end (match-end 1))
5982 (closing-start (match-beginning 1)))
5983 (add-text-properties
5984 begin end
5985 '(font-lock-multiline t font-lock-fontified t face org-macro))
5986 (org-remove-flyspell-overlays-in begin end)
5987 (when org-hide-macro-markers
5988 (add-text-properties begin opening-end '(invisible t))
5989 (add-text-properties closing-start end '(invisible t)))
5990 t)))))
5992 (defun org-activate-footnote-links (limit)
5993 "Add text properties for footnotes."
5994 (let ((fn (org-footnote-next-reference-or-definition limit)))
5995 (when fn
5996 (let* ((beg (nth 1 fn))
5997 (end (nth 2 fn))
5998 (label (car fn))
5999 (referencep (/= (line-beginning-position) beg)))
6000 (when (and referencep (nth 3 fn))
6001 (save-excursion
6002 (goto-char beg)
6003 (search-forward (or label "fn:"))
6004 (org-remove-flyspell-overlays-in beg (match-end 0))))
6005 (add-text-properties beg end
6006 (list 'mouse-face 'highlight
6007 'keymap org-mouse-map
6008 'help-echo
6009 (if referencep "Footnote reference"
6010 "Footnote definition")
6011 'font-lock-fontified t
6012 'font-lock-multiline t
6013 'face 'org-footnote))))))
6015 (defun org-activate-dates (limit)
6016 "Add text properties for dates."
6017 (when (and (re-search-forward org-tsr-regexp-both limit t)
6018 (not (equal (char-before (match-beginning 0)) 91)))
6019 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6020 (add-text-properties (match-beginning 0) (match-end 0)
6021 (list 'mouse-face 'highlight
6022 'keymap org-mouse-map))
6023 (org-rear-nonsticky-at (match-end 0))
6024 (when org-display-custom-times
6025 ;; If it's a date range, activate custom time for second date.
6026 (when (match-end 3)
6027 (org-display-custom-time (match-beginning 3) (match-end 3)))
6028 (org-display-custom-time (match-beginning 1) (match-end 1)))
6031 (defvar-local org-target-link-regexp nil
6032 "Regular expression matching radio targets in plain text.")
6034 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6035 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6036 border border border))
6037 "Regular expression matching a link target.")
6039 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6040 "Regular expression matching a radio target.")
6042 (defconst org-any-target-regexp
6043 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6044 "Regular expression matching any target.")
6046 (defun org-activate-target-links (limit)
6047 "Add text properties for target matches."
6048 (when org-target-link-regexp
6049 (let ((case-fold-search t))
6050 (when (re-search-forward org-target-link-regexp limit t)
6051 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6052 (add-text-properties (match-beginning 1) (match-end 1)
6053 (list 'mouse-face 'highlight
6054 'keymap org-mouse-map
6055 'help-echo "Radio target link"
6056 'org-linked-text t))
6057 (org-rear-nonsticky-at (match-end 1))
6058 t))))
6060 (defun org-update-radio-target-regexp ()
6061 "Find all radio targets in this file and update the regular expression.
6062 Also refresh fontification if needed."
6063 (interactive)
6064 (let ((old-regexp org-target-link-regexp)
6065 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6066 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6067 (targets
6068 (org-with-wide-buffer
6069 (goto-char (point-min))
6070 (let (rtn)
6071 (while (re-search-forward org-radio-target-regexp nil t)
6072 ;; Make sure point is really within the object.
6073 (backward-char)
6074 (let ((obj (org-element-context)))
6075 (when (eq (org-element-type obj) 'radio-target)
6076 (cl-pushnew (org-element-property :value obj) rtn
6077 :test #'equal))))
6078 rtn))))
6079 (setq org-target-link-regexp
6080 (and targets
6081 (concat before-re
6082 (mapconcat
6083 (lambda (x)
6084 (replace-regexp-in-string
6085 " +" "\\s-+" (regexp-quote x) t t))
6086 targets
6087 "\\|")
6088 after-re)))
6089 (unless (equal old-regexp org-target-link-regexp)
6090 ;; Clean-up cache.
6091 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6092 ((not org-target-link-regexp) old-regexp)
6094 (concat before-re
6095 (mapconcat
6096 (lambda (re)
6097 (substring re (length before-re)
6098 (- (length after-re))))
6099 (list old-regexp org-target-link-regexp)
6100 "\\|")
6101 after-re)))))
6102 (org-with-wide-buffer
6103 (goto-char (point-min))
6104 (while (re-search-forward regexp nil t)
6105 (org-element-cache-refresh (match-beginning 1)))))
6106 ;; Re fontify buffer.
6107 (when (memq 'radio org-highlight-links)
6108 (org-restart-font-lock)))))
6110 (defvar org-latex-and-related-regexp nil
6111 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6113 (defun org-compute-latex-and-related-regexp ()
6114 "Compute regular expression for LaTeX, entities and sub/superscript.
6115 Result depends on variable `org-highlight-latex-and-related'."
6116 (setq-local
6117 org-latex-and-related-regexp
6118 (let* ((re-sub
6119 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6120 ((eq org-use-sub-superscripts '{})
6121 (list org-match-substring-with-braces-regexp))
6122 (org-use-sub-superscripts (list org-match-substring-regexp))))
6123 (re-latex
6124 (when (memq 'latex org-highlight-latex-and-related)
6125 (let ((matchers (plist-get org-format-latex-options :matchers)))
6126 (delq nil
6127 (mapcar (lambda (x)
6128 (and (member (car x) matchers) (nth 1 x)))
6129 org-latex-regexps)))))
6130 (re-entities
6131 (when (memq 'entities org-highlight-latex-and-related)
6132 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6133 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6135 (defun org-do-latex-and-related (limit)
6136 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6137 LIMIT bounds the search for syntax to highlight. Stop at first
6138 highlighted object, if any. Return t if some highlighting was
6139 done, nil otherwise."
6140 (when (org-string-nw-p org-latex-and-related-regexp)
6141 (catch 'found
6142 (while (re-search-forward org-latex-and-related-regexp limit t)
6143 (unless
6144 (cl-some
6145 (lambda (f)
6146 (memq f '(org-code org-verbatim underline org-special-keyword)))
6147 (save-excursion
6148 (goto-char (1+ (match-beginning 0)))
6149 (face-at-point nil t)))
6150 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6151 '(?_ ?^))
6153 0)))
6154 (font-lock-prepend-text-property
6155 (+ offset (match-beginning 0)) (match-end 0)
6156 'face 'org-latex-and-related)
6157 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6158 '(font-lock-multiline t)))
6159 (throw 'found t)))
6160 nil)))
6162 (defun org-restart-font-lock ()
6163 "Restart `font-lock-mode', to force refontification."
6164 (when (and (boundp 'font-lock-mode) font-lock-mode)
6165 (font-lock-mode -1)
6166 (font-lock-mode 1)))
6168 (defun org-activate-tags (limit)
6169 (when (re-search-forward
6170 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6171 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6172 (add-text-properties (match-beginning 1) (match-end 1)
6173 (list 'mouse-face 'highlight
6174 'keymap org-mouse-map))
6175 (org-rear-nonsticky-at (match-end 1))
6178 (defun org-outline-level ()
6179 "Compute the outline level of the heading at point.
6181 If this is called at a normal headline, the level is the number
6182 of stars. Use `org-reduced-level' to remove the effect of
6183 `org-odd-levels'. Unlike to `org-current-level', this function
6184 takes into consideration inlinetasks."
6185 (org-with-wide-buffer
6186 (end-of-line)
6187 (if (re-search-backward org-outline-regexp-bol nil t)
6188 (1- (- (match-end 0) (match-beginning 0)))
6189 0)))
6191 (defvar org-font-lock-keywords nil)
6193 (defsubst org-re-property (property &optional literal allow-null value)
6194 "Return a regexp matching a PROPERTY line.
6196 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6197 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6198 non-nil, match properties even without a value.
6200 Match group 3 is set to the value when it exists. If there is no
6201 value and ALLOW-NULL is non-nil, it is set to the empty string.
6203 With optional argument VALUE, match only property lines with
6204 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6205 unless LITERAL is non-nil."
6206 (concat
6207 "^\\(?4:[ \t]*\\)"
6208 (format "\\(?1::\\(?2:%s\\):\\)"
6209 (if literal property (regexp-quote property)))
6210 (cond (value
6211 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6212 (if literal value (regexp-quote value))))
6213 (allow-null
6214 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6216 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6218 (defconst org-property-re
6219 (org-re-property "\\S-+" 'literal t)
6220 "Regular expression matching a property line.
6221 There are four matching groups:
6222 1: :PROPKEY: including the leading and trailing colon,
6223 2: PROPKEY without the leading and trailing colon,
6224 3: PROPVAL without leading or trailing spaces,
6225 4: the indentation of the current line,
6226 5: trailing whitespace.")
6228 (defvar org-font-lock-hook nil
6229 "Functions to be called for special font lock stuff.")
6231 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6233 (defvar org-font-lock-set-keywords-hook nil
6234 "Functions that can manipulate `org-font-lock-extra-keywords'.
6235 This is called after `org-font-lock-extra-keywords' is defined, but before
6236 it is installed to be used by font lock. This can be useful if something
6237 needs to be inserted at a specific position in the font-lock sequence.")
6239 (defun org-font-lock-hook (limit)
6240 "Run `org-font-lock-hook' within LIMIT."
6241 (run-hook-with-args 'org-font-lock-hook limit))
6243 (defun org-set-font-lock-defaults ()
6244 "Set font lock defaults for the current buffer."
6245 (let* ((em org-fontify-emphasized-text)
6246 (lk org-highlight-links)
6247 (org-font-lock-extra-keywords
6248 (list
6249 ;; Call the hook
6250 '(org-font-lock-hook)
6251 ;; Headlines
6252 `(,(if org-fontify-whole-heading-line
6253 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6254 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6255 (1 (org-get-level-face 1))
6256 (2 (org-get-level-face 2))
6257 (3 (org-get-level-face 3)))
6258 ;; Table lines
6259 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6260 (1 'org-table t))
6261 ;; Table internals
6262 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6263 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6264 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6265 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6266 ;; Drawers
6267 '(org-fontify-drawers)
6268 ;; Properties
6269 (list org-property-re
6270 '(1 'org-special-keyword t)
6271 '(3 'org-property-value t))
6272 ;; Link related fontification.
6273 '(org-activate-links)
6274 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6275 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6276 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6277 (when (memq 'footnote lk) '(org-activate-footnote-links))
6278 ;; Targets.
6279 (list org-any-target-regexp '(0 'org-target t))
6280 ;; Diary sexps.
6281 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6282 ;; Macro
6283 '(org-fontify-macros)
6284 ;; TODO keyword
6285 (list (format org-heading-keyword-regexp-format
6286 org-todo-regexp)
6287 '(2 (org-get-todo-face 2) t))
6288 ;; DONE
6289 (if org-fontify-done-headline
6290 (list (format org-heading-keyword-regexp-format
6291 (concat
6292 "\\(?:"
6293 (mapconcat 'regexp-quote org-done-keywords "\\|")
6294 "\\)"))
6295 '(2 'org-headline-done t))
6296 nil)
6297 ;; Priorities
6298 '(org-font-lock-add-priority-faces)
6299 ;; Tags
6300 '(org-font-lock-add-tag-faces)
6301 ;; Tags groups
6302 (when (and org-group-tags org-tag-groups-alist)
6303 (list (concat org-outline-regexp-bol ".+\\(:"
6304 (regexp-opt (mapcar 'car org-tag-groups-alist))
6305 ":\\).*$")
6306 '(1 'org-tag-group prepend)))
6307 ;; Special keywords
6308 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6309 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6310 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6311 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6312 ;; Emphasis
6313 (when em '(org-do-emphasis-faces))
6314 ;; Checkboxes
6315 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6316 1 'org-checkbox prepend)
6317 (when (cdr (assq 'checkbox org-list-automatic-rules))
6318 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6319 (0 (org-get-checkbox-statistics-face) t)))
6320 ;; Description list items
6321 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6322 1 'org-list-dt prepend)
6323 ;; ARCHIVEd headings
6324 (list (concat
6325 org-outline-regexp-bol
6326 "\\(.*:" org-archive-tag ":.*\\)")
6327 '(1 'org-archived prepend))
6328 ;; Specials
6329 '(org-do-latex-and-related)
6330 '(org-fontify-entities)
6331 '(org-raise-scripts)
6332 ;; Code
6333 '(org-activate-code (1 'org-code t))
6334 ;; COMMENT
6335 (list (format
6336 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6337 org-todo-regexp
6338 org-comment-string)
6339 '(9 'org-special-keyword t))
6340 ;; Blocks and meta lines
6341 '(org-fontify-meta-lines-and-blocks))))
6342 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6343 (run-hooks 'org-font-lock-set-keywords-hook)
6344 ;; Now set the full font-lock-keywords
6345 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6346 (setq-local font-lock-defaults
6347 '(org-font-lock-keywords t nil nil backward-paragraph))
6348 (kill-local-variable 'font-lock-keywords)
6349 nil))
6351 (defun org-toggle-pretty-entities ()
6352 "Toggle the composition display of entities as UTF8 characters."
6353 (interactive)
6354 (setq-local org-pretty-entities (not org-pretty-entities))
6355 (org-restart-font-lock)
6356 (if org-pretty-entities
6357 (message "Entities are now displayed as UTF8 characters")
6358 (save-restriction
6359 (widen)
6360 (decompose-region (point-min) (point-max))
6361 (message "Entities are now displayed as plain text"))))
6363 (defvar-local org-custom-properties-overlays nil
6364 "List of overlays used for custom properties.")
6366 (defun org-toggle-custom-properties-visibility ()
6367 "Display or hide properties in `org-custom-properties'."
6368 (interactive)
6369 (if org-custom-properties-overlays
6370 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6371 (setq org-custom-properties-overlays nil))
6372 (when org-custom-properties
6373 (org-with-wide-buffer
6374 (goto-char (point-min))
6375 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6376 (while (re-search-forward regexp nil t)
6377 (let ((end (cdr (save-match-data (org-get-property-block)))))
6378 (when (and end (< (point) end))
6379 ;; Hide first custom property in current drawer.
6380 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6381 (overlay-put o 'invisible t)
6382 (overlay-put o 'org-custom-property t)
6383 (push o org-custom-properties-overlays))
6384 ;; Hide additional custom properties in the same drawer.
6385 (while (re-search-forward regexp end t)
6386 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6387 (overlay-put o 'invisible t)
6388 (overlay-put o 'org-custom-property t)
6389 (push o org-custom-properties-overlays)))))
6390 ;; Each entry is limited to a single property drawer.
6391 (outline-next-heading)))))))
6393 (defun org-fontify-entities (limit)
6394 "Find an entity to fontify."
6395 (let (ee)
6396 (when org-pretty-entities
6397 (catch 'match
6398 ;; "\_ "-family is left out on purpose. Only the first one,
6399 ;; i.e., "\_ ", could be fontified anyway, and it would be
6400 ;; confusing when adding a second white space character.
6401 (while (re-search-forward
6402 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6403 limit t)
6404 (when (and (not (org-at-comment-p))
6405 (setq ee (org-entity-get (match-string 1)))
6406 (= (length (nth 6 ee)) 1))
6407 (let* ((end (if (equal (match-string 2) "{}")
6408 (match-end 2)
6409 (match-end 1))))
6410 (add-text-properties
6411 (match-beginning 0) end
6412 (list 'font-lock-fontified t))
6413 (compose-region (match-beginning 0) end
6414 (nth 6 ee) nil)
6415 (backward-char 1)
6416 (throw 'match t))))
6417 nil))))
6419 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6420 "Fontify string S like in Org mode."
6421 (with-temp-buffer
6422 (insert s)
6423 (let ((org-odd-levels-only odd-levels))
6424 (org-mode)
6425 (org-font-lock-ensure)
6426 (buffer-string))))
6428 (defvar org-m nil)
6429 (defvar org-l nil)
6430 (defvar org-f nil)
6431 (defun org-get-level-face (n)
6432 "Get the right face for match N in font-lock matching of headlines."
6433 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6434 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6435 (if org-cycle-level-faces
6436 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6437 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6438 (cond
6439 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6440 ((eq n 2) org-f)
6441 (t (unless org-level-color-stars-only org-f))))
6443 (defun org-face-from-face-or-color (context inherit face-or-color)
6444 "Create a face list that inherits INHERIT, but sets the foreground color.
6445 When FACE-OR-COLOR is not a string, just return it."
6446 (if (stringp face-or-color)
6447 (list :inherit inherit
6448 (cdr (assoc context org-faces-easy-properties))
6449 face-or-color)
6450 face-or-color))
6452 (defun org-get-todo-face (kwd)
6453 "Get the right face for a TODO keyword KWD.
6454 If KWD is a number, get the corresponding match group."
6455 (when (numberp kwd) (setq kwd (match-string kwd)))
6456 (or (org-face-from-face-or-color
6457 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6458 (and (member kwd org-done-keywords) 'org-done)
6459 'org-todo))
6461 (defun org-get-priority-face (priority)
6462 "Get the right face for PRIORITY.
6463 PRIORITY is a character."
6464 (or (org-face-from-face-or-color
6465 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6466 'org-priority))
6468 (defun org-get-tag-face (tag)
6469 "Get the right face for TAG.
6470 If TAG is a number, get the corresponding match group."
6471 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6472 (or (org-face-from-face-or-color
6473 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6474 'org-tag)))
6476 (defun org-font-lock-add-priority-faces (limit)
6477 "Add the special priority faces."
6478 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6479 (add-text-properties
6480 (match-beginning 1) (match-end 1)
6481 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6482 'font-lock-fontified t))))
6484 (defun org-font-lock-add-tag-faces (limit)
6485 "Add the special tag faces."
6486 (when (and org-tag-faces org-tags-special-faces-re)
6487 (while (re-search-forward org-tags-special-faces-re limit t)
6488 (add-text-properties (match-beginning 1) (match-end 1)
6489 (list 'face (org-get-tag-face 1)
6490 'font-lock-fontified t))
6491 (backward-char 1))))
6493 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6494 "Remove fontification and activation overlays from links."
6495 (font-lock-default-unfontify-region beg end)
6496 (let* ((buffer-undo-list t)
6497 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6498 (inhibit-modification-hooks t)
6499 deactivate-mark buffer-file-name buffer-file-truename)
6500 (decompose-region beg end)
6501 (remove-text-properties beg end
6502 '(mouse-face t keymap t org-linked-text t
6503 invisible t intangible t
6504 org-emphasis t))
6505 (org-remove-font-lock-display-properties beg end)))
6507 (defconst org-script-display '(((raise -0.3) (height 0.7))
6508 ((raise 0.3) (height 0.7))
6509 ((raise -0.5))
6510 ((raise 0.5)))
6511 "Display properties for showing superscripts and subscripts.")
6513 (defun org-remove-font-lock-display-properties (beg end)
6514 "Remove specific display properties that have been added by font lock.
6515 The will remove the raise properties that are used to show superscripts
6516 and subscripts."
6517 (let (next prop)
6518 (while (< beg end)
6519 (setq next (next-single-property-change beg 'display nil end)
6520 prop (get-text-property beg 'display))
6521 (when (member prop org-script-display)
6522 (put-text-property beg next 'display nil))
6523 (setq beg next))))
6525 (defun org-raise-scripts (limit)
6526 "Add raise properties to sub/superscripts."
6527 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6528 (re-search-forward
6529 (if (eq org-use-sub-superscripts t)
6530 org-match-substring-regexp
6531 org-match-substring-with-braces-regexp)
6532 limit t))
6533 (let* ((pos (point)) table-p comment-p
6534 (mpos (match-beginning 3))
6535 (emph-p (get-text-property mpos 'org-emphasis))
6536 (link-p (get-text-property mpos 'mouse-face))
6537 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6538 (goto-char (point-at-bol))
6539 (setq table-p (looking-at-p org-table-dataline-regexp)
6540 comment-p (looking-at-p "^[ \t]*#[ +]"))
6541 (goto-char pos)
6542 ;; Handle a_b^c
6543 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6544 (unless (or comment-p emph-p link-p keyw-p)
6545 (put-text-property (match-beginning 3) (match-end 0)
6546 'display
6547 (if (equal (char-after (match-beginning 2)) ?^)
6548 (nth (if table-p 3 1) org-script-display)
6549 (nth (if table-p 2 0) org-script-display)))
6550 (add-text-properties (match-beginning 2) (match-end 2)
6551 (list 'invisible t))
6552 (when (and (eq (char-after (match-beginning 3)) ?{)
6553 (eq (char-before (match-end 3)) ?}))
6554 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6555 (list 'invisible t))
6556 (add-text-properties (1- (match-end 3)) (match-end 3)
6557 (list 'invisible t))))
6558 t)))
6560 (defun org-remove-empty-overlays-at (pos)
6561 "Remove outline overlays that do not contain non-white stuff."
6562 (dolist (o (overlays-at pos))
6563 (and (eq 'outline (overlay-get o 'invisible))
6564 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6565 (overlay-end o))))
6566 (delete-overlay o))))
6568 (defun org-show-empty-lines-in-parent ()
6569 "Move to the parent and re-show empty lines before visible headlines."
6570 (save-excursion
6571 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6572 (org-cycle-show-empty-lines context))))
6574 (defun org-files-list ()
6575 "Return `org-agenda-files' list, plus all open Org files.
6576 This is useful for operations that need to scan all of a user's
6577 open and agenda-wise Org files."
6578 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6579 (dolist (buf (buffer-list))
6580 (with-current-buffer buf
6581 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6582 (cl-pushnew (expand-file-name (buffer-file-name)) files
6583 :test #'equal))))
6584 files))
6586 (defsubst org-entry-beginning-position ()
6587 "Return the beginning position of the current entry."
6588 (save-excursion (org-back-to-heading t) (point)))
6590 (defsubst org-entry-end-position ()
6591 "Return the end position of the current entry."
6592 (save-excursion (outline-next-heading) (point)))
6594 (defun org-subtree-end-visible-p ()
6595 "Is the end of the current subtree visible?"
6596 (pos-visible-in-window-p
6597 (save-excursion (org-end-of-subtree t) (point))))
6599 (defun org-first-headline-recenter ()
6600 "Move cursor to the first headline and recenter the headline."
6601 (let ((window (get-buffer-window)))
6602 (when window
6603 (goto-char (point-min))
6604 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6605 (set-window-start window (line-beginning-position))))))
6608 ;;; Visibility (headlines, blocks, drawers)
6610 (defun org-flag-region (from to flag spec)
6611 "Hide or show lines from FROM to TO, according to FLAG.
6612 SPEC is the invisibility spec, as a symbol."
6613 (remove-overlays from to 'invisible spec)
6614 ;; Use `front-advance' since text right before to the beginning of
6615 ;; the overlay belongs to the visible line than to the contents.
6616 (when flag
6617 (let ((o (make-overlay from to nil 'front-advance)))
6618 (overlay-put o 'evaporate t)
6619 (overlay-put o 'invisible spec)
6620 (overlay-put o 'isearch-open-invisible #'delete-overlay))))
6622 ;;;; Headlines visibility
6624 (defun org-show-entry ()
6625 "Show the body directly following this heading.
6626 Show the heading too, if it is currently invisible."
6627 (interactive)
6628 (save-excursion
6629 (ignore-errors
6630 (org-back-to-heading t)
6631 (org-flag-region
6632 (line-end-position 0)
6633 (save-excursion
6634 (if (re-search-forward
6635 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6636 (match-beginning 1)
6637 (point-max)))
6639 'outline))))
6641 (defun org-show-children (&optional level)
6642 "Show all direct subheadings of this heading.
6643 Prefix arg LEVEL is how many levels below the current level
6644 should be shown. Default is enough to cause the following
6645 heading to appear."
6646 (interactive "p")
6647 (save-excursion
6648 (org-back-to-heading t)
6649 (let* ((current-level (funcall outline-level))
6650 (max-level (org-get-valid-level
6651 current-level
6652 (if level (prefix-numeric-value level) 1)))
6653 (end (save-excursion (org-end-of-subtree t t)))
6654 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6655 (past-first-child nil)
6656 ;; Make sure to skip inlinetasks.
6657 (re (format regexp-fmt
6658 current-level
6659 (cond
6660 ((not (featurep 'org-inlinetask)) "")
6661 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6663 (t (1- org-inlinetask-min-level))))))
6664 ;; Display parent heading.
6665 (org-flag-heading nil)
6666 (forward-line)
6667 ;; Display children. First child may be deeper than expected
6668 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6669 ;; MAX-LEVEL accordingly.
6670 (while (re-search-forward re end t)
6671 (unless past-first-child
6672 (setq re (format regexp-fmt
6673 current-level
6674 (max (funcall outline-level) max-level)))
6675 (setq past-first-child t))
6676 (org-flag-heading nil)))))
6678 (defun org-show-subtree ()
6679 "Show everything after this heading at deeper levels."
6680 (interactive)
6681 (org-flag-region
6682 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6684 ;;;; Blocks visibility
6686 (defun org-hide-block-toggle-maybe ()
6687 "Toggle visibility of block at point.
6688 Unlike to `org-hide-block-toggle', this function does not throw
6689 an error. Return a non-nil value when toggling is successful."
6690 (interactive)
6691 (ignore-errors (org-hide-block-toggle)))
6693 (defun org-hide-block-toggle (&optional force)
6694 "Toggle the visibility of the current block.
6695 When optional argument FORCE is `off', make block visible. If it
6696 is non-nil, hide it unconditionally. Throw an error when not at
6697 a block. Return a non-nil value when toggling is successful."
6698 (interactive)
6699 (let ((element (org-element-at-point)))
6700 (unless (memq (org-element-type element)
6701 '(center-block comment-block dynamic-block example-block
6702 export-block quote-block special-block
6703 src-block verse-block))
6704 (user-error "Not at a block"))
6705 (let* ((post (org-element-property :post-affiliated element))
6706 (start (save-excursion
6707 (goto-char post)
6708 (line-end-position)))
6709 (end (save-excursion
6710 (goto-char (org-element-property :end element))
6711 (skip-chars-backward " \t\n")
6712 (line-end-position))))
6713 ;; Do nothing when not before or at the block opening line or at
6714 ;; the block closing line.
6715 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6716 (cond ((eq force 'off)
6717 (org-flag-region start end nil 'org-hide-block))
6718 (force
6719 (org-flag-region start end t 'org-hide-block))
6720 ((eq (get-char-property start 'invisible) 'org-hide-block)
6721 (org-flag-region start end nil 'org-hide-block))
6723 (org-flag-region start end t 'org-hide-block)))
6724 ;; When the block is hidden away, make sure point is left in
6725 ;; a visible part of the buffer.
6726 (when (invisible-p (max (1- (point)) (point-min)))
6727 (goto-char post))
6728 ;; Signal success.
6729 t))))
6731 (defun org-hide-block-toggle-all ()
6732 "Toggle the visibility of all blocks in the current buffer."
6733 (org-block-map 'org-hide-block-toggle))
6735 (defun org-hide-block-all ()
6736 "Fold all blocks in the current buffer."
6737 (interactive)
6738 (org-show-all '(blocks))
6739 (org-block-map 'org-hide-block-toggle-maybe))
6741 ;;;; Drawers visibility
6743 (defun org-cycle-hide-drawers (state &optional exceptions)
6744 "Re-hide all drawers after a visibility state change.
6745 STATE should be one of the symbols listed in the docstring of
6746 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6747 a list of strings specifying which drawers should not be hidden."
6748 (when (and (derived-mode-p 'org-mode)
6749 (not (memq state '(overview folded contents))))
6750 (save-excursion
6751 (let* ((globalp (eq state 'all))
6752 (beg (if globalp (point-min) (point)))
6753 (end (if globalp (point-max)
6754 (if (eq state 'children)
6755 (save-excursion (outline-next-heading) (point))
6756 (org-end-of-subtree t)))))
6757 (goto-char beg)
6758 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6759 (unless (member-ignore-case (match-string 1) exceptions)
6760 (let ((drawer (org-element-at-point)))
6761 (when (memq (org-element-type drawer) '(drawer property-drawer))
6762 (org-flag-drawer t drawer)
6763 ;; Make sure to skip drawer entirely or we might flag
6764 ;; it another time when matching its ending line with
6765 ;; `org-drawer-regexp'.
6766 (goto-char (org-element-property :end drawer))))))))))
6768 (defun org-flag-drawer (flag &optional element)
6769 "When FLAG is non-nil, hide the drawer we are at.
6770 Otherwise make it visible. When optional argument ELEMENT is
6771 a parsed drawer, as returned by `org-element-at-point', hide or
6772 show that drawer instead."
6773 (let ((drawer (or element
6774 (and (save-excursion
6775 (beginning-of-line)
6776 (looking-at-p org-drawer-regexp))
6777 (org-element-at-point)))))
6778 (when (memq (org-element-type drawer) '(drawer property-drawer))
6779 (let ((post (org-element-property :post-affiliated drawer)))
6780 (org-flag-region
6781 (save-excursion (goto-char post) (line-end-position))
6782 (save-excursion (goto-char (org-element-property :end drawer))
6783 (skip-chars-backward " \t\n")
6784 (line-end-position))
6785 flag 'org-hide-drawer)
6786 ;; When the drawer is hidden away, make sure point lies in
6787 ;; a visible part of the buffer.
6788 (when (invisible-p (max (1- (point)) (point-min)))
6789 (goto-char post))))))
6791 ;;;; Visibility cycling
6793 (defvar-local org-cycle-global-status nil)
6794 (put 'org-cycle-global-status 'org-state t)
6795 (defvar-local org-cycle-subtree-status nil)
6796 (put 'org-cycle-subtree-status 'org-state t)
6798 (defun org-show-all (&optional types)
6799 "Show all contents in the visible part of the buffer.
6800 By default, the function expands headings, blocks and drawers.
6801 When optional argument TYPE is a list of symbols among `blocks',
6802 `drawers' and `headings', to only expand one specific type."
6803 (dolist (type (or types '(blocks drawers headings)))
6804 (org-flag-region (point-min) (point-max) nil
6805 (pcase type
6806 (`blocks 'org-hide-block)
6807 (`drawers 'org-hide-drawer)
6808 (`headings 'outline)
6809 (_ (error "Invalid type: %S" type))))))
6811 ;;;###autoload
6812 (defun org-cycle (&optional arg)
6813 "TAB-action and visibility cycling for Org mode.
6815 This is the command invoked in Org mode by the `TAB' key. Its main
6816 purpose is outline visibility cycling, but it also invokes other actions
6817 in special contexts.
6819 When this function is called with a `\\[universal-argument]' prefix, rotate \
6820 the entire
6821 buffer through 3 states (global cycling)
6822 1. OVERVIEW: Show only top-level headlines.
6823 2. CONTENTS: Show all headlines of all levels, but no body text.
6824 3. SHOW ALL: Show everything.
6826 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6827 switch to the startup visibility,
6828 determined by the variable `org-startup-folded', and by any VISIBILITY
6829 properties in the buffer.
6831 With a `\\[universal-argument] \\[universal-argument] \
6832 \\[universal-argument]' prefix argument, show the entire buffer, including
6833 any drawers.
6835 When inside a table, re-align the table and move to the next field.
6837 When point is at the beginning of a headline, rotate the subtree started
6838 by this line through 3 different states (local cycling)
6839 1. FOLDED: Only the main headline is shown.
6840 2. CHILDREN: The main headline and the direct children are shown.
6841 From this state, you can move to one of the children
6842 and zoom in further.
6843 3. SUBTREE: Show the entire subtree, including body text.
6844 If there is no subtree, switch directly from CHILDREN to FOLDED.
6846 When point is at the beginning of an empty headline and the variable
6847 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6848 of the headline by demoting and promoting it to likely levels. This
6849 speeds up creation document structure by pressing `TAB' once or several
6850 times right after creating a new headline.
6852 When there is a numeric prefix, go up to a heading with level ARG, do
6853 a `show-subtree' and return to the previous cursor position. If ARG
6854 is negative, go up that many levels.
6856 When point is not at the beginning of a headline, execute the global
6857 binding for `TAB', which is re-indenting the line. See the option
6858 `org-cycle-emulate-tab' for details.
6860 As a special case, if point is at the beginning of the buffer and there is
6861 no headline in line 1, this function will act as if called with prefix arg
6862 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6863 prefix arg, but only
6864 if the variable `org-cycle-global-at-bob' is t."
6865 (interactive "P")
6866 (org-load-modules-maybe)
6867 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6868 (and org-cycle-level-after-item/entry-creation
6869 (or (org-cycle-level)
6870 (org-cycle-item-indentation))))
6871 (let* ((limit-level
6872 (or org-cycle-max-level
6873 (and (boundp 'org-inlinetask-min-level)
6874 org-inlinetask-min-level
6875 (1- org-inlinetask-min-level))))
6876 (nstars (and limit-level
6877 (if org-odd-levels-only
6878 (and limit-level (1- (* limit-level 2)))
6879 limit-level)))
6880 (org-outline-regexp
6881 (if (not (derived-mode-p 'org-mode))
6882 outline-regexp
6883 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6884 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6885 (not (looking-at org-outline-regexp))))
6886 (org-cycle-hook
6887 (if bob-special
6888 (delq 'org-optimize-window-after-visibility-change
6889 (copy-sequence org-cycle-hook))
6890 org-cycle-hook))
6891 (pos (point)))
6893 (cond
6895 ((equal arg '(16))
6896 (setq last-command 'dummy)
6897 (org-set-startup-visibility)
6898 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6900 ((equal arg '(64))
6901 (org-show-all)
6902 (org-unlogged-message "Entire buffer visible, including drawers"))
6904 ((equal arg '(4)) (org-cycle-internal-global))
6906 ;; Try hiding block at point.
6907 ((org-hide-block-toggle-maybe))
6909 ;; Try cdlatex TAB completion
6910 ((org-try-cdlatex-tab))
6912 ;; Table: enter it or move to the next field.
6913 ((org-at-table-p 'any)
6914 (if (org-at-table.el-p)
6915 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6916 Use `\\[org-edit-special]' to edit table.el tables"))
6917 (if arg (org-table-edit-field t)
6918 (org-table-justify-field-maybe)
6919 (call-interactively 'org-table-next-field))))
6921 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6923 ;; Global cycling: delegate to `org-cycle-internal-global'.
6924 (bob-special (org-cycle-internal-global))
6926 ;; Drawers: delegate to `org-flag-drawer'.
6927 ((save-excursion
6928 (beginning-of-line 1)
6929 (looking-at org-drawer-regexp))
6930 (org-flag-drawer ; toggle block visibility
6931 (not (get-char-property (match-end 0) 'invisible))))
6933 ;; Show-subtree, ARG levels up from here.
6934 ((integerp arg)
6935 (save-excursion
6936 (org-back-to-heading)
6937 (outline-up-heading (if (< arg 0) (- arg)
6938 (- (funcall outline-level) arg)))
6939 (org-show-subtree)))
6941 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6942 ((and (featurep 'org-inlinetask)
6943 (org-inlinetask-at-task-p)
6944 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6945 (org-inlinetask-toggle-visibility))
6947 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6948 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6949 (save-excursion (move-beginning-of-line 1)
6950 (looking-at org-outline-regexp)))
6951 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6952 (org-cycle-internal-local))
6954 ;; From there: TAB emulation and template completion.
6955 (buffer-read-only (org-back-to-heading))
6957 ((run-hook-with-args-until-success
6958 'org-tab-after-check-for-cycling-hook))
6960 ((run-hook-with-args-until-success
6961 'org-tab-before-tab-emulation-hook))
6963 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6964 (or (not (bolp))
6965 (not (looking-at org-outline-regexp))))
6966 (call-interactively (global-key-binding "\t")))
6968 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6969 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6970 (or (and (eq org-cycle-emulate-tab 'white)
6971 (= (match-end 0) (point-at-eol)))
6972 (and (eq org-cycle-emulate-tab 'whitestart)
6973 (>= (match-end 0) pos))))
6975 (eq org-cycle-emulate-tab t))
6976 (call-interactively (global-key-binding "\t")))
6978 (t (save-excursion
6979 (org-back-to-heading)
6980 (org-cycle)))))))
6982 (defun org-cycle-internal-global ()
6983 "Do the global cycling action."
6984 ;; Hack to avoid display of messages for .org attachments in Gnus
6985 (let ((ga (string-match "\\*fontification" (buffer-name))))
6986 (cond
6987 ((and (eq last-command this-command)
6988 (eq org-cycle-global-status 'overview))
6989 ;; We just created the overview - now do table of contents
6990 ;; This can be slow in very large buffers, so indicate action
6991 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6992 (unless ga (org-unlogged-message "CONTENTS..."))
6993 (org-content)
6994 (unless ga (org-unlogged-message "CONTENTS...done"))
6995 (setq org-cycle-global-status 'contents)
6996 (run-hook-with-args 'org-cycle-hook 'contents))
6998 ((and (eq last-command this-command)
6999 (eq org-cycle-global-status 'contents))
7000 ;; We just showed the table of contents - now show everything
7001 (run-hook-with-args 'org-pre-cycle-hook 'all)
7002 (org-show-all '(headings blocks))
7003 (unless ga (org-unlogged-message "SHOW ALL"))
7004 (setq org-cycle-global-status 'all)
7005 (run-hook-with-args 'org-cycle-hook 'all))
7008 ;; Default action: go to overview
7009 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7010 (org-overview)
7011 (unless ga (org-unlogged-message "OVERVIEW"))
7012 (setq org-cycle-global-status 'overview)
7013 (run-hook-with-args 'org-cycle-hook 'overview)))))
7015 (defvar org-called-with-limited-levels nil
7016 "Non-nil when `org-with-limited-levels' is currently active.")
7018 (defun org-cycle-internal-local ()
7019 "Do the local cycling action."
7020 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7021 ;; First, determine end of headline (EOH), end of subtree or item
7022 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7023 (save-excursion
7024 (if (org-at-item-p)
7025 (progn
7026 (beginning-of-line)
7027 (setq struct (org-list-struct))
7028 (setq eoh (point-at-eol))
7029 (setq eos (org-list-get-item-end-before-blank (point) struct))
7030 (setq has-children (org-list-has-child-p (point) struct)))
7031 (org-back-to-heading)
7032 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7033 (setq eos (save-excursion (org-end-of-subtree t t)
7034 (when (bolp) (backward-char)) (point)))
7035 (setq has-children
7036 (or (save-excursion
7037 (let ((level (funcall outline-level)))
7038 (outline-next-heading)
7039 (and (org-at-heading-p t)
7040 (> (funcall outline-level) level))))
7041 (save-excursion
7042 (org-list-search-forward (org-item-beginning-re) eos t)))))
7043 ;; Determine end invisible part of buffer (EOL)
7044 (beginning-of-line 2)
7045 (while (and (not (eobp)) ;This is like `next-line'.
7046 (get-char-property (1- (point)) 'invisible))
7047 (goto-char (next-single-char-property-change (point) 'invisible))
7048 (and (eolp) (beginning-of-line 2)))
7049 (setq eol (point)))
7050 ;; Find out what to do next and set `this-command'
7051 (cond
7052 ((= eos eoh)
7053 ;; Nothing is hidden behind this heading
7054 (unless (org-before-first-heading-p)
7055 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7056 (org-unlogged-message "EMPTY ENTRY")
7057 (setq org-cycle-subtree-status nil)
7058 (save-excursion
7059 (goto-char eos)
7060 (outline-next-heading)
7061 (when (org-invisible-p) (org-flag-heading nil))))
7062 ((and (or (>= eol eos)
7063 (not (string-match "\\S-" (buffer-substring eol eos))))
7064 (or has-children
7065 (not (setq children-skipped
7066 org-cycle-skip-children-state-if-no-children))))
7067 ;; Entire subtree is hidden in one line: children view
7068 (unless (org-before-first-heading-p)
7069 (run-hook-with-args 'org-pre-cycle-hook 'children))
7070 (if (org-at-item-p)
7071 (org-list-set-item-visibility (point-at-bol) struct 'children)
7072 (org-show-entry)
7073 (org-with-limited-levels (org-show-children))
7074 (org-show-set-visibility 'canonical)
7075 ;; Fold every list in subtree to top-level items.
7076 (when (eq org-cycle-include-plain-lists 'integrate)
7077 (save-excursion
7078 (org-back-to-heading)
7079 (while (org-list-search-forward (org-item-beginning-re) eos t)
7080 (beginning-of-line 1)
7081 (let* ((struct (org-list-struct))
7082 (prevs (org-list-prevs-alist struct))
7083 (end (org-list-get-bottom-point struct)))
7084 (dolist (e (org-list-get-all-items (point) struct prevs))
7085 (org-list-set-item-visibility e struct 'folded))
7086 (goto-char (if (< end eos) end eos)))))))
7087 (org-unlogged-message "CHILDREN")
7088 (save-excursion
7089 (goto-char eos)
7090 (outline-next-heading)
7091 (when (org-invisible-p) (org-flag-heading nil)))
7092 (setq org-cycle-subtree-status 'children)
7093 (unless (org-before-first-heading-p)
7094 (run-hook-with-args 'org-cycle-hook 'children)))
7095 ((or children-skipped
7096 (and (eq last-command this-command)
7097 (eq org-cycle-subtree-status 'children)))
7098 ;; We just showed the children, or no children are there,
7099 ;; now show everything.
7100 (unless (org-before-first-heading-p)
7101 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7102 (org-flag-region eoh eos nil 'outline)
7103 (org-unlogged-message
7104 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7105 (setq org-cycle-subtree-status 'subtree)
7106 (unless (org-before-first-heading-p)
7107 (run-hook-with-args 'org-cycle-hook 'subtree)))
7109 ;; Default action: hide the subtree.
7110 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7111 (org-flag-region eoh eos t 'outline)
7112 (org-unlogged-message "FOLDED")
7113 (setq org-cycle-subtree-status 'folded)
7114 (unless (org-before-first-heading-p)
7115 (run-hook-with-args 'org-cycle-hook 'folded))))))
7117 ;;;###autoload
7118 (defun org-global-cycle (&optional arg)
7119 "Cycle the global visibility. For details see `org-cycle'.
7120 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7121 With a numeric prefix, show all headlines up to that level."
7122 (interactive "P")
7123 (let ((org-cycle-include-plain-lists
7124 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7125 (cond
7126 ((integerp arg)
7127 (org-show-all '(headings blocks))
7128 (outline-hide-sublevels arg)
7129 (setq org-cycle-global-status 'contents))
7130 ((equal arg '(4))
7131 (org-set-startup-visibility)
7132 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7134 (org-cycle '(4))))))
7136 (defun org-set-startup-visibility ()
7137 "Set the visibility required by startup options and properties."
7138 (cond
7139 ((eq org-startup-folded t)
7140 (org-overview))
7141 ((eq org-startup-folded 'content)
7142 (org-content))
7143 ((or (eq org-startup-folded 'showeverything)
7144 (eq org-startup-folded nil))
7145 (org-show-all)))
7146 (unless (eq org-startup-folded 'showeverything)
7147 (when org-hide-block-startup (org-hide-block-all))
7148 (org-set-visibility-according-to-property)
7149 (org-cycle-hide-archived-subtrees 'all)
7150 (org-cycle-hide-drawers 'all)
7151 (org-cycle-show-empty-lines t)))
7153 (defun org-set-visibility-according-to-property ()
7154 "Switch subtree visibilities according to :VISIBILITY: property."
7155 (interactive)
7156 (org-with-wide-buffer
7157 (goto-char (point-min))
7158 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7159 (if (not (org-at-property-p)) (outline-next-heading)
7160 (let ((state (match-string 3)))
7161 (save-excursion
7162 (org-back-to-heading t)
7163 (outline-hide-subtree)
7164 (org-reveal)
7165 (cond
7166 ((equal state "folded")
7167 (outline-hide-subtree))
7168 ((equal state "children")
7169 (org-show-hidden-entry)
7170 (org-show-children))
7171 ((equal state "content")
7172 (save-excursion
7173 (save-restriction
7174 (org-narrow-to-subtree)
7175 (org-content))))
7176 ((member state '("all" "showall"))
7177 (outline-show-subtree)))))))))
7179 (defun org-overview ()
7180 "Switch to overview mode, showing only top-level headlines.
7181 This shows all headlines with a level equal or greater than the level
7182 of the first headline in the buffer. This is important, because if the
7183 first headline is not level one, then (hide-sublevels 1) gives confusing
7184 results."
7185 (interactive)
7186 (save-excursion
7187 (let ((level
7188 (save-excursion
7189 (goto-char (point-min))
7190 (when (re-search-forward org-outline-regexp-bol nil t)
7191 (goto-char (match-beginning 0))
7192 (funcall outline-level)))))
7193 (and level (outline-hide-sublevels level)))))
7195 (defun org-content (&optional arg)
7196 "Show all headlines in the buffer, like a table of contents.
7197 With numerical argument N, show content up to level N."
7198 (interactive "P")
7199 (org-overview)
7200 (save-excursion
7201 ;; Visit all headings and show their offspring
7202 (and (integerp arg) (org-overview))
7203 (goto-char (point-max))
7204 (catch 'exit
7205 (while (and (progn (condition-case nil
7206 (outline-previous-visible-heading 1)
7207 (error (goto-char (point-min))))
7209 (looking-at org-outline-regexp))
7210 (if (integerp arg)
7211 (org-show-children (1- arg))
7212 (outline-show-branches))
7213 (when (bobp) (throw 'exit nil))))))
7215 (defun org-optimize-window-after-visibility-change (state)
7216 "Adjust the window after a change in outline visibility.
7217 This function is the default value of the hook `org-cycle-hook'."
7218 (when (get-buffer-window (current-buffer))
7219 (cond
7220 ((eq state 'content) nil)
7221 ((eq state 'all) nil)
7222 ((eq state 'folded) nil)
7223 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7224 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7226 (defun org-clean-visibility-after-subtree-move ()
7227 "Fix visibility issues after moving a subtree."
7228 ;; First, find a reasonable region to look at:
7229 ;; Start two siblings above, end three below
7230 (let* ((beg (save-excursion
7231 (and (org-get-last-sibling)
7232 (org-get-last-sibling))
7233 (point)))
7234 (end (save-excursion
7235 (and (org-get-next-sibling)
7236 (org-get-next-sibling)
7237 (org-get-next-sibling))
7238 (if (org-at-heading-p)
7239 (point-at-eol)
7240 (point))))
7241 (level (looking-at "\\*+"))
7242 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7243 (save-excursion
7244 (save-restriction
7245 (narrow-to-region beg end)
7246 (when re
7247 ;; Properly fold already folded siblings
7248 (goto-char (point-min))
7249 (while (re-search-forward re nil t)
7250 (when (and (not (org-invisible-p))
7251 (org-invisible-p (line-end-position)))
7252 (outline-hide-entry))))
7253 (org-cycle-hide-drawers 'all)
7254 (org-cycle-show-empty-lines 'overview)))))
7256 (defun org-cycle-show-empty-lines (state)
7257 "Show empty lines above all visible headlines.
7258 The region to be covered depends on STATE when called through
7259 `org-cycle-hook'. Lisp program can use t for STATE to get the
7260 entire buffer covered. Note that an empty line is only shown if there
7261 are at least `org-cycle-separator-lines' empty lines before the headline."
7262 (when (/= org-cycle-separator-lines 0)
7263 (save-excursion
7264 (let* ((n (abs org-cycle-separator-lines))
7265 (re (cond
7266 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7267 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7268 (t (let ((ns (number-to-string (- n 2))))
7269 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7270 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7271 beg end)
7272 (cond
7273 ((memq state '(overview contents t))
7274 (setq beg (point-min) end (point-max)))
7275 ((memq state '(children folded))
7276 (setq beg (point)
7277 end (progn (org-end-of-subtree t t)
7278 (line-beginning-position 2)))))
7279 (when beg
7280 (goto-char beg)
7281 (while (re-search-forward re end t)
7282 (unless (get-char-property (match-end 1) 'invisible)
7283 (let ((e (match-end 1))
7284 (b (if (>= org-cycle-separator-lines 0)
7285 (match-beginning 1)
7286 (save-excursion
7287 (goto-char (match-beginning 0))
7288 (skip-chars-backward " \t\n")
7289 (line-end-position)))))
7290 (org-flag-region b e nil 'outline))))))))
7291 ;; Never hide empty lines at the end of the file.
7292 (save-excursion
7293 (goto-char (point-max))
7294 (outline-previous-heading)
7295 (outline-end-of-heading)
7296 (when (and (looking-at "[ \t\n]+")
7297 (= (match-end 0) (point-max)))
7298 (org-flag-region (point) (match-end 0) nil 'outline))))
7300 ;;;; Reveal point location
7302 (defun org-show-context (&optional key)
7303 "Make sure point and context are visible.
7304 Optional argument KEY, when non-nil, is a symbol. See
7305 `org-show-context-detail' for allowed values and how much is to
7306 be shown."
7307 (org-show-set-visibility
7308 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7309 ((cdr (assq key org-show-context-detail)))
7310 (t (cdr (assq 'default org-show-context-detail))))))
7312 (defun org-show-set-visibility (detail)
7313 "Set visibility around point according to DETAIL.
7314 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7315 `tree', `canonical' or t. See `org-show-context-detail' for more
7316 information."
7317 ;; Show current heading and possibly its entry, following headline
7318 ;; or all children.
7319 (if (and (org-at-heading-p) (not (eq detail 'local)))
7320 (org-flag-heading nil)
7321 (org-show-entry)
7322 ;; If point is hidden within a drawer or a block, make sure to
7323 ;; expose it.
7324 (dolist (o (overlays-at (point)))
7325 (when (memq (overlay-get o 'invisible)
7326 '(org-hide-block org-hide-drawer outline))
7327 (delete-overlay o)))
7328 (unless (org-before-first-heading-p)
7329 (org-with-limited-levels
7330 (cl-case detail
7331 ((tree canonical t) (org-show-children))
7332 ((nil minimal ancestors))
7333 (t (save-excursion
7334 (outline-next-heading)
7335 (org-flag-heading nil)))))))
7336 ;; Show all siblings.
7337 (when (eq detail 'lineage) (org-show-siblings))
7338 ;; Show ancestors, possibly with their children.
7339 (when (memq detail '(ancestors lineage tree canonical t))
7340 (save-excursion
7341 (while (org-up-heading-safe)
7342 (org-flag-heading nil)
7343 (when (memq detail '(canonical t)) (org-show-entry))
7344 (when (memq detail '(tree canonical t)) (org-show-children))))))
7346 (defvar org-reveal-start-hook nil
7347 "Hook run before revealing a location.")
7349 (defun org-reveal (&optional siblings)
7350 "Show current entry, hierarchy above it, and the following headline.
7352 This can be used to show a consistent set of context around
7353 locations exposed with `org-show-context'.
7355 With optional argument SIBLINGS, on each level of the hierarchy all
7356 siblings are shown. This repairs the tree structure to what it would
7357 look like when opened with hierarchical calls to `org-cycle'.
7359 With a \\[universal-argument] \\[universal-argument] prefix, \
7360 go to the parent and show the entire tree."
7361 (interactive "P")
7362 (run-hooks 'org-reveal-start-hook)
7363 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7364 ((equal siblings '(16))
7365 (save-excursion
7366 (when (org-up-heading-safe)
7367 (org-show-subtree)
7368 (run-hook-with-args 'org-cycle-hook 'subtree))))
7369 (t (org-show-set-visibility 'lineage))))
7372 ;;; Indirect buffer display of subtrees
7374 (defvar org-indirect-dedicated-frame nil
7375 "This is the frame being used for indirect tree display.")
7376 (defvar org-last-indirect-buffer nil)
7378 (defun org-tree-to-indirect-buffer (&optional arg)
7379 "Create indirect buffer and narrow it to current subtree.
7381 With a numerical prefix ARG, go up to this level and then take that tree.
7382 If ARG is negative, go up that many levels.
7384 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7385 indirect buffer previously made with this command, to avoid proliferation of
7386 indirect buffers. However, when you call the command with a \
7387 `\\[universal-argument]' prefix, or
7388 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7389 so that you can work with several indirect buffers at the same time. If
7390 `org-indirect-buffer-display' is `dedicated-frame', the \
7391 `\\[universal-argument]' prefix also
7392 requests that a new frame be made for the new buffer, so that the dedicated
7393 frame is not changed."
7394 (interactive "P")
7395 (let ((cbuf (current-buffer))
7396 (cwin (selected-window))
7397 (pos (point))
7398 beg end level heading ibuf)
7399 (save-excursion
7400 (org-back-to-heading t)
7401 (when (numberp arg)
7402 (setq level (org-outline-level))
7403 (when (< arg 0) (setq arg (+ level arg)))
7404 (while (> (setq level (org-outline-level)) arg)
7405 (org-up-heading-safe)))
7406 (setq beg (point)
7407 heading (org-get-heading 'no-tags))
7408 (org-end-of-subtree t t)
7409 (when (org-at-heading-p) (backward-char 1))
7410 (setq end (point)))
7411 (when (and (buffer-live-p org-last-indirect-buffer)
7412 (not (eq org-indirect-buffer-display 'new-frame))
7413 (not arg))
7414 (kill-buffer org-last-indirect-buffer))
7415 (setq ibuf (org-get-indirect-buffer cbuf heading)
7416 org-last-indirect-buffer ibuf)
7417 (cond
7418 ((or (eq org-indirect-buffer-display 'new-frame)
7419 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7420 (select-frame (make-frame))
7421 (delete-other-windows)
7422 (pop-to-buffer-same-window ibuf)
7423 (org-set-frame-title heading))
7424 ((eq org-indirect-buffer-display 'dedicated-frame)
7425 (raise-frame
7426 (select-frame (or (and org-indirect-dedicated-frame
7427 (frame-live-p org-indirect-dedicated-frame)
7428 org-indirect-dedicated-frame)
7429 (setq org-indirect-dedicated-frame (make-frame)))))
7430 (delete-other-windows)
7431 (pop-to-buffer-same-window ibuf)
7432 (org-set-frame-title (concat "Indirect: " heading)))
7433 ((eq org-indirect-buffer-display 'current-window)
7434 (pop-to-buffer-same-window ibuf))
7435 ((eq org-indirect-buffer-display 'other-window)
7436 (pop-to-buffer ibuf))
7437 (t (error "Invalid value")))
7438 (narrow-to-region beg end)
7439 (org-show-all '(headings blocks))
7440 (goto-char pos)
7441 (run-hook-with-args 'org-cycle-hook 'all)
7442 (and (window-live-p cwin) (select-window cwin))))
7444 (defun org-get-indirect-buffer (&optional buffer heading)
7445 (setq buffer (or buffer (current-buffer)))
7446 (let ((n 1) (base (buffer-name buffer)) bname)
7447 (while (buffer-live-p
7448 (get-buffer
7449 (setq bname
7450 (concat base "-"
7451 (if heading (concat heading "-" (number-to-string n))
7452 (number-to-string n))))))
7453 (setq n (1+ n)))
7454 (condition-case nil
7455 (make-indirect-buffer buffer bname 'clone)
7456 (error (make-indirect-buffer buffer bname)))))
7458 (defun org-set-frame-title (title)
7459 "Set the title of the current frame to the string TITLE."
7460 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7462 ;;;; Structure editing
7464 ;;; Inserting headlines
7466 (defun org--line-empty-p (n)
7467 "Is the Nth next line empty?
7469 Counts the current line as N = 1 and the previous line as N = 0;
7470 see `beginning-of-line'."
7471 (save-excursion
7472 (and (not (bobp))
7473 (or (beginning-of-line n) t)
7474 (save-match-data
7475 (looking-at "[ \t]*$")))))
7477 (defun org-previous-line-empty-p ()
7478 "Is the previous line a blank line?
7479 When NEXT is non-nil, check the next line instead."
7480 (org--line-empty-p 0))
7482 (defun org-next-line-empty-p ()
7483 "Is the previous line a blank line?
7484 When NEXT is non-nil, check the next line instead."
7485 (org--line-empty-p 2))
7487 (defun org--blank-before-heading-p (&optional parent)
7488 "Non-nil when an empty line should precede a new heading here.
7489 When optional argument PARENT is non-nil, consider parent
7490 headline instead of current one."
7491 (pcase (assq 'heading org-blank-before-new-entry)
7492 (`(heading . auto)
7493 (save-excursion
7494 (org-with-limited-levels
7495 (unless (and (org-before-first-heading-p)
7496 (not (outline-next-heading)))
7497 (org-back-to-heading t)
7498 (when parent (org-up-heading-safe))
7499 (cond ((not (bobp))
7500 (org-previous-line-empty-p))
7501 ((outline-next-heading)
7502 (org-previous-line-empty-p))
7503 ;; Ignore trailing spaces on last buffer line.
7504 ((progn (skip-chars-backward " \t") (bolp))
7505 (org-previous-line-empty-p))
7506 (t nil))))))
7507 (`(heading . ,value) value)
7508 (_ nil)))
7510 (defun org-insert-heading (&optional arg invisible-ok top)
7511 "Insert a new heading or an item with the same depth at point.
7513 If point is at the beginning of a heading, insert a new heading
7514 or a new headline above the current one. When at the beginning
7515 of a regular line of text, turn it into a heading.
7517 If point is in the middle of a line, split it and create a new
7518 headline with the text in the current line after point (see
7519 `org-M-RET-may-split-line' on how to modify this behavior). As
7520 a special case, on a headline, splitting can only happen on the
7521 title itself. E.g., this excludes breaking stars or tags.
7523 With a `\\[universal-argument]' prefix, set \
7524 `org-insert-heading-respect-content' to
7525 a non-nil value for the duration of the command. This forces the
7526 insertion of a heading after the current subtree, independently
7527 on the location of point.
7529 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7530 insert the heading at the end of the tree
7531 above the current heading. For example, if point is within a
7532 2nd-level heading, then it will insert a 2nd-level heading at
7533 the end of the 1st-level parent subtree.
7535 When INVISIBLE-OK is set, stop at invisible headlines when going
7536 back. This is important for non-interactive uses of the
7537 command.
7539 When optional argument TOP is non-nil, insert a level 1 heading,
7540 unconditionally."
7541 (interactive "P")
7542 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7543 (level (org-current-level))
7544 (stars (make-string (if (and level (not top)) level 1) ?*)))
7545 (cond
7546 ((or org-insert-heading-respect-content
7547 (member arg '((4) (16)))
7548 (and (not invisible-ok)
7549 (invisible-p (max (1- (point)) (point-min)))))
7550 ;; Position point at the location of insertion.
7551 (if (not level) ;before first headline
7552 (org-with-limited-levels (outline-next-heading))
7553 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7554 ;; is nil.
7555 (org-with-limited-levels (org-back-to-heading invisible-ok))
7556 (cond ((equal arg '(16))
7557 (org-up-heading-safe)
7558 (org-end-of-subtree t t))
7560 (org-end-of-subtree t t))))
7561 (unless (bolp) (insert "\n")) ;ensure final newline
7562 (unless (and blank? (org-previous-line-empty-p))
7563 (org-N-empty-lines-before-current (if blank? 1 0)))
7564 (insert stars " \n")
7565 (forward-char -1))
7566 ;; At a headline...
7567 ((org-at-heading-p)
7568 (cond ((bolp)
7569 (when blank? (save-excursion (insert "\n")))
7570 (save-excursion (insert stars " \n"))
7571 (unless (and blank? (org-previous-line-empty-p))
7572 (org-N-empty-lines-before-current (if blank? 1 0)))
7573 (end-of-line))
7574 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7575 (org-match-line org-complex-heading-regexp)
7576 (org-pos-in-match-range (point) 4))
7577 ;; Grab the text that should moved to the new headline.
7578 ;; Preserve tags.
7579 (let ((split (delete-and-extract-region (point) (match-end 4))))
7580 (if (looking-at "[ \t]*$") (replace-match "")
7581 (org-set-tags nil t))
7582 (end-of-line)
7583 (when blank? (insert "\n"))
7584 (insert "\n" stars " ")
7585 (when (org-string-nw-p split) (insert split))
7586 (when (eobp) (save-excursion (insert "\n")))))
7588 (end-of-line)
7589 (when blank? (insert "\n"))
7590 (insert "\n" stars " ")
7591 (when (eobp) (save-excursion (insert "\n"))))))
7592 ;; On regular text, turn line into a headline or split, if
7593 ;; appropriate.
7594 ((bolp)
7595 (insert stars " ")
7596 (unless (and blank? (org-previous-line-empty-p))
7597 (org-N-empty-lines-before-current (if blank? 1 0))))
7599 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7600 (end-of-line))
7601 (insert "\n" stars " ")
7602 (unless (and blank? (org-previous-line-empty-p))
7603 (org-N-empty-lines-before-current (if blank? 1 0))))))
7604 (run-hooks 'org-insert-heading-hook))
7606 (defun org-N-empty-lines-before-current (n)
7607 "Make the number of empty lines before current exactly N.
7608 So this will delete or add empty lines."
7609 (let ((column (current-column)))
7610 (beginning-of-line)
7611 (unless (bobp)
7612 (let ((start (save-excursion
7613 (skip-chars-backward " \r\t\n")
7614 (line-end-position))))
7615 (delete-region start (line-end-position 0))))
7616 (insert (make-string n ?\n))
7617 (move-to-column column)))
7619 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7620 "Return the heading of the current entry, without the stars.
7621 When NO-TAGS is non-nil, don't include tags.
7622 When NO-TODO is non-nil, don't include TODO keywords.
7623 When NO-PRIORITY is non-nil, don't include priority cookie.
7624 When NO-COMMENT is non-nil, don't include COMMENT string."
7625 (save-excursion
7626 (org-back-to-heading t)
7627 (let ((case-fold-search nil))
7628 (looking-at org-complex-heading-regexp)
7629 (let ((todo (and (not no-todo) (match-string 2)))
7630 (priority (and (not no-priority) (match-string 3)))
7631 (headline (pcase (match-string 4)
7632 (`nil "")
7633 ((and (guard no-comment) h)
7634 (replace-regexp-in-string
7635 (eval-when-compile
7636 (format "\\`%s[ \t]+" org-comment-string))
7637 "" h))
7638 (h h)))
7639 (tags (and (not no-tags) (match-string 5))))
7640 (mapconcat #'identity
7641 (delq nil (list todo priority headline tags))
7642 " ")))))
7644 (defun org-heading-components ()
7645 "Return the components of the current heading.
7646 This is a list with the following elements:
7647 - the level as an integer
7648 - the reduced level, different if `org-odd-levels-only' is set.
7649 - the TODO keyword, or nil
7650 - the priority character, like ?A, or nil if no priority is given
7651 - the headline text itself, or the tags string if no headline text
7652 - the tags string, or nil."
7653 (save-excursion
7654 (org-back-to-heading t)
7655 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7656 (list (length (match-string 1))
7657 (org-reduced-level (length (match-string 1)))
7658 (match-string-no-properties 2)
7659 (and (match-end 3) (aref (match-string 3) 2))
7660 (match-string-no-properties 4)
7661 (match-string-no-properties 5)))))
7663 (defun org-get-entry ()
7664 "Get the entry text, after heading, entire subtree."
7665 (save-excursion
7666 (org-back-to-heading t)
7667 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7669 (defun org-edit-headline (&optional heading)
7670 "Edit the current headline.
7671 Set it to HEADING when provided."
7672 (interactive)
7673 (org-with-wide-buffer
7674 (org-back-to-heading t)
7675 (let ((case-fold-search nil))
7676 (when (looking-at org-complex-heading-regexp)
7677 (let* ((old (match-string-no-properties 4))
7678 (new (save-match-data
7679 (org-trim (or heading (read-string "Edit: " old))))))
7680 (unless (equal old new)
7681 (if old (replace-match new t t nil 4)
7682 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7683 (insert " " new))
7684 (org-set-tags nil t)
7685 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7687 (defun org-insert-heading-after-current ()
7688 "Insert a new heading with same level as current, after current subtree."
7689 (interactive)
7690 (org-back-to-heading)
7691 (org-insert-heading)
7692 (org-move-subtree-down)
7693 (end-of-line 1))
7695 (defun org-insert-heading-respect-content (&optional invisible-ok)
7696 "Insert heading with `org-insert-heading-respect-content' set to t."
7697 (interactive)
7698 (org-insert-heading '(4) invisible-ok))
7700 (defun org-insert-todo-heading-respect-content (&optional force-state)
7701 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7702 (interactive)
7703 (org-insert-todo-heading force-state '(4)))
7705 (defun org-insert-todo-heading (arg &optional force-heading)
7706 "Insert a new heading with the same level and TODO state as current heading.
7708 If the heading has no TODO state, or if the state is DONE, use
7709 the first state (TODO by default). Also with one prefix arg,
7710 force first state. With two prefix args, force inserting at the
7711 end of the parent subtree.
7713 When called at a plain list item, insert a new item with an
7714 unchecked check box."
7715 (interactive "P")
7716 (when (or force-heading (not (org-insert-item 'checkbox)))
7717 (org-insert-heading (or (and (equal arg '(16)) '(16))
7718 force-heading))
7719 (save-excursion
7720 (org-forward-heading-same-level -1)
7721 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7722 (let* ((new-mark-x
7723 (if (or (equal arg '(4))
7724 (not (match-beginning 2))
7725 (member (match-string 2) org-done-keywords))
7726 (car org-todo-keywords-1)
7727 (match-string 2)))
7728 (new-mark
7730 (run-hook-with-args-until-success
7731 'org-todo-get-default-hook new-mark-x nil)
7732 new-mark-x)))
7733 (beginning-of-line 1)
7734 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7735 (if org-treat-insert-todo-heading-as-state-change
7736 (org-todo new-mark)
7737 (insert new-mark " "))))
7738 (when org-provide-todo-statistics
7739 (org-update-parent-todo-statistics))))
7741 (defun org-insert-subheading (arg)
7742 "Insert a new subheading and demote it.
7743 Works for outline headings and for plain lists alike."
7744 (interactive "P")
7745 (org-insert-heading arg)
7746 (cond
7747 ((org-at-heading-p) (org-do-demote))
7748 ((org-at-item-p) (org-indent-item))))
7750 (defun org-insert-todo-subheading (arg)
7751 "Insert a new subheading with TODO keyword or checkbox and demote it.
7752 Works for outline headings and for plain lists alike."
7753 (interactive "P")
7754 (org-insert-todo-heading arg)
7755 (cond
7756 ((org-at-heading-p) (org-do-demote))
7757 ((org-at-item-p) (org-indent-item))))
7759 ;;; Promotion and Demotion
7761 (defvar org-after-demote-entry-hook nil
7762 "Hook run after an entry has been demoted.
7763 The cursor will be at the beginning of the entry.
7764 When a subtree is being demoted, the hook will be called for each node.")
7766 (defvar org-after-promote-entry-hook nil
7767 "Hook run after an entry has been promoted.
7768 The cursor will be at the beginning of the entry.
7769 When a subtree is being promoted, the hook will be called for each node.")
7771 (defun org-promote-subtree ()
7772 "Promote the entire subtree.
7773 See also `org-promote'."
7774 (interactive)
7775 (save-excursion
7776 (org-with-limited-levels (org-map-tree 'org-promote)))
7777 (org-fix-position-after-promote))
7779 (defun org-demote-subtree ()
7780 "Demote the entire subtree.
7781 See `org-demote' and `org-promote'."
7782 (interactive)
7783 (save-excursion
7784 (org-with-limited-levels (org-map-tree 'org-demote)))
7785 (org-fix-position-after-promote))
7787 (defun org-do-promote ()
7788 "Promote the current heading higher up the tree.
7789 If the region is active in `transient-mark-mode', promote all
7790 headings in the region."
7791 (interactive)
7792 (save-excursion
7793 (if (org-region-active-p)
7794 (org-map-region 'org-promote (region-beginning) (region-end))
7795 (org-promote)))
7796 (org-fix-position-after-promote))
7798 (defun org-do-demote ()
7799 "Demote the current heading lower down the tree.
7800 If the region is active in `transient-mark-mode', demote all
7801 headings in the region."
7802 (interactive)
7803 (save-excursion
7804 (if (org-region-active-p)
7805 (org-map-region 'org-demote (region-beginning) (region-end))
7806 (org-demote)))
7807 (org-fix-position-after-promote))
7809 (defun org-fix-position-after-promote ()
7810 "Fix cursor position and indentation after demoting/promoting."
7811 (let ((pos (point)))
7812 (when (save-excursion
7813 (beginning-of-line)
7814 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7815 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7816 (cond ((eobp) (insert " "))
7817 ((eolp) (insert " "))
7818 ((equal (char-after) ?\s) (forward-char 1))))))
7820 (defun org-current-level ()
7821 "Return the level of the current entry, or nil if before the first headline.
7822 The level is the number of stars at the beginning of the
7823 headline. Use `org-reduced-level' to remove the effect of
7824 `org-odd-levels'. Unlike to `org-outline-level', this function
7825 ignores inlinetasks."
7826 (let ((level (org-with-limited-levels (org-outline-level))))
7827 (and (> level 0) level)))
7829 (defun org-get-previous-line-level ()
7830 "Return the outline depth of the last headline before the current line.
7831 Returns 0 for the first headline in the buffer, and nil if before the
7832 first headline."
7833 (and (org-current-level)
7834 (or (and (/= (line-beginning-position) (point-min))
7835 (save-excursion (beginning-of-line 0) (org-current-level)))
7836 0)))
7838 (defun org-reduced-level (l)
7839 "Compute the effective level of a heading.
7840 This takes into account the setting of `org-odd-levels-only'."
7841 (cond
7842 ((zerop l) 0)
7843 (org-odd-levels-only (1+ (floor (/ l 2))))
7844 (t l)))
7846 (defun org-level-increment ()
7847 "Return the number of stars that will be added or removed at a
7848 time to headlines when structure editing, based on the value of
7849 `org-odd-levels-only'."
7850 (if org-odd-levels-only 2 1))
7852 (defun org-get-valid-level (level &optional change)
7853 "Rectify a level change under the influence of `org-odd-levels-only'.
7854 LEVEL is a current level, CHANGE is by how much the level should
7855 be modified. Even if CHANGE is nil, LEVEL may be returned
7856 modified because even level numbers will become the next higher
7857 odd number. Returns values greater than 0."
7858 (if org-odd-levels-only
7859 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7860 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7861 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7862 (max 1 (+ level (or change 0)))))
7864 (defun org-promote ()
7865 "Promote the current heading higher up the tree."
7866 (org-with-wide-buffer
7867 (org-back-to-heading t)
7868 (let* ((after-change-functions (remq 'flyspell-after-change-function
7869 after-change-functions))
7870 (level (save-match-data (funcall outline-level)))
7871 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7872 (diff (abs (- level (length up-head) -1))))
7873 (cond
7874 ((and (= level 1) org-allow-promoting-top-level-subtree)
7875 (replace-match "# " nil t))
7876 ((= level 1)
7877 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7878 (t (replace-match up-head nil t)))
7879 (unless (= level 1)
7880 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7881 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7882 (run-hooks 'org-after-promote-entry-hook))))
7884 (defun org-demote ()
7885 "Demote the current heading lower down the tree."
7886 (org-with-wide-buffer
7887 (org-back-to-heading t)
7888 (let* ((after-change-functions (remq 'flyspell-after-change-function
7889 after-change-functions))
7890 (level (save-match-data (funcall outline-level)))
7891 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7892 (diff (abs (- level (length down-head) -1))))
7893 (replace-match down-head nil t)
7894 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7895 (when org-adapt-indentation (org-fixup-indentation diff))
7896 (run-hooks 'org-after-demote-entry-hook))))
7898 (defun org-cycle-level ()
7899 "Cycle the level of an empty headline through possible states.
7900 This goes first to child, then to parent, level, then up the hierarchy.
7901 After top level, it switches back to sibling level."
7902 (interactive)
7903 (let ((org-adapt-indentation nil))
7904 (when (org-point-at-end-of-empty-headline)
7905 (setq this-command 'org-cycle-level) ; Only needed for caching
7906 (let ((cur-level (org-current-level))
7907 (prev-level (org-get-previous-line-level)))
7908 (cond
7909 ;; If first headline in file, promote to top-level.
7910 ((= prev-level 0)
7911 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7912 do (org-do-promote)))
7913 ;; If same level as prev, demote one.
7914 ((= prev-level cur-level)
7915 (org-do-demote))
7916 ;; If parent is top-level, promote to top level if not already.
7917 ((= prev-level 1)
7918 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7919 do (org-do-promote)))
7920 ;; If top-level, return to prev-level.
7921 ((= cur-level 1)
7922 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7923 do (org-do-demote)))
7924 ;; If less than prev-level, promote one.
7925 ((< cur-level prev-level)
7926 (org-do-promote))
7927 ;; If deeper than prev-level, promote until higher than
7928 ;; prev-level.
7929 ((> cur-level prev-level)
7930 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7931 do (org-do-promote))))
7932 t))))
7934 (defun org-map-tree (fun)
7935 "Call FUN for every heading underneath the current one."
7936 (org-back-to-heading t)
7937 (let ((level (funcall outline-level)))
7938 (save-excursion
7939 (funcall fun)
7940 (while (and (progn
7941 (outline-next-heading)
7942 (> (funcall outline-level) level))
7943 (not (eobp)))
7944 (funcall fun)))))
7946 (defun org-map-region (fun beg end)
7947 "Call FUN for every heading between BEG and END."
7948 (let ((org-ignore-region t))
7949 (save-excursion
7950 (setq end (copy-marker end))
7951 (goto-char beg)
7952 (when (and (re-search-forward org-outline-regexp-bol nil t)
7953 (< (point) end))
7954 (funcall fun))
7955 (while (and (progn
7956 (outline-next-heading)
7957 (< (point) end))
7958 (not (eobp)))
7959 (funcall fun)))))
7961 (defun org-fixup-indentation (diff)
7962 "Change the indentation in the current entry by DIFF.
7964 DIFF is an integer. Indentation is done according to the
7965 following rules:
7967 - Planning information and property drawers are always indented
7968 according to the new level of the headline;
7970 - Footnote definitions and their contents are ignored;
7972 - Inlinetasks' boundaries are not shifted;
7974 - Empty lines are ignored;
7976 - Other lines' indentation are shifted by DIFF columns, unless
7977 it would introduce a structural change in the document, in
7978 which case no shifting is done at all.
7980 Assume point is at a heading or an inlinetask beginning."
7981 (org-with-wide-buffer
7982 (narrow-to-region (line-beginning-position)
7983 (save-excursion
7984 (if (org-with-limited-levels (org-at-heading-p))
7985 (org-with-limited-levels (outline-next-heading))
7986 (org-inlinetask-goto-end))
7987 (point)))
7988 (forward-line)
7989 ;; Indent properly planning info and property drawer.
7990 (when (looking-at-p org-planning-line-re)
7991 (org-indent-line)
7992 (forward-line))
7993 (when (looking-at org-property-drawer-re)
7994 (goto-char (match-end 0))
7995 (forward-line)
7996 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7997 (catch 'no-shift
7998 (when (zerop diff) (throw 'no-shift nil))
7999 ;; If DIFF is negative, first check if a shift is possible at all
8000 ;; (e.g., it doesn't break structure). This can only happen if
8001 ;; some contents are not properly indented.
8002 (let ((case-fold-search t))
8003 (when (< diff 0)
8004 (let ((diff (- diff))
8005 (forbidden-re (concat org-outline-regexp
8006 "\\|"
8007 (substring org-footnote-definition-re 1))))
8008 (save-excursion
8009 (while (not (eobp))
8010 (cond
8011 ((looking-at-p "[ \t]*$") (forward-line))
8012 ((and (looking-at-p org-footnote-definition-re)
8013 (let ((e (org-element-at-point)))
8014 (and (eq (org-element-type e) 'footnote-definition)
8015 (goto-char (org-element-property :end e))))))
8016 ((looking-at-p org-outline-regexp) (forward-line))
8017 ;; Give up if shifting would move before column 0 or
8018 ;; if it would introduce a headline or a footnote
8019 ;; definition.
8021 (skip-chars-forward " \t")
8022 (let ((ind (current-column)))
8023 (when (or (< ind diff)
8024 (and (= ind diff) (looking-at-p forbidden-re)))
8025 (throw 'no-shift nil)))
8026 ;; Ignore contents of example blocks and source
8027 ;; blocks if their indentation is meant to be
8028 ;; preserved. Jump to block's closing line.
8029 (beginning-of-line)
8030 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8031 (let ((e (org-element-at-point)))
8032 (and (memq (org-element-type e)
8033 '(example-block src-block))
8034 (or org-src-preserve-indentation
8035 (org-element-property :preserve-indent e))
8036 (goto-char (org-element-property :end e))
8037 (progn (skip-chars-backward " \r\t\n")
8038 (beginning-of-line)
8039 t))))
8040 (forward-line))))))))
8041 ;; Shift lines but footnote definitions, inlinetasks boundaries
8042 ;; by DIFF. Also skip contents of source or example blocks
8043 ;; when indentation is meant to be preserved.
8044 (while (not (eobp))
8045 (cond
8046 ((and (looking-at-p org-footnote-definition-re)
8047 (let ((e (org-element-at-point)))
8048 (and (eq (org-element-type e) 'footnote-definition)
8049 (goto-char (org-element-property :end e))))))
8050 ((looking-at-p org-outline-regexp) (forward-line))
8051 ((looking-at-p "[ \t]*$") (forward-line))
8053 (indent-line-to (+ (org-get-indentation) diff))
8054 (beginning-of-line)
8055 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8056 (let ((e (org-element-at-point)))
8057 (and (memq (org-element-type e)
8058 '(example-block src-block))
8059 (or org-src-preserve-indentation
8060 (org-element-property :preserve-indent e))
8061 (goto-char (org-element-property :end e))
8062 (progn (skip-chars-backward " \r\t\n")
8063 (beginning-of-line)
8064 t))))
8065 (forward-line)))))))))
8067 (defun org-convert-to-odd-levels ()
8068 "Convert an Org file with all levels allowed to one with odd levels.
8069 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8070 level 5 etc."
8071 (interactive)
8072 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8073 (let ((outline-level 'org-outline-level)
8074 (org-odd-levels-only nil) n)
8075 (save-excursion
8076 (goto-char (point-min))
8077 (while (re-search-forward "^\\*\\*+ " nil t)
8078 (setq n (- (length (match-string 0)) 2))
8079 (while (>= (setq n (1- n)) 0)
8080 (org-demote))
8081 (end-of-line 1))))))
8083 (defun org-convert-to-oddeven-levels ()
8084 "Convert an Org file with only odd levels to one with odd/even levels.
8085 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8086 file contains a section with an even level, conversion would
8087 destroy the structure of the file. An error is signaled in this
8088 case."
8089 (interactive)
8090 (goto-char (point-min))
8091 ;; First check if there are no even levels
8092 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8093 (org-show-set-visibility 'canonical)
8094 (error "Not all levels are odd in this file. Conversion not possible"))
8095 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8096 (let ((outline-regexp org-outline-regexp)
8097 (outline-level 'org-outline-level)
8098 (org-odd-levels-only nil) n)
8099 (save-excursion
8100 (goto-char (point-min))
8101 (while (re-search-forward "^\\*\\*+ " nil t)
8102 (setq n (/ (1- (length (match-string 0))) 2))
8103 (while (>= (setq n (1- n)) 0)
8104 (org-promote))
8105 (end-of-line 1))))))
8107 (defun org-tr-level (n)
8108 "Make N odd if required."
8109 (if org-odd-levels-only (1+ (/ n 2)) n))
8111 ;;; Vertical tree motion, cutting and pasting of subtrees
8113 (defun org-move-subtree-up (&optional arg)
8114 "Move the current subtree up past ARG headlines of the same level."
8115 (interactive "p")
8116 (org-move-subtree-down (- (prefix-numeric-value arg))))
8118 (defun org-move-subtree-down (&optional arg)
8119 "Move the current subtree down past ARG headlines of the same level."
8120 (interactive "p")
8121 (setq arg (prefix-numeric-value arg))
8122 (org-preserve-local-variables
8123 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8124 'org-get-last-sibling))
8125 (ins-point (make-marker))
8126 (cnt (abs arg))
8127 (col (current-column))
8128 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8129 ;; Select the tree
8130 (org-back-to-heading)
8131 (setq beg0 (point))
8132 (save-excursion
8133 (setq ne-beg (org-back-over-empty-lines))
8134 (setq beg (point)))
8135 (save-match-data
8136 (save-excursion (outline-end-of-heading)
8137 (setq folded (org-invisible-p)))
8138 (progn (org-end-of-subtree nil t)
8139 (unless (eobp) (backward-char))))
8140 (outline-next-heading)
8141 (setq ne-end (org-back-over-empty-lines))
8142 (setq end (point))
8143 (goto-char beg0)
8144 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8145 ;; include less whitespace
8146 (save-excursion
8147 (goto-char beg)
8148 (forward-line (- ne-beg ne-end))
8149 (setq beg (point))))
8150 ;; Find insertion point, with error handling
8151 (while (> cnt 0)
8152 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8153 (goto-char beg0)
8154 (user-error "Cannot move past superior level or buffer limit"))
8155 (setq cnt (1- cnt)))
8156 (when (> arg 0)
8157 ;; Moving forward - still need to move over subtree
8158 (org-end-of-subtree t t)
8159 (save-excursion
8160 (org-back-over-empty-lines)
8161 (or (bolp) (newline))))
8162 (setq ne-ins (org-back-over-empty-lines))
8163 (move-marker ins-point (point))
8164 (setq txt (buffer-substring beg end))
8165 (org-save-markers-in-region beg end)
8166 (delete-region beg end)
8167 (org-remove-empty-overlays-at beg)
8168 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8169 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8170 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8171 (let ((bbb (point)))
8172 (insert-before-markers txt)
8173 (org-reinstall-markers-in-region bbb)
8174 (move-marker ins-point bbb))
8175 (or (bolp) (insert "\n"))
8176 (setq ins-end (point))
8177 (goto-char ins-point)
8178 (org-skip-whitespace)
8179 (when (and (< arg 0)
8180 (org-first-sibling-p)
8181 (> ne-ins ne-beg))
8182 ;; Move whitespace back to beginning
8183 (save-excursion
8184 (goto-char ins-end)
8185 (let ((kill-whole-line t))
8186 (kill-line (- ne-ins ne-beg)) (point)))
8187 (insert (make-string (- ne-ins ne-beg) ?\n)))
8188 (move-marker ins-point nil)
8189 (if folded
8190 (outline-hide-subtree)
8191 (org-show-entry)
8192 (org-show-children))
8193 (org-clean-visibility-after-subtree-move)
8194 ;; move back to the initial column we were at
8195 (move-to-column col))))
8197 (defvar org-subtree-clip ""
8198 "Clipboard for cut and paste of subtrees.
8199 This is actually only a copy of the kill, because we use the normal kill
8200 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8202 (defvar org-subtree-clip-folded nil
8203 "Was the last copied subtree folded?
8204 This is used to fold the tree back after pasting.")
8206 (defun org-cut-subtree (&optional n)
8207 "Cut the current subtree into the clipboard.
8208 With prefix arg N, cut this many sequential subtrees.
8209 This is a short-hand for marking the subtree and then cutting it."
8210 (interactive "p")
8211 (org-copy-subtree n 'cut))
8213 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8214 "Copy the current subtree into the clipboard.
8215 With prefix arg N, copy this many sequential subtrees.
8216 This is a short-hand for marking the subtree and then copying it.
8217 If CUT is non-nil, actually cut the subtree.
8218 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8219 of some markers in the region, even if CUT is non-nil. This is
8220 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8221 (interactive "p")
8222 (org-preserve-local-variables
8223 (let (beg end folded (beg0 (point)))
8224 (if (called-interactively-p 'any)
8225 (org-back-to-heading nil) ; take what looks like a subtree
8226 (org-back-to-heading t)) ; take what is really there
8227 (setq beg (point))
8228 (skip-chars-forward " \t\r\n")
8229 (save-match-data
8230 (if nosubtrees
8231 (outline-next-heading)
8232 (save-excursion (outline-end-of-heading)
8233 (setq folded (org-invisible-p)))
8234 (ignore-errors (org-forward-heading-same-level (1- n) t))
8235 (org-end-of-subtree t t)))
8236 ;; Include the end of an inlinetask
8237 (when (and (featurep 'org-inlinetask)
8238 (looking-at-p (concat (org-inlinetask-outline-regexp)
8239 "END[ \t]*$")))
8240 (end-of-line))
8241 (setq end (point))
8242 (goto-char beg0)
8243 (when (> end beg)
8244 (setq org-subtree-clip-folded folded)
8245 (when (or cut force-store-markers)
8246 (org-save-markers-in-region beg end))
8247 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8248 (setq org-subtree-clip (current-kill 0))
8249 (message "%s: Subtree(s) with %d characters"
8250 (if cut "Cut" "Copied")
8251 (length org-subtree-clip))))))
8253 (defun org-paste-subtree (&optional level tree for-yank remove)
8254 "Paste the clipboard as a subtree, with modification of headline level.
8255 The entire subtree is promoted or demoted in order to match a new headline
8256 level.
8258 If the cursor is at the beginning of a headline, the same level as
8259 that headline is used to paste the tree.
8261 If not, the new level is derived from the *visible* headings
8262 before and after the insertion point, and taken to be the inferior headline
8263 level of the two. So if the previous visible heading is level 3 and the
8264 next is level 4 (or vice versa), level 4 will be used for insertion.
8265 This makes sure that the subtree remains an independent subtree and does
8266 not swallow low level entries.
8268 You can also force a different level, either by using a numeric prefix
8269 argument, or by inserting the heading marker by hand. For example, if the
8270 cursor is after \"*****\", then the tree will be shifted to level 5.
8272 If optional TREE is given, use this text instead of the kill ring.
8274 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8275 move back over whitespace before inserting, and move point to the end of
8276 the inserted text when done.
8278 When REMOVE is non-nil, remove the subtree from the clipboard."
8279 (interactive "P")
8280 (setq tree (or tree (and kill-ring (current-kill 0))))
8281 (unless (org-kill-is-subtree-p tree)
8282 (user-error "%s"
8283 (substitute-command-keys
8284 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8285 (org-with-limited-levels
8286 (let* ((visp (not (org-invisible-p)))
8287 (txt tree)
8288 (^re_ "\\(\\*+\\)[ \t]*")
8289 (old-level (if (string-match org-outline-regexp-bol txt)
8290 (- (match-end 0) (match-beginning 0) 1)
8291 -1))
8292 (force-level (cond (level (prefix-numeric-value level))
8293 ((and (looking-at "[ \t]*$")
8294 (string-match
8295 "^\\*+$" (buffer-substring
8296 (point-at-bol) (point))))
8297 (- (match-end 0) (match-beginning 0)))
8298 ((and (bolp)
8299 (looking-at org-outline-regexp))
8300 (- (match-end 0) (point) 1))))
8301 (previous-level (save-excursion
8302 (condition-case nil
8303 (progn
8304 (outline-previous-visible-heading 1)
8305 (if (looking-at ^re_)
8306 (- (match-end 0) (match-beginning 0) 1)
8308 (error 1))))
8309 (next-level (save-excursion
8310 (condition-case nil
8311 (progn
8312 (or (looking-at org-outline-regexp)
8313 (outline-next-visible-heading 1))
8314 (if (looking-at ^re_)
8315 (- (match-end 0) (match-beginning 0) 1)
8317 (error 1))))
8318 (new-level (or force-level (max previous-level next-level)))
8319 (shift (if (or (= old-level -1)
8320 (= new-level -1)
8321 (= old-level new-level))
8323 (- new-level old-level)))
8324 (delta (if (> shift 0) -1 1))
8325 (func (if (> shift 0) 'org-demote 'org-promote))
8326 (org-odd-levels-only nil)
8327 beg end newend)
8328 ;; Remove the forced level indicator
8329 (when force-level
8330 (delete-region (point-at-bol) (point)))
8331 ;; Paste
8332 (beginning-of-line (if (bolp) 1 2))
8333 (setq beg (point))
8334 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8335 (insert-before-markers txt)
8336 (unless (string-suffix-p "\n" txt) (insert "\n"))
8337 (setq newend (point))
8338 (org-reinstall-markers-in-region beg)
8339 (setq end (point))
8340 (goto-char beg)
8341 (skip-chars-forward " \t\n\r")
8342 (setq beg (point))
8343 (when (and (org-invisible-p) visp)
8344 (save-excursion (outline-show-heading)))
8345 ;; Shift if necessary
8346 (unless (= shift 0)
8347 (save-restriction
8348 (narrow-to-region beg end)
8349 (while (not (= shift 0))
8350 (org-map-region func (point-min) (point-max))
8351 (setq shift (+ delta shift)))
8352 (goto-char (point-min))
8353 (setq newend (point-max))))
8354 (when (or (called-interactively-p 'interactive) for-yank)
8355 (message "Clipboard pasted as level %d subtree" new-level))
8356 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8357 kill-ring
8358 (eq org-subtree-clip (current-kill 0))
8359 org-subtree-clip-folded)
8360 ;; The tree was folded before it was killed/copied
8361 (outline-hide-subtree))
8362 (and for-yank (goto-char newend))
8363 (and remove (setq kill-ring (cdr kill-ring))))))
8365 (defun org-kill-is-subtree-p (&optional txt)
8366 "Check if the current kill is an outline subtree, or a set of trees.
8367 Returns nil if kill does not start with a headline, or if the first
8368 headline level is not the largest headline level in the tree.
8369 So this will actually accept several entries of equal levels as well,
8370 which is OK for `org-paste-subtree'.
8371 If optional TXT is given, check this string instead of the current kill."
8372 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8373 (re (org-get-limited-outline-regexp))
8374 (^re (concat "^" re))
8375 (start-level (and kill
8376 (string-match
8377 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8378 kill)
8379 (- (match-end 2) (match-beginning 2) 1)))
8380 (start (1+ (or (match-beginning 2) -1))))
8381 (if (not start-level)
8382 (progn
8383 nil) ;; does not even start with a heading
8384 (catch 'exit
8385 (while (setq start (string-match ^re kill (1+ start)))
8386 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8387 (throw 'exit nil)))
8388 t))))
8390 (defvar org-markers-to-move nil
8391 "Markers that should be moved with a cut-and-paste operation.
8392 Those markers are stored together with their positions relative to
8393 the start of the region.")
8395 (defun org-save-markers-in-region (beg end)
8396 "Check markers in region.
8397 If these markers are between BEG and END, record their position relative
8398 to BEG, so that after moving the block of text, we can put the markers back
8399 into place.
8400 This function gets called just before an entry or tree gets cut from the
8401 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8402 called immediately, to move the markers with the entries."
8403 (setq org-markers-to-move nil)
8404 (when (featurep 'org-clock)
8405 (org-clock-save-markers-for-cut-and-paste beg end))
8406 (when (featurep 'org-agenda)
8407 (org-agenda-save-markers-for-cut-and-paste beg end)))
8409 (defun org-check-and-save-marker (marker beg end)
8410 "Check if MARKER is between BEG and END.
8411 If yes, remember the marker and the distance to BEG."
8412 (when (and (marker-buffer marker)
8413 (equal (marker-buffer marker) (current-buffer))
8414 (>= marker beg) (< marker end))
8415 (push (cons marker (- marker beg)) org-markers-to-move)))
8417 (defun org-reinstall-markers-in-region (beg)
8418 "Move all remembered markers to their position relative to BEG."
8419 (dolist (x org-markers-to-move)
8420 (move-marker (car x) (+ beg (cdr x))))
8421 (setq org-markers-to-move nil))
8423 (defun org-narrow-to-subtree ()
8424 "Narrow buffer to the current subtree."
8425 (interactive)
8426 (save-excursion
8427 (save-match-data
8428 (org-with-limited-levels
8429 (narrow-to-region
8430 (progn (org-back-to-heading t) (point))
8431 (progn (org-end-of-subtree t t)
8432 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8433 (point)))))))
8435 (defun org-narrow-to-block ()
8436 "Narrow buffer to the current block."
8437 (interactive)
8438 (let* ((case-fold-search t)
8439 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8440 "^[ \t]*#\\+end_.*")))
8441 (if blockp
8442 (narrow-to-region (car blockp) (cdr blockp))
8443 (user-error "Not in a block"))))
8445 (defun org-clone-subtree-with-time-shift (n &optional shift)
8446 "Clone the task (subtree) at point N times.
8447 The clones will be inserted as siblings.
8449 In interactive use, the user will be prompted for the number of
8450 clones to be produced. If the entry has a timestamp, the user
8451 will also be prompted for a time shift, which may be a repeater
8452 as used in time stamps, for example `+3d'. To disable this,
8453 you can call the function with a universal prefix argument.
8455 When a valid repeater is given and the entry contains any time
8456 stamps, the clones will become a sequence in time, with time
8457 stamps in the subtree shifted for each clone produced. If SHIFT
8458 is nil or the empty string, time stamps will be left alone. The
8459 ID property of the original subtree is removed.
8461 In each clone, all the CLOCK entries will be removed. This
8462 prevents Org from considering that the clocked times overlap.
8464 If the original subtree did contain time stamps with a repeater,
8465 the following will happen:
8466 - the repeater will be removed in each clone
8467 - an additional clone will be produced, with the current, unshifted
8468 date(s) in the entry.
8469 - the original entry will be placed *after* all the clones, with
8470 repeater intact.
8471 - the start days in the repeater in the original entry will be shifted
8472 to past the last clone.
8473 In this way you can spell out a number of instances of a repeating task,
8474 and still retain the repeater to cover future instances of the task.
8476 As described above, N+1 clones are produced when the original
8477 subtree has a repeater. Setting N to 0, then, can be used to
8478 remove the repeater from a subtree and create a shifted clone
8479 with the original repeater."
8480 (interactive "nNumber of clones to produce: ")
8481 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8482 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8483 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8484 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8485 (shift
8486 (or shift
8487 (if (and (not (equal current-prefix-arg '(4)))
8488 (save-excursion
8489 (goto-char beg)
8490 (re-search-forward org-ts-regexp-both end-of-tree t)))
8491 (read-from-minibuffer
8492 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8493 ""))) ;No time shift
8494 (doshift
8495 (and (org-string-nw-p shift)
8496 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8497 shift)
8498 (user-error "Invalid shift specification %s" shift)))))
8499 (goto-char end-of-tree)
8500 (unless (bolp) (insert "\n"))
8501 (let* ((end (point))
8502 (template (buffer-substring beg end))
8503 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8504 (shift-what (pcase (and doshift (match-string 2 shift))
8505 (`nil nil)
8506 ("d" 'day)
8507 ("w" (setq shift-n (* 7 shift-n)) 'day)
8508 ("m" 'month)
8509 ("y" 'year)
8510 (_ (error "Unsupported time unit"))))
8511 (nmin 1)
8512 (nmax n)
8513 (n-no-remove -1)
8514 (idprop (org-entry-get nil "ID")))
8515 (when (and doshift
8516 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8517 template))
8518 (delete-region beg end)
8519 (setq end beg)
8520 (setq nmin 0)
8521 (setq nmax (1+ nmax))
8522 (setq n-no-remove nmax))
8523 (goto-char end)
8524 (cl-loop for n from nmin to nmax do
8525 (insert
8526 ;; Prepare clone.
8527 (with-temp-buffer
8528 (insert template)
8529 (org-mode)
8530 (goto-char (point-min))
8531 (org-show-subtree)
8532 (and idprop (if org-clone-delete-id
8533 (org-entry-delete nil "ID")
8534 (org-id-get-create t)))
8535 (unless (= n 0)
8536 (while (re-search-forward org-clock-line-re nil t)
8537 (delete-region (line-beginning-position)
8538 (line-beginning-position 2)))
8539 (goto-char (point-min))
8540 (while (re-search-forward org-drawer-regexp nil t)
8541 (org-remove-empty-drawer-at (point))))
8542 (goto-char (point-min))
8543 (when doshift
8544 (while (re-search-forward org-ts-regexp-both nil t)
8545 (org-timestamp-change (* n shift-n) shift-what))
8546 (unless (= n n-no-remove)
8547 (goto-char (point-min))
8548 (while (re-search-forward org-ts-regexp nil t)
8549 (save-excursion
8550 (goto-char (match-beginning 0))
8551 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8552 (delete-region (match-beginning 1) (match-end 1)))))))
8553 (buffer-string)))))
8554 (goto-char beg)))
8556 ;;; Outline Sorting
8558 (defun org-sort (&optional with-case)
8559 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8560 Optional argument WITH-CASE means sort case-sensitively."
8561 (interactive "P")
8562 (org-call-with-arg
8563 (cond ((org-at-table-p) #'org-table-sort-lines)
8564 ((org-at-item-p) #'org-sort-list)
8565 (t #'org-sort-entries))
8566 with-case))
8568 (defun org-sort-remove-invisible (s)
8569 "Remove invisible part of links and emphasis markers from string S."
8570 (remove-text-properties 0 (length s) org-rm-props s)
8571 (replace-regexp-in-string
8572 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8573 (replace-regexp-in-string
8574 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8575 (org-link-display-format s)
8576 t t) t t))
8578 (defvar org-priority-regexp) ; defined later in the file
8580 (defvar org-after-sorting-entries-or-items-hook nil
8581 "Hook that is run after a bunch of entries or items have been sorted.
8582 When children are sorted, the cursor is in the parent line when this
8583 hook gets called. When a region or a plain list is sorted, the cursor
8584 will be in the first entry of the sorted region/list.")
8586 (defun org-sort-entries
8587 (&optional with-case sorting-type getkey-func compare-func property
8588 interactive?)
8589 "Sort entries on a certain level of an outline tree.
8590 If there is an active region, the entries in the region are sorted.
8591 Else, if the cursor is before the first entry, sort the top-level items.
8592 Else, the children of the entry at point are sorted.
8594 Sorting can be alphabetically, numerically, by date/time as given by
8595 a time stamp, by a property, by priority order, or by a custom function.
8597 The command prompts for the sorting type unless it has been given to the
8598 function through the SORTING-TYPE argument, which needs to be a character,
8599 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8600 the precise meaning of each character:
8602 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8603 c By creation time, which is assumed to be the first inactive time stamp
8604 at the beginning of a line.
8605 d By deadline date/time.
8606 k By clocking time.
8607 n Numerically, by converting the beginning of the entry/item to a number.
8608 o By order of TODO keywords.
8609 p By priority according to the cookie.
8610 r By the value of a property.
8611 s By scheduled date/time.
8612 t By date/time, either the first active time stamp in the entry, or, if
8613 none exist, by the first inactive one.
8615 Capital letters will reverse the sort order.
8617 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8618 called with point at the beginning of the record. It must return a
8619 value that is compatible with COMPARE-FUNC, the function used to
8620 compare entries.
8622 Comparing entries ignores case by default. However, with an optional argument
8623 WITH-CASE, the sorting considers case as well.
8625 Sorting is done against the visible part of the headlines, it ignores hidden
8626 links.
8628 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8630 A non-nil value for INTERACTIVE? is used to signal that this
8631 function is being called interactively."
8632 (interactive (list current-prefix-arg nil nil nil nil t))
8633 (let ((case-func (if with-case 'identity 'downcase))
8634 start beg end stars re re2
8635 txt what tmp)
8636 ;; Find beginning and end of region to sort
8637 (cond
8638 ((org-region-active-p)
8639 ;; we will sort the region
8640 (setq end (region-end)
8641 what "region")
8642 (goto-char (region-beginning))
8643 (unless (org-at-heading-p) (outline-next-heading))
8644 (setq start (point)))
8645 ((or (org-at-heading-p)
8646 (ignore-errors (progn (org-back-to-heading) t)))
8647 ;; we will sort the children of the current headline
8648 (org-back-to-heading)
8649 (setq start (point)
8650 end (progn (org-end-of-subtree t t)
8651 (or (bolp) (insert "\n"))
8652 (when (>= (org-back-over-empty-lines) 1)
8653 (forward-line 1))
8654 (point))
8655 what "children")
8656 (goto-char start)
8657 (outline-show-subtree)
8658 (outline-next-heading))
8660 ;; we will sort the top-level entries in this file
8661 (goto-char (point-min))
8662 (or (org-at-heading-p) (outline-next-heading))
8663 (setq start (point))
8664 (goto-char (point-max))
8665 (beginning-of-line 1)
8666 (when (looking-at ".*?\\S-")
8667 ;; File ends in a non-white line
8668 (end-of-line 1)
8669 (insert "\n"))
8670 (setq end (point-max))
8671 (setq what "top-level")
8672 (goto-char start)
8673 (org-show-all '(headings blocks))))
8675 (setq beg (point))
8676 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8678 (looking-at "\\(\\*+\\)")
8679 (setq stars (match-string 1)
8680 re (concat "^" (regexp-quote stars) " +")
8681 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8682 txt (buffer-substring beg end))
8683 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8684 (when (and (not (equal stars "*")) (string-match re2 txt))
8685 (user-error "Region to sort contains a level above the first entry"))
8687 (unless sorting-type
8688 (message
8689 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8690 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8691 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8692 what)
8693 (setq sorting-type (read-char-exclusive)))
8695 (unless getkey-func
8696 (and (= (downcase sorting-type) ?f)
8697 (setq getkey-func
8698 (or (and interactive?
8699 (org-read-function
8700 "Function for extracting keys: "))
8701 (error "Missing key extractor")))))
8703 (and (= (downcase sorting-type) ?r)
8704 (not property)
8705 (setq property
8706 (completing-read "Property: "
8707 (mapcar #'list (org-buffer-property-keys t))
8708 nil t)))
8710 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8711 (message "Sorting entries...")
8713 (save-restriction
8714 (narrow-to-region start end)
8715 (let ((restore-clock?
8716 ;; The clock marker is lost when using `sort-subr'; mark
8717 ;; the clock with temporary `:org-clock-marker-backup'
8718 ;; text property.
8719 (when (and (eq (org-clock-is-active) (current-buffer))
8720 (<= start (marker-position org-clock-marker))
8721 (>= end (marker-position org-clock-marker)))
8722 (org-with-silent-modifications
8723 (put-text-property (1- org-clock-marker) org-clock-marker
8724 :org-clock-marker-backup t))
8726 (dcst (downcase sorting-type))
8727 (case-fold-search nil)
8728 (now (current-time)))
8729 (org-preserve-local-variables
8730 (sort-subr
8731 (/= dcst sorting-type)
8732 ;; This function moves to the beginning character of the
8733 ;; "record" to be sorted.
8734 (lambda nil
8735 (if (re-search-forward re nil t)
8736 (goto-char (match-beginning 0))
8737 (goto-char (point-max))))
8738 ;; This function moves to the last character of the "record" being
8739 ;; sorted.
8740 (lambda nil
8741 (save-match-data
8742 (condition-case nil
8743 (outline-forward-same-level 1)
8744 (error
8745 (goto-char (point-max))))))
8746 ;; This function returns the value that gets sorted against.
8747 (lambda ()
8748 (cond
8749 ((= dcst ?n)
8750 (if (looking-at org-complex-heading-regexp)
8751 (string-to-number
8752 (org-sort-remove-invisible (match-string 4)))
8753 nil))
8754 ((= dcst ?a)
8755 (if (looking-at org-complex-heading-regexp)
8756 (funcall case-func
8757 (org-sort-remove-invisible (match-string 4)))
8758 nil))
8759 ((= dcst ?k)
8760 (or (get-text-property (point) :org-clock-minutes) 0))
8761 ((= dcst ?t)
8762 (let ((end (save-excursion (outline-next-heading) (point))))
8763 (if (or (re-search-forward org-ts-regexp end t)
8764 (re-search-forward org-ts-regexp-both end t))
8765 (org-time-string-to-seconds (match-string 0))
8766 (float-time now))))
8767 ((= dcst ?c)
8768 (let ((end (save-excursion (outline-next-heading) (point))))
8769 (if (re-search-forward
8770 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8771 end t)
8772 (org-time-string-to-seconds (match-string 0))
8773 (float-time now))))
8774 ((= dcst ?s)
8775 (let ((end (save-excursion (outline-next-heading) (point))))
8776 (if (re-search-forward org-scheduled-time-regexp end t)
8777 (org-time-string-to-seconds (match-string 1))
8778 (float-time now))))
8779 ((= dcst ?d)
8780 (let ((end (save-excursion (outline-next-heading) (point))))
8781 (if (re-search-forward org-deadline-time-regexp end t)
8782 (org-time-string-to-seconds (match-string 1))
8783 (float-time now))))
8784 ((= dcst ?p)
8785 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8786 (string-to-char (match-string 2))
8787 org-default-priority))
8788 ((= dcst ?r)
8789 (or (org-entry-get nil property) ""))
8790 ((= dcst ?o)
8791 (when (looking-at org-complex-heading-regexp)
8792 (let* ((m (match-string 2))
8793 (s (if (member m org-done-keywords) '- '+)))
8794 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8795 ((= dcst ?f)
8796 (if getkey-func
8797 (progn
8798 (setq tmp (funcall getkey-func))
8799 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8800 tmp)
8801 (error "Invalid key function `%s'" getkey-func)))
8802 (t (error "Invalid sorting type `%c'" sorting-type))))
8804 (cond
8805 ((= dcst ?a) 'string<)
8806 ((= dcst ?f)
8807 (or compare-func
8808 (and interactive?
8809 (org-read-function
8810 (concat "Function for comparing keys "
8811 "(empty for default `sort-subr' predicate): ")
8812 'allow-empty))))
8813 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8814 (when restore-clock?
8815 (move-marker org-clock-marker
8816 (1+ (next-single-property-change
8817 start :org-clock-marker-backup)))
8818 (remove-text-properties (1- org-clock-marker) org-clock-marker
8819 '(:org-clock-marker-backup t)))))
8820 (run-hooks 'org-after-sorting-entries-or-items-hook)
8821 (message "Sorting entries...done")))
8823 (defun org-contextualize-keys (alist contexts)
8824 "Return valid elements in ALIST depending on CONTEXTS.
8826 `org-agenda-custom-commands' or `org-capture-templates' are the
8827 values used for ALIST, and `org-agenda-custom-commands-contexts'
8828 or `org-capture-templates-contexts' are the associated contexts
8829 definitions."
8830 (let ((contexts
8831 ;; normalize contexts
8832 (mapcar
8833 (lambda(c) (cond ((listp (cadr c))
8834 (list (car c) (car c) (nth 1 c)))
8835 ((string= "" (cadr c))
8836 (list (car c) (car c) (nth 2 c)))
8837 (t c)))
8838 contexts))
8839 (a alist) r s)
8840 ;; loop over all commands or templates
8841 (dolist (c a)
8842 (let (vrules repl)
8843 (cond
8844 ((not (assoc (car c) contexts))
8845 (push c r))
8846 ((and (assoc (car c) contexts)
8847 (setq vrules (org-contextualize-validate-key
8848 (car c) contexts)))
8849 (mapc (lambda (vr)
8850 (unless (equal (car vr) (cadr vr))
8851 (setq repl vr)))
8852 vrules)
8853 (if (not repl) (push c r)
8854 (push (cadr repl) s)
8855 (push
8856 (cons (car c)
8857 (cdr (or (assoc (cadr repl) alist)
8858 (error "Undefined key `%s' as contextual replacement for `%s'"
8859 (cadr repl) (car c)))))
8860 r))))))
8861 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8862 (delq
8864 (delete-dups
8865 (mapcar (lambda (x)
8866 (let ((tpl (car x)))
8867 (unless (delq
8869 (mapcar (lambda (y)
8870 (equal y tpl))
8872 x)))
8873 (reverse r))))))
8875 (defun org-contextualize-validate-key (key contexts)
8876 "Check CONTEXTS for agenda or capture KEY."
8877 (let (res)
8878 (dolist (r contexts)
8879 (dolist (rr (car (last r)))
8880 (when
8881 (and (equal key (car r))
8882 (if (functionp rr) (funcall rr)
8883 (or (and (eq (car rr) 'in-file)
8884 (buffer-file-name)
8885 (string-match (cdr rr) (buffer-file-name)))
8886 (and (eq (car rr) 'in-mode)
8887 (string-match (cdr rr) (symbol-name major-mode)))
8888 (and (eq (car rr) 'in-buffer)
8889 (string-match (cdr rr) (buffer-name)))
8890 (when (and (eq (car rr) 'not-in-file)
8891 (buffer-file-name))
8892 (not (string-match (cdr rr) (buffer-file-name))))
8893 (when (eq (car rr) 'not-in-mode)
8894 (not (string-match (cdr rr) (symbol-name major-mode))))
8895 (when (eq (car rr) 'not-in-buffer)
8896 (not (string-match (cdr rr) (buffer-name)))))))
8897 (push r res))))
8898 (delete-dups (delq nil res))))
8900 (defun org-context-p (&rest contexts)
8901 "Check if local context is any of CONTEXTS.
8902 Possible values in the list of contexts are `table', `headline', and `item'."
8903 (let ((pos (point)))
8904 (goto-char (point-at-bol))
8905 (prog1 (or (and (memq 'table contexts)
8906 (looking-at "[ \t]*|"))
8907 (and (memq 'headline contexts)
8908 (looking-at org-outline-regexp))
8909 (and (memq 'item contexts)
8910 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8911 (and (memq 'item-body contexts)
8912 (org-in-item-p)))
8913 (goto-char pos))))
8915 ;;;###autoload
8916 (defun org-run-like-in-org-mode (cmd)
8917 "Run a command, pretending that the current buffer is in Org mode.
8918 This will temporarily bind local variables that are typically bound in
8919 Org mode to the values they have in Org mode, and then interactively
8920 call CMD."
8921 (org-load-modules-maybe)
8922 (let (binds)
8923 (dolist (var (org-get-local-variables))
8924 (when (or (not (boundp (car var)))
8925 (eq (symbol-value (car var))
8926 (default-value (car var))))
8927 (push (list (car var) `(quote ,(cadr var))) binds)))
8928 (eval `(let ,binds
8929 (call-interactively (quote ,cmd))))))
8931 (defun org-get-category (&optional pos force-refresh)
8932 "Get the category applying to position POS."
8933 (save-match-data
8934 (when force-refresh (org-refresh-category-properties))
8935 (let ((pos (or pos (point))))
8936 (or (get-text-property pos 'org-category)
8937 (progn (org-refresh-category-properties)
8938 (get-text-property pos 'org-category))))))
8940 ;;; Refresh properties
8942 (defun org-refresh-properties (dprop tprop)
8943 "Refresh buffer text properties.
8944 DPROP is the drawer property and TPROP is either the
8945 corresponding text property to set, or an alist with each element
8946 being a text property (as a symbol) and a function to apply to
8947 the value of the drawer property."
8948 (let* ((case-fold-search t)
8949 (inhibit-read-only t)
8950 (inherit? (org-property-inherit-p dprop))
8951 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8952 (global (and inherit? (org--property-global-value dprop nil))))
8953 (org-with-silent-modifications
8954 (org-with-point-at 1
8955 ;; Set global values (e.g., values defined through
8956 ;; "#+PROPERTY:" keywords) to the whole buffer.
8957 (when global (put-text-property (point-min) (point-max) tprop global))
8958 ;; Set local values.
8959 (while (re-search-forward property-re nil t)
8960 (when (org-at-property-p)
8961 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8962 (outline-next-heading))))))
8964 (defun org-refresh-property (tprop p &optional inherit)
8965 "Refresh the buffer text property TPROP from the drawer property P.
8966 The refresh happens only for the current headline, or the whole
8967 sub-tree if optional argument INHERIT is non-nil."
8968 (unless (org-before-first-heading-p)
8969 (save-excursion
8970 (org-back-to-heading t)
8971 (let ((start (point))
8972 (end (save-excursion
8973 (if inherit (org-end-of-subtree t t)
8974 (or (outline-next-heading) (point-max))))))
8975 (if (symbolp tprop)
8976 ;; TPROP is a text property symbol.
8977 (put-text-property start end tprop p)
8978 ;; TPROP is an alist with (property . function) elements.
8979 (pcase-dolist (`(,prop . ,f) tprop)
8980 (put-text-property start end prop (funcall f p))))))))
8982 (defun org-refresh-category-properties ()
8983 "Refresh category text properties in the buffer."
8984 (let ((case-fold-search t)
8985 (inhibit-read-only t)
8986 (default-category
8987 (cond ((null org-category)
8988 (if buffer-file-name
8989 (file-name-sans-extension
8990 (file-name-nondirectory buffer-file-name))
8991 "???"))
8992 ((symbolp org-category) (symbol-name org-category))
8993 (t org-category))))
8994 (org-with-silent-modifications
8995 (org-with-wide-buffer
8996 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8997 ;; This is the default category for the buffer. If none is
8998 ;; found, fall-back to `org-category' or buffer file name.
8999 (put-text-property
9000 (point-min) (point-max)
9001 'org-category
9002 (catch 'buffer-category
9003 (goto-char (point-max))
9004 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9005 (let ((element (org-element-at-point)))
9006 (when (eq (org-element-type element) 'keyword)
9007 (throw 'buffer-category
9008 (org-element-property :value element)))))
9009 default-category))
9010 ;; Set sub-tree specific categories.
9011 (goto-char (point-min))
9012 (let ((regexp (org-re-property "CATEGORY")))
9013 (while (re-search-forward regexp nil t)
9014 (let ((value (match-string-no-properties 3)))
9015 (when (org-at-property-p)
9016 (put-text-property
9017 (save-excursion (org-back-to-heading t) (point))
9018 (save-excursion (org-end-of-subtree t t) (point))
9019 'org-category
9020 value)))))))))
9022 (defun org-refresh-stats-properties ()
9023 "Refresh stats text properties in the buffer."
9024 (org-with-silent-modifications
9025 (org-with-point-at 1
9026 (let ((regexp (concat org-outline-regexp-bol
9027 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9028 (while (re-search-forward regexp nil t)
9029 (let* ((numerator (string-to-number (match-string 1)))
9030 (denominator (and (match-end 2)
9031 (string-to-number (match-string 2))))
9032 (stats (cond ((not denominator) numerator) ;percent
9033 ((= denominator 0) 0)
9034 (t (/ (* numerator 100) denominator)))))
9035 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9036 'org-stats stats)))))))
9038 (defun org-refresh-effort-properties ()
9039 "Refresh effort properties"
9040 (org-refresh-properties
9041 org-effort-property
9042 '((effort . identity)
9043 (effort-minutes . org-duration-to-minutes))))
9045 ;;;; Link Stuff
9047 ;;; Link abbreviations
9049 (defun org-link-expand-abbrev (link)
9050 "Apply replacements as defined in `org-link-abbrev-alist'."
9051 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9052 (let* ((key (match-string 1 link))
9053 (as (or (assoc key org-link-abbrev-alist-local)
9054 (assoc key org-link-abbrev-alist)))
9055 (tag (and (match-end 2) (match-string 3 link)))
9056 rpl)
9057 (if (not as)
9058 link
9059 (setq rpl (cdr as))
9060 (cond
9061 ((symbolp rpl) (funcall rpl tag))
9062 ((string-match "%(\\([^)]+\\))" rpl)
9063 (replace-match
9064 (save-match-data
9065 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9066 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9067 ((string-match "%h" rpl)
9068 (replace-match (url-hexify-string (or tag "")) t t rpl))
9069 (t (concat rpl tag)))))
9070 link))
9072 ;;; Storing and inserting links
9074 (defvar org-insert-link-history nil
9075 "Minibuffer history for links inserted with `org-insert-link'.")
9077 (defvar org-stored-links nil
9078 "Contains the links stored with `org-store-link'.")
9080 (defvar org-store-link-plist nil
9081 "Plist with info about the most recently link created with `org-store-link'.")
9083 (defun org-store-link-functions ()
9084 "Return a list of functions that are called to create and store a link.
9085 The functions defined in the :store property of
9086 `org-link-parameters'.
9088 Each function will be called in turn until one returns a non-nil
9089 value. Each function should check if it is responsible for
9090 creating this link (for example by looking at the major mode).
9091 If not, it must exit and return nil. If yes, it should return
9092 a non-nil value after calling `org-store-link-props' with a list
9093 of properties and values. Special properties are:
9095 :type The link prefix, like \"http\". This must be given.
9096 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9097 This is obligatory as well.
9098 :description Optional default description for the second pair
9099 of brackets in an Org mode link. The user can still change
9100 this when inserting this link into an Org mode buffer.
9102 In addition to these, any additional properties can be specified
9103 and then used in capture templates."
9104 (cl-loop for link in org-link-parameters
9105 with store-func
9106 do (setq store-func (org-link-get-parameter (car link) :store))
9107 if store-func
9108 collect store-func))
9110 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9111 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9113 ;;;###autoload
9114 (defun org-store-link (arg &optional interactive?)
9115 "Store an org-link to the current location.
9116 \\<org-mode-map>
9117 This link is added to `org-stored-links' and can later be inserted
9118 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9120 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9121 A single
9122 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9123 `org-gnus-prefer-web-links' for links to Usenet articles.
9125 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9126 skipping storing functions that are not
9127 part of Org core.
9129 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9130 prefix ARG forces storing a link for each line in the
9131 active region.
9133 Assume the function is called interactively if INTERACTIVE? is
9134 non-nil."
9135 (interactive "P\np")
9136 (org-load-modules-maybe)
9137 (if (and (equal arg '(64)) (org-region-active-p))
9138 (save-excursion
9139 (let ((end (region-end)))
9140 (goto-char (region-beginning))
9141 (set-mark (point))
9142 (while (< (point-at-eol) end)
9143 (move-end-of-line 1) (activate-mark)
9144 (let (current-prefix-arg)
9145 (call-interactively 'org-store-link))
9146 (move-beginning-of-line 2)
9147 (set-mark (point)))))
9148 (setq org-store-link-plist nil)
9149 (let (link cpltxt desc description search txt custom-id agenda-link)
9150 (cond
9151 ;; Store a link using an external link type, if any function is
9152 ;; available. If more than one can generate a link from current
9153 ;; location, ask which one to use.
9154 ((and (not (equal arg '(16)))
9155 (let ((results-alist nil))
9156 (dolist (f (org-store-link-functions))
9157 (when (funcall f)
9158 ;; XXX: return value is not link's plist, so we
9159 ;; store the new value before it is modified. It
9160 ;; would be cleaner to ask store link functions to
9161 ;; return the plist instead.
9162 (push (cons f (copy-sequence org-store-link-plist))
9163 results-alist)))
9164 (pcase results-alist
9165 (`nil nil)
9166 (`((,_ . ,_)) t) ;single choice: nothing to do
9167 (`((,name . ,_) . ,_)
9168 ;; Reinstate link plist associated to the chosen
9169 ;; function.
9170 (apply #'org-store-link-props
9171 (cdr (assoc-string
9172 (completing-read
9173 "Which function for creating the link? "
9174 (mapcar #'car results-alist)
9175 nil t (symbol-name name))
9176 results-alist)))
9177 t))))
9178 (setq link (plist-get org-store-link-plist :link))
9179 (setq desc (or (plist-get org-store-link-plist :description)
9180 link)))
9182 ;; Store a link from a source code buffer.
9183 ((org-src-edit-buffer-p)
9184 (let ((coderef-format (org-src-coderef-format)))
9185 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9186 (setq link (format "(%s)" (match-string-no-properties 3))))
9187 (interactive?
9188 (let ((label (read-string "Code line label: ")))
9189 (end-of-line)
9190 (setq link (format coderef-format label))
9191 (let ((gc (- 79 (length link))))
9192 (if (< (current-column) gc)
9193 (org-move-to-column gc t)
9194 (insert " ")))
9195 (insert link)
9196 (setq link (concat "(" label ")"))
9197 (setq desc nil)))
9198 (t (setq link nil)))))
9200 ;; We are in the agenda, link to referenced location
9201 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9202 (let ((m (or (get-text-property (point) 'org-hd-marker)
9203 (get-text-property (point) 'org-marker))))
9204 (when m
9205 (org-with-point-at m
9206 (setq agenda-link (org-store-link nil interactive?))))))
9208 ((eq major-mode 'calendar-mode)
9209 (let ((cd (calendar-cursor-to-date)))
9210 (setq link
9211 (format-time-string
9212 (car org-time-stamp-formats)
9213 (apply 'encode-time
9214 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9215 nil nil nil))))
9216 (org-store-link-props :type "calendar" :date cd)))
9218 ((eq major-mode 'help-mode)
9219 (setq link (concat "help:" (save-excursion
9220 (goto-char (point-min))
9221 (looking-at "^[^ ]+")
9222 (match-string 0))))
9223 (org-store-link-props :type "help"))
9225 ((eq major-mode 'w3-mode)
9226 (setq cpltxt (if (and (buffer-name)
9227 (not (string-match "Untitled" (buffer-name))))
9228 (buffer-name)
9229 (url-view-url t))
9230 link (url-view-url t))
9231 (org-store-link-props :type "w3" :url (url-view-url t)))
9233 ((eq major-mode 'image-mode)
9234 (setq cpltxt (concat "file:"
9235 (abbreviate-file-name buffer-file-name))
9236 link cpltxt)
9237 (org-store-link-props :type "image" :file buffer-file-name))
9239 ;; In dired, store a link to the file of the current line
9240 ((derived-mode-p 'dired-mode)
9241 (let ((file (dired-get-filename nil t)))
9242 (setq file (if file
9243 (abbreviate-file-name
9244 (expand-file-name (dired-get-filename nil t)))
9245 ;; otherwise, no file so use current directory.
9246 default-directory))
9247 (setq cpltxt (concat "file:" file)
9248 link cpltxt)))
9250 ((setq search (run-hook-with-args-until-success
9251 'org-create-file-search-functions))
9252 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9253 "::" search))
9254 (setq cpltxt (or description link)))
9256 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9257 (org-with-limited-levels
9258 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9259 (cond
9260 ;; Store a link using the target at point
9261 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9262 (setq cpltxt
9263 (concat "file:"
9264 (abbreviate-file-name
9265 (buffer-file-name (buffer-base-buffer)))
9266 "::" (match-string 1))
9267 link cpltxt))
9268 ((and (featurep 'org-id)
9269 (or (eq org-id-link-to-org-use-id t)
9270 (and interactive?
9271 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9272 (and (eq org-id-link-to-org-use-id
9273 'create-if-interactive-and-no-custom-id)
9274 (not custom-id))))
9275 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9276 ;; Store a link using the ID at point
9277 (setq link (condition-case nil
9278 (prog1 (org-id-store-link)
9279 (setq desc (or (plist-get org-store-link-plist
9280 :description)
9281 "")))
9282 (error
9283 ;; Probably before first headline, link only to file
9284 (concat "file:"
9285 (abbreviate-file-name
9286 (buffer-file-name (buffer-base-buffer))))))))
9288 ;; Just link to current headline
9289 (setq cpltxt (concat "file:"
9290 (abbreviate-file-name
9291 (buffer-file-name (buffer-base-buffer)))))
9292 ;; Add a context search string
9293 (when (org-xor org-context-in-file-links
9294 (equal arg '(4)))
9295 (let* ((element (org-element-at-point))
9296 (name (org-element-property :name element)))
9297 (setq txt (cond
9298 ((org-at-heading-p) nil)
9299 (name)
9300 ((org-region-active-p)
9301 (buffer-substring (region-beginning) (region-end)))))
9302 (when (or (null txt) (string-match "\\S-" txt))
9303 (setq cpltxt
9304 (concat cpltxt "::"
9305 (condition-case nil
9306 (org-make-org-heading-search-string txt)
9307 (error "")))
9308 desc (or name
9309 (nth 4 (ignore-errors (org-heading-components)))
9310 "NONE")))))
9311 (when (string-match "::\\'" cpltxt)
9312 (setq cpltxt (substring cpltxt 0 -2)))
9313 (setq link cpltxt)))))
9315 ((buffer-file-name (buffer-base-buffer))
9316 ;; Just link to this file here.
9317 (setq cpltxt (concat "file:"
9318 (abbreviate-file-name
9319 (buffer-file-name (buffer-base-buffer)))))
9320 ;; Add a context string.
9321 (when (org-xor org-context-in-file-links
9322 (equal arg '(4)))
9323 (setq txt (if (org-region-active-p)
9324 (buffer-substring (region-beginning) (region-end))
9325 (buffer-substring (point-at-bol) (point-at-eol))))
9326 ;; Only use search option if there is some text.
9327 (when (string-match "\\S-" txt)
9328 (setq cpltxt
9329 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9330 desc "NONE")))
9331 (setq link cpltxt))
9333 (interactive?
9334 (user-error "No method for storing a link from this buffer"))
9336 (t (setq link nil)))
9338 ;; We're done setting link and desc, clean up
9339 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9340 (setq link (or link cpltxt)
9341 desc (or desc cpltxt))
9342 (cond ((not desc))
9343 ((equal desc "NONE") (setq desc nil))
9344 (t (setq desc
9345 (replace-regexp-in-string
9346 org-bracket-link-analytic-regexp
9347 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9348 desc))))
9349 ;; Return the link
9350 (if (not (and interactive? link))
9351 (or agenda-link (and link (org-make-link-string link desc)))
9352 (push (list link desc) org-stored-links)
9353 (message "Stored: %s" (or desc link))
9354 (when custom-id
9355 (setq link (concat "file:" (abbreviate-file-name
9356 (buffer-file-name)) "::#" custom-id))
9357 (push (list link desc) org-stored-links))
9358 (car org-stored-links)))))
9360 (defun org-store-link-props (&rest plist)
9361 "Store link properties.
9362 The properties are pre-processed by extracting names, addresses
9363 and dates."
9364 (let ((x (plist-get plist :from)))
9365 (when x
9366 (let ((adr (mail-extract-address-components x)))
9367 (setq plist (plist-put plist :fromname (car adr)))
9368 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9369 (let ((x (plist-get plist :to)))
9370 (when x
9371 (let ((adr (mail-extract-address-components x)))
9372 (setq plist (plist-put plist :toname (car adr)))
9373 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9374 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9375 (when x
9376 (setq plist (plist-put plist :date-timestamp
9377 (format-time-string
9378 (org-time-stamp-format t) x)))
9379 (setq plist (plist-put plist :date-timestamp-inactive
9380 (format-time-string
9381 (org-time-stamp-format t t) x)))))
9382 (let ((from (plist-get plist :from))
9383 (to (plist-get plist :to)))
9384 (when (and from to org-from-is-user-regexp)
9385 (setq plist
9386 (plist-put plist :fromto
9387 (if (string-match org-from-is-user-regexp from)
9388 (concat "to %t")
9389 (concat "from %f"))))))
9390 (setq org-store-link-plist plist))
9392 (defun org-add-link-props (&rest plist)
9393 "Add these properties to the link property list."
9394 (let (key value)
9395 (while plist
9396 (setq key (pop plist) value (pop plist))
9397 (setq org-store-link-plist
9398 (plist-put org-store-link-plist key value)))))
9400 (defun org-email-link-description (&optional fmt)
9401 "Return the description part of an email link.
9402 This takes information from `org-store-link-plist' and formats it
9403 according to FMT (default from `org-email-link-description-format')."
9404 (setq fmt (or fmt org-email-link-description-format))
9405 (let* ((p org-store-link-plist)
9406 (to (plist-get p :toaddress))
9407 (from (plist-get p :fromaddress))
9408 (table
9409 (list
9410 (cons "%c" (plist-get p :fromto))
9411 (cons "%F" (plist-get p :from))
9412 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9413 (cons "%T" (plist-get p :to))
9414 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9415 (cons "%s" (plist-get p :subject))
9416 (cons "%d" (plist-get p :date))
9417 (cons "%m" (plist-get p :message-id)))))
9418 (when (string-match "%c" fmt)
9419 ;; Check if the user wrote this message
9420 (if (and org-from-is-user-regexp from to
9421 (save-match-data (string-match org-from-is-user-regexp from)))
9422 (setq fmt (replace-match "to %t" t t fmt))
9423 (setq fmt (replace-match "from %f" t t fmt))))
9424 (org-replace-escapes fmt table)))
9426 (defun org-make-org-heading-search-string (&optional string)
9427 "Make search string for the current headline or STRING."
9428 (let ((s (or string
9429 (and (derived-mode-p 'org-mode)
9430 (save-excursion
9431 (org-back-to-heading t)
9432 (org-element-property :raw-value (org-element-at-point))))))
9433 (lines org-context-in-file-links))
9434 (unless string (setq s (concat "*" s))) ;Add * for headlines
9435 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9436 (when (and string (integerp lines) (> lines 0))
9437 (let ((slines (org-split-string s "\n")))
9438 (when (< lines (length slines))
9439 (setq s (mapconcat
9440 'identity
9441 (reverse (nthcdr (- (length slines) lines)
9442 (reverse slines))) "\n")))))
9443 (mapconcat #'identity (split-string s) " ")))
9445 (defconst org-link-escape-chars
9446 ;;%20 %5B %5D %25
9447 '(?\s ?\[ ?\] ?%)
9448 "List of characters that should be escaped in a link when stored to Org.
9449 This is the list that is used for internal purposes.")
9451 (defun org-make-link-string (link &optional description)
9452 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9453 (unless (org-string-nw-p link) (error "Empty link"))
9454 (let ((uri (cond ((string-match org-link-types-re link)
9455 (concat (match-string 1 link)
9456 (org-link-escape (substring link (match-end 1)))))
9457 ((or (file-name-absolute-p link)
9458 (string-match-p "\\`\\.\\.?/" link))
9459 (org-link-escape link))
9460 ;; For readability, do not encode space characters
9461 ;; in fuzzy links.
9462 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9463 (description
9464 (and (org-string-nw-p description)
9465 ;; Remove brackets from description, as they are fatal.
9466 (replace-regexp-in-string
9467 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9468 (org-trim description)))))
9469 (format "[[%s]%s]"
9471 (if description (format "[%s]" description) ""))))
9473 (defun org-link-escape (text &optional table merge)
9474 "Return percent escaped representation of TEXT.
9475 TEXT is a string with the text to escape.
9476 Optional argument TABLE is a list with characters that should be
9477 escaped. When nil, `org-link-escape-chars' is used.
9478 If optional argument MERGE is set, merge TABLE into
9479 `org-link-escape-chars'."
9480 (let ((characters-to-encode
9481 (cond ((null table) org-link-escape-chars)
9482 (merge (append org-link-escape-chars table))
9483 (t table))))
9484 (mapconcat
9485 (lambda (c)
9486 (if (or (memq c characters-to-encode)
9487 (and org-url-hexify-p (or (< c 32) (> c 126))))
9488 (mapconcat (lambda (e) (format "%%%.2X" e))
9489 (or (encode-coding-char c 'utf-8)
9490 (error "Unable to percent escape character: %c" c))
9492 (char-to-string c)))
9493 text "")))
9495 (defun org-link-unescape (str)
9496 "Unhex hexified Unicode parts in string STR.
9497 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9498 reciprocal of `org-link-escape', which see."
9499 (if (org-string-nw-p str)
9500 (replace-regexp-in-string
9501 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9502 str))
9504 (defun org-link-unescape-compound (hex)
9505 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9506 Note: this function also decodes single byte encodings like
9507 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9508 (save-match-data
9509 (let* ((bytes (cdr (split-string hex "%")))
9510 (ret "")
9511 (eat 0)
9512 (sum 0))
9513 (while bytes
9514 (let* ((val (string-to-number (pop bytes) 16))
9515 (shift-xor
9516 (if (= 0 eat)
9517 (cond
9518 ((>= val 252) (cons 6 252))
9519 ((>= val 248) (cons 5 248))
9520 ((>= val 240) (cons 4 240))
9521 ((>= val 224) (cons 3 224))
9522 ((>= val 192) (cons 2 192))
9523 (t (cons 0 0)))
9524 (cons 6 128))))
9525 (when (>= val 192) (setq eat (car shift-xor)))
9526 (setq val (logxor val (cdr shift-xor)))
9527 (setq sum (+ (lsh sum (car shift-xor)) val))
9528 (when (> eat 0) (setq eat (- eat 1)))
9529 (cond
9530 ((= 0 eat) ;multi byte
9531 (setq ret (concat ret (char-to-string sum)))
9532 (setq sum 0))
9533 ((not bytes) ; single byte(s)
9534 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9535 ret)))
9537 (defun org-link-unescape-single-byte-sequence (hex)
9538 "Unhexify hex-encoded single byte character sequences."
9539 (mapconcat (lambda (byte)
9540 (char-to-string (string-to-number byte 16)))
9541 (cdr (split-string hex "%")) ""))
9543 (defun org-fixup-message-id-for-http (s)
9544 "Replace special characters in a message id, so it can be used in an http query."
9545 (when (string-match "%" s)
9546 (setq s (mapconcat (lambda (c)
9547 (if (eq c ?%)
9548 "%25"
9549 (char-to-string c)))
9550 s "")))
9551 (while (string-match "<" s)
9552 (setq s (replace-match "%3C" t t s)))
9553 (while (string-match ">" s)
9554 (setq s (replace-match "%3E" t t s)))
9555 (while (string-match "@" s)
9556 (setq s (replace-match "%40" t t s)))
9559 (defun org-link-prettify (link)
9560 "Return a human-readable representation of LINK.
9561 The car of LINK must be a raw link.
9562 The cdr of LINK must be either a link description or nil."
9563 (let ((desc (or (cadr link) "<no description>")))
9564 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9565 "<" (car link) ">")))
9567 ;;;###autoload
9568 (defun org-insert-link-global ()
9569 "Insert a link like Org mode does.
9570 This command can be called in any mode to insert a link in Org syntax."
9571 (interactive)
9572 (org-load-modules-maybe)
9573 (org-run-like-in-org-mode 'org-insert-link))
9575 (defun org-insert-all-links (arg &optional pre post)
9576 "Insert all links in `org-stored-links'.
9577 When a universal prefix, do not delete the links from `org-stored-links'.
9578 When `ARG' is a number, insert the last N link(s).
9579 `PRE' and `POST' are optional arguments to define a string to
9580 prepend or to append."
9581 (interactive "P")
9582 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9583 (links (copy-sequence org-stored-links))
9584 (pr (or pre "- "))
9585 (po (or post "\n"))
9586 (cnt 1) l)
9587 (if (null org-stored-links)
9588 (message "No link to insert")
9589 (while (and (or (listp arg) (>= arg cnt))
9590 (setq l (if (listp arg)
9591 (pop links)
9592 (pop org-stored-links))))
9593 (setq cnt (1+ cnt))
9594 (insert pr)
9595 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9596 (insert po)))))
9598 (defun org-insert-last-stored-link (arg)
9599 "Insert the last link stored in `org-stored-links'."
9600 (interactive "p")
9601 (org-insert-all-links arg "" "\n"))
9603 (defun org-link-fontify-links-to-this-file ()
9604 "Fontify links to the current file in `org-stored-links'."
9605 (let ((f (buffer-file-name)) a b)
9606 (setq a (mapcar (lambda(l)
9607 (let ((ll (car l)))
9608 (when (and (string-match "^file:\\(.+\\)::" ll)
9609 (equal f (expand-file-name (match-string 1 ll))))
9610 ll)))
9611 org-stored-links))
9612 (when (featurep 'org-id)
9613 (setq b (mapcar (lambda(l)
9614 (let ((ll (car l)))
9615 (when (and (string-match "^id:\\(.+\\)$" ll)
9616 (equal f (expand-file-name
9617 (or (org-id-find-id-file
9618 (match-string 1 ll)) ""))))
9619 ll)))
9620 org-stored-links)))
9621 (mapcar (lambda(l)
9622 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9623 (delq nil (append a b)))))
9625 (defvar org--links-history nil)
9626 (defun org-insert-link (&optional complete-file link-location default-description)
9627 "Insert a link. At the prompt, enter the link.
9629 Completion can be used to insert any of the link protocol prefixes in use.
9631 The history can be used to select a link previously stored with
9632 `org-store-link'. When the empty string is entered (i.e. if you just
9633 press `RET' at the prompt), the link defaults to the most recently
9634 stored link. As `SPC' triggers completion in the minibuffer, you need to
9635 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9637 You will also be prompted for a description, and if one is given, it will
9638 be displayed in the buffer instead of the link.
9640 If there is already a link at point, this command will allow you to edit
9641 link and description parts.
9643 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9644 file name can be
9645 selected using completion. The path to the file will be relative to the
9646 current directory if the file is in the current directory or a subdirectory.
9647 Otherwise, the link will be the absolute path as completed in the minibuffer
9648 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9649 option `org-link-file-path-type'.
9651 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9652 absolute path even if the file is in
9653 the current directory or below.
9655 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9656 prefix negates `org-keep-stored-link-after-insertion'.
9658 If the LINK-LOCATION parameter is non-nil, this value will be used as
9659 the link location instead of reading one interactively.
9661 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9662 be used as the default description. Otherwise, if
9663 `org-make-link-description-function' is non-nil, this function
9664 will be called with the link target, and the result will be the
9665 default link description. When called non-interactivily, don't
9666 allow to edit the default description."
9667 (interactive "P")
9668 (let* ((wcf (current-window-configuration))
9669 (origbuf (current-buffer))
9670 (region (when (org-region-active-p)
9671 (buffer-substring (region-beginning) (region-end))))
9672 (remove (and region (list (region-beginning) (region-end))))
9673 (desc region)
9674 (link link-location)
9675 (abbrevs org-link-abbrev-alist-local)
9676 entry all-prefixes auto-desc)
9677 (cond
9678 (link-location) ; specified by arg, just use it.
9679 ((org-in-regexp org-bracket-link-regexp 1)
9680 ;; We do have a link at point, and we are going to edit it.
9681 (setq remove (list (match-beginning 0) (match-end 0)))
9682 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9683 (setq link (read-string "Link: "
9684 (org-link-unescape
9685 (match-string-no-properties 1)))))
9686 ((or (org-in-regexp org-angle-link-re)
9687 (org-in-regexp org-plain-link-re))
9688 ;; Convert to bracket link
9689 (setq remove (list (match-beginning 0) (match-end 0))
9690 link (read-string "Link: "
9691 (org-unbracket-string "<" ">" (match-string 0)))))
9692 ((member complete-file '((4) (16)))
9693 ;; Completing read for file names.
9694 (setq link (org-file-complete-link complete-file)))
9696 ;; Read link, with completion for stored links.
9697 (org-link-fontify-links-to-this-file)
9698 (org-switch-to-buffer-other-window "*Org Links*")
9699 (with-current-buffer "*Org Links*"
9700 (erase-buffer)
9701 (insert "Insert a link.
9702 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9703 (when org-stored-links
9704 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9705 (insert (mapconcat 'org-link-prettify
9706 (reverse org-stored-links) "\n")))
9707 (goto-char (point-min)))
9708 (let ((cw (selected-window)))
9709 (select-window (get-buffer-window "*Org Links*" 'visible))
9710 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9711 (unless (pos-visible-in-window-p (point-max))
9712 (org-fit-window-to-buffer))
9713 (and (window-live-p cw) (select-window cw)))
9714 (setq all-prefixes (append (mapcar 'car abbrevs)
9715 (mapcar 'car org-link-abbrev-alist)
9716 (org-link-types)))
9717 (unwind-protect
9718 ;; Fake a link history, containing the stored links.
9719 (let ((org--links-history
9720 (append (mapcar #'car org-stored-links)
9721 org-insert-link-history)))
9722 (setq link
9723 (org-completing-read
9724 "Link: "
9725 (append
9726 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9727 (mapcar #'car org-stored-links))
9728 nil nil nil
9729 'org--links-history
9730 (caar org-stored-links)))
9731 (unless (org-string-nw-p link) (user-error "No link selected"))
9732 (dolist (l org-stored-links)
9733 (when (equal link (cadr l))
9734 (setq link (car l))
9735 (setq auto-desc t)))
9736 (when (or (member link all-prefixes)
9737 (and (equal ":" (substring link -1))
9738 (member (substring link 0 -1) all-prefixes)
9739 (setq link (substring link 0 -1))))
9740 (setq link (with-current-buffer origbuf
9741 (org-link-try-special-completion link)))))
9742 (set-window-configuration wcf)
9743 (kill-buffer "*Org Links*"))
9744 (setq entry (assoc link org-stored-links))
9745 (or entry (push link org-insert-link-history))
9746 (setq desc (or desc (nth 1 entry)))))
9748 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9749 (not org-keep-stored-link-after-insertion))
9750 (setq org-stored-links (delq (assoc link org-stored-links)
9751 org-stored-links)))
9753 (when (and (string-match org-plain-link-re link)
9754 (not (string-match org-ts-regexp link)))
9755 ;; URL-like link, normalize the use of angular brackets.
9756 (setq link (org-unbracket-string "<" ">" link)))
9758 ;; Check if we are linking to the current file with a search
9759 ;; option If yes, simplify the link by using only the search
9760 ;; option.
9761 (when (and buffer-file-name
9762 (let ((case-fold-search nil))
9763 (string-match "\\`file:\\(.+?\\)::" link)))
9764 (let ((path (match-string-no-properties 1 link))
9765 (search (substring-no-properties link (match-end 0))))
9766 (save-match-data
9767 (when (equal (file-truename buffer-file-name) (file-truename path))
9768 ;; We are linking to this same file, with a search option
9769 (setq link search)))))
9771 ;; Check if we can/should use a relative path. If yes, simplify
9772 ;; the link.
9773 (let ((case-fold-search nil))
9774 (when (string-match "\\`\\(file\\|docview\\):" link)
9775 (let* ((type (match-string-no-properties 0 link))
9776 (path-start (match-end 0))
9777 (search (and (string-match "::\\(.*\\)\\'" link)
9778 (match-string 1 link)))
9779 (path
9780 (if search
9781 (substring-no-properties
9782 link path-start (match-beginning 0))
9783 (substring-no-properties link (match-end 0))))
9784 (origpath path))
9785 (cond
9786 ((or (eq org-link-file-path-type 'absolute)
9787 (equal complete-file '(16)))
9788 (setq path (abbreviate-file-name (expand-file-name path))))
9789 ((eq org-link-file-path-type 'noabbrev)
9790 (setq path (expand-file-name path)))
9791 ((eq org-link-file-path-type 'relative)
9792 (setq path (file-relative-name path)))
9794 (save-match-data
9795 (if (string-match (concat "^" (regexp-quote
9796 (expand-file-name
9797 (file-name-as-directory
9798 default-directory))))
9799 (expand-file-name path))
9800 ;; We are linking a file with relative path name.
9801 (setq path (substring (expand-file-name path)
9802 (match-end 0)))
9803 (setq path (abbreviate-file-name (expand-file-name path)))))))
9804 (setq link (concat type path (and search (concat "::" search))))
9805 (when (equal desc origpath)
9806 (setq desc path)))))
9808 (unless auto-desc
9809 (let ((initial-input
9810 (cond
9811 (default-description)
9812 ((not org-make-link-description-function) desc)
9813 (t (condition-case nil
9814 (funcall org-make-link-description-function link desc)
9815 (error
9816 (message "Can't get link description from `%s'"
9817 (symbol-name org-make-link-description-function))
9818 (sit-for 2)
9819 nil))))))
9820 (setq desc (if (called-interactively-p 'any)
9821 (read-string "Description: " initial-input)
9822 initial-input))))
9824 (unless (string-match "\\S-" desc) (setq desc nil))
9825 (when remove (apply 'delete-region remove))
9826 (insert (org-make-link-string link desc))
9827 ;; Redisplay so as the new link has proper invisible characters.
9828 (sit-for 0)))
9830 (defun org-link-try-special-completion (type)
9831 "If there is completion support for link type TYPE, offer it."
9832 (let ((fun (org-link-get-parameter type :complete)))
9833 (if (functionp fun)
9834 (funcall fun)
9835 (read-string "Link (no completion support): " (concat type ":")))))
9837 (defun org-file-complete-link (&optional arg)
9838 "Create a file link using completion."
9839 (let ((file (read-file-name "File: "))
9840 (pwd (file-name-as-directory (expand-file-name ".")))
9841 (pwd1 (file-name-as-directory (abbreviate-file-name
9842 (expand-file-name ".")))))
9843 (cond ((equal arg '(16))
9844 (concat "file:"
9845 (abbreviate-file-name (expand-file-name file))))
9846 ((string-match
9847 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9848 (concat "file:" (match-string 1 file)))
9849 ((string-match
9850 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9851 (expand-file-name file))
9852 (concat "file:"
9853 (match-string 1 (expand-file-name file))))
9854 (t (concat "file:" file)))))
9857 ;;; Opening/following a link
9859 (defvar org-link-search-failed nil)
9861 (defvar org-open-link-functions nil
9862 "Hook for functions finding a plain text link.
9863 These functions must take a single argument, the link content.
9864 They will be called for links that look like [[link text][description]]
9865 when LINK TEXT does not have a protocol like \"http:\" and does not look
9866 like a filename (e.g. \"./blue.png\").
9868 These functions will be called *before* Org attempts to resolve the
9869 link by doing text searches in the current buffer - so if you want a
9870 link \"[[target]]\" to still find \"<<target>>\", your function should
9871 handle this as a special case.
9873 When the function does handle the link, it must return a non-nil value.
9874 If it decides that it is not responsible for this link, it must return
9875 nil to indicate that that Org can continue with other options like
9876 exact and fuzzy text search.")
9878 (defun org-next-link (&optional search-backward)
9879 "Move forward to the next link.
9880 If the link is in hidden text, expose it."
9881 (interactive "P")
9882 (when (and org-link-search-failed (eq this-command last-command))
9883 (goto-char (point-min))
9884 (message "Link search wrapped back to beginning of buffer"))
9885 (setq org-link-search-failed nil)
9886 (let* ((pos (point))
9887 (ct (org-context))
9888 (a (assq :link ct))
9889 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9890 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9891 ((looking-at org-any-link-re)
9892 ;; Don't stay stuck at link without an org-link face
9893 (forward-char (if search-backward -1 1))))
9894 (if (funcall srch-fun org-any-link-re nil t)
9895 (progn
9896 (goto-char (match-beginning 0))
9897 (when (org-invisible-p) (org-show-context)))
9898 (goto-char pos)
9899 (setq org-link-search-failed t)
9900 (message "No further link found"))))
9902 (defun org-previous-link ()
9903 "Move backward to the previous link.
9904 If the link is in hidden text, expose it."
9905 (interactive)
9906 (funcall 'org-next-link t))
9908 (defun org-translate-link (s)
9909 "Translate a link string if a translation function has been defined."
9910 (with-temp-buffer
9911 (insert (org-trim s))
9912 (org-trim (org-element-interpret-data (org-element-context)))))
9914 (defun org-translate-link-from-planner (type path)
9915 "Translate a link from Emacs Planner syntax so that Org can follow it.
9916 This is still an experimental function, your mileage may vary."
9917 (cond
9918 ((member type '("http" "https" "news" "ftp"))
9919 ;; standard Internet links are the same.
9920 nil)
9921 ((and (equal type "irc") (string-match "^//" path))
9922 ;; Planner has two / at the beginning of an irc link, we have 1.
9923 ;; We should have zero, actually....
9924 (setq path (substring path 1)))
9925 ((and (equal type "lisp") (string-match "^/" path))
9926 ;; Planner has a slash, we do not.
9927 (setq type "elisp" path (substring path 1)))
9928 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9929 ;; A typical message link. Planner has the id after the final slash,
9930 ;; we separate it with a hash mark
9931 (setq path (concat (match-string 1 path) "#"
9932 (org-unbracket-string "<" ">" (match-string 2 path))))))
9933 (cons type path))
9935 (defun org-find-file-at-mouse (ev)
9936 "Open file link or URL at mouse."
9937 (interactive "e")
9938 (mouse-set-point ev)
9939 (org-open-at-point 'in-emacs))
9941 (defun org-open-at-mouse (ev)
9942 "Open file link or URL at mouse.
9943 See the docstring of `org-open-file' for details."
9944 (interactive "e")
9945 (mouse-set-point ev)
9946 (when (eq major-mode 'org-agenda-mode)
9947 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9948 (org-open-at-point))
9950 (defvar org-window-config-before-follow-link nil
9951 "The window configuration before following a link.
9952 This is saved in case the need arises to restore it.")
9954 ;;;###autoload
9955 (defun org-open-at-point-global ()
9956 "Follow a link or time-stamp like Org mode does.
9957 This command can be called in any mode to follow an external link
9958 or a time-stamp that has Org mode syntax. Its behavior is
9959 undefined when called on internal links (e.g., fuzzy links).
9960 Raise an error when there is nothing to follow. "
9961 (interactive)
9962 (cond ((org-in-regexp org-any-link-re)
9963 (org-open-link-from-string (match-string-no-properties 0)))
9964 ((or (org-in-regexp org-ts-regexp-both nil t)
9965 (org-in-regexp org-tsr-regexp-both nil t))
9966 (org-follow-timestamp-link))
9967 (t (user-error "No link found"))))
9969 ;;;###autoload
9970 (defun org-open-link-from-string (s &optional arg reference-buffer)
9971 "Open a link in the string S, as if it was in Org mode."
9972 (interactive "sLink: \nP")
9973 (let ((reference-buffer (or reference-buffer (current-buffer))))
9974 (with-temp-buffer
9975 (let ((org-inhibit-startup (not reference-buffer)))
9976 (org-mode)
9977 (insert s)
9978 (goto-char (point-min))
9979 (when reference-buffer
9980 (setq org-link-abbrev-alist-local
9981 (with-current-buffer reference-buffer
9982 org-link-abbrev-alist-local)))
9983 (org-open-at-point arg reference-buffer)))))
9985 (defvar org-open-at-point-functions nil
9986 "Hook that is run when following a link at point.
9988 Functions in this hook must return t if they identify and follow
9989 a link at point. If they don't find anything interesting at point,
9990 they must return nil.")
9992 (defvar org-link-search-inhibit-query nil)
9993 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9994 (defun org--open-doi-link (path)
9995 "Open a \"doi\" type link.
9996 PATH is a the path to search for, as a string."
9997 (browse-url (url-encode-url (concat org-doi-server-url path))))
9999 (defun org--open-elisp-link (path)
10000 "Open a \"elisp\" type link.
10001 PATH is the sexp to evaluate, as a string."
10002 (let ((cmd path))
10003 (if (or (and (org-string-nw-p
10004 org-confirm-elisp-link-not-regexp)
10005 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10006 (not org-confirm-elisp-link-function)
10007 (funcall org-confirm-elisp-link-function
10008 (format "Execute \"%s\" as elisp? "
10009 (org-add-props cmd nil 'face 'org-warning))))
10010 (message "%s => %s" cmd
10011 (if (eq (string-to-char cmd) ?\()
10012 (eval (read cmd))
10013 (call-interactively (read cmd))))
10014 (user-error "Abort"))))
10016 (defun org--open-help-link (path)
10017 "Open a \"help\" type link.
10018 PATH is a symbol name, as a string."
10019 (pcase (intern path)
10020 ((and (pred fboundp) variable) (describe-function variable))
10021 ((and (pred boundp) function) (describe-variable function))
10022 (name (user-error "Unknown function or variable: %s" name))))
10024 (defun org--open-shell-link (path)
10025 "Open a \"shell\" type link.
10026 PATH is the command to execute, as a string."
10027 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10028 (cmd path))
10029 (if (or (and (org-string-nw-p
10030 org-confirm-shell-link-not-regexp)
10031 (string-match
10032 org-confirm-shell-link-not-regexp cmd))
10033 (not org-confirm-shell-link-function)
10034 (funcall org-confirm-shell-link-function
10035 (format "Execute \"%s\" in shell? "
10036 (org-add-props cmd nil
10037 'face 'org-warning))))
10038 (progn
10039 (message "Executing %s" cmd)
10040 (shell-command cmd buf)
10041 (when (featurep 'midnight)
10042 (setq clean-buffer-list-kill-buffer-names
10043 (cons (buffer-name buf)
10044 clean-buffer-list-kill-buffer-names))))
10045 (user-error "Abort"))))
10047 (defun org-open-at-point (&optional arg reference-buffer)
10048 "Open link, timestamp, footnote or tags at point.
10050 When point is on a link, follow it. Normally, files will be
10051 opened by an appropriate application. If the optional prefix
10052 argument ARG is non-nil, Emacs will visit the file. With
10053 a double prefix argument, try to open outside of Emacs, in the
10054 application the system uses for this file type.
10056 When point is on a timestamp, open the agenda at the day
10057 specified.
10059 When point is a footnote definition, move to the first reference
10060 found. If it is on a reference, move to the associated
10061 definition.
10063 When point is on a headline, display a list of every link in the
10064 entry, so it is possible to pick one, or all, of them. If point
10065 is on a tag, call `org-tags-view' instead.
10067 When optional argument REFERENCE-BUFFER is non-nil, it should
10068 specify a buffer from where the link search should happen. This
10069 is used internally by `org-open-link-from-string'.
10071 On top of syntactically correct links, this function will also
10072 try to open links and time-stamps in comments, example
10073 blocks... i.e., whenever point is on something looking like
10074 a timestamp or a link."
10075 (interactive "P")
10076 ;; On a code block, open block's results.
10077 (unless (call-interactively 'org-babel-open-src-block-result)
10078 (org-load-modules-maybe)
10079 (setq org-window-config-before-follow-link (current-window-configuration))
10080 (org-remove-occur-highlights nil nil t)
10081 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10082 (let* ((context
10083 ;; Only consider supported types, even if they are not
10084 ;; the closest one.
10085 (org-element-lineage
10086 (org-element-context)
10087 '(clock footnote-definition footnote-reference headline
10088 inlinetask link timestamp)
10090 (type (org-element-type context))
10091 (value (org-element-property :value context)))
10092 (cond
10093 ;; On a headline or an inlinetask, but not on a timestamp,
10094 ;; a link, a footnote reference.
10095 ((memq type '(headline inlinetask))
10096 (org-match-line org-complex-heading-regexp)
10097 (if (and (match-beginning 5)
10098 (>= (point) (match-beginning 5))
10099 (< (point) (match-end 5)))
10100 ;; On tags.
10101 (org-tags-view arg (substring (match-string 5) 0 -1))
10102 ;; Not on tags.
10103 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10104 (`(nil . ,_)
10105 (require 'org-attach)
10106 (org-attach-reveal 'if-exists))
10107 (`(,links . ,links-end)
10108 (dolist (link (if (stringp links) (list links) links))
10109 (search-forward link nil links-end)
10110 (goto-char (match-beginning 0))
10111 (org-open-at-point))))))
10112 ;; On a footnote reference or at definition's label.
10113 ((or (eq type 'footnote-reference)
10114 (and (eq type 'footnote-definition)
10115 (save-excursion
10116 ;; Do not validate action when point is on the
10117 ;; spaces right after the footnote label, in
10118 ;; order to be on par with behaviour on links.
10119 (skip-chars-forward " \t")
10120 (let ((begin
10121 (org-element-property :contents-begin context)))
10122 (if begin (< (point) begin)
10123 (= (org-element-property :post-affiliated context)
10124 (line-beginning-position)))))))
10125 (org-footnote-action))
10126 ;; No valid context. Ignore catch-all types like `headline'.
10127 ;; If point is on something looking like a link or
10128 ;; a time-stamp, try opening it. It may be useful in
10129 ;; comments, example blocks...
10130 ((memq type '(footnote-definition headline inlinetask nil))
10131 (call-interactively #'org-open-at-point-global))
10132 ;; On a clock line, make sure point is on the timestamp
10133 ;; before opening it.
10134 ((and (eq type 'clock)
10135 value
10136 (>= (point) (org-element-property :begin value))
10137 (<= (point) (org-element-property :end value)))
10138 (org-follow-timestamp-link))
10139 ;; Do nothing on white spaces after an object.
10140 ((>= (point)
10141 (save-excursion
10142 (goto-char (org-element-property :end context))
10143 (skip-chars-backward " \t")
10144 (point)))
10145 (user-error "No link found"))
10146 ((eq type 'timestamp) (org-follow-timestamp-link))
10147 ((eq type 'link)
10148 (let ((type (org-element-property :type context))
10149 (path (org-link-unescape (org-element-property :path context))))
10150 ;; Switch back to REFERENCE-BUFFER needed when called in
10151 ;; a temporary buffer through `org-open-link-from-string'.
10152 (with-current-buffer (or reference-buffer (current-buffer))
10153 (cond
10154 ((equal type "file")
10155 (if (string-match "[*?{]" (file-name-nondirectory path))
10156 (dired path)
10157 ;; Look into `org-link-parameters' in order to find
10158 ;; a DEDICATED-FUNCTION to open file. The function
10159 ;; will be applied on raw link instead of parsed
10160 ;; link due to the limitation in `org-add-link-type'
10161 ;; ("open" function called with a single argument).
10162 ;; If no such function is found, fallback to
10163 ;; `org-open-file'.
10164 (let* ((option (org-element-property :search-option context))
10165 (app (org-element-property :application context))
10166 (dedicated-function
10167 (org-link-get-parameter
10168 (if app (concat type "+" app) type)
10169 :follow)))
10170 (if dedicated-function
10171 (funcall dedicated-function
10172 (concat path
10173 (and option (concat "::" option))))
10174 (apply #'org-open-file
10175 path
10176 (cond (arg)
10177 ((equal app "emacs") 'emacs)
10178 ((equal app "sys") 'system))
10179 (cond ((not option) nil)
10180 ((string-match-p "\\`[0-9]+\\'" option)
10181 (list (string-to-number option)))
10182 (t (list nil
10183 (org-link-unescape option)))))))))
10184 ((functionp (org-link-get-parameter type :follow))
10185 (funcall (org-link-get-parameter type :follow) path))
10186 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10187 (unless (run-hook-with-args-until-success
10188 'org-open-link-functions path)
10189 (if (not arg) (org-mark-ring-push)
10190 (switch-to-buffer-other-window
10191 (org-get-buffer-for-internal-link (current-buffer))))
10192 (let ((destination
10193 (org-with-wide-buffer
10194 (if (equal type "radio")
10195 (org-search-radio-target
10196 (org-element-property :path context))
10197 (org-link-search
10198 (if (member type '("custom-id" "coderef"))
10199 (org-element-property :raw-link context)
10200 path)
10201 ;; Prevent fuzzy links from matching
10202 ;; themselves.
10203 (and (equal type "fuzzy")
10204 (+ 2 (org-element-property :begin context)))))
10205 (point))))
10206 (unless (and (<= (point-min) destination)
10207 (>= (point-max) destination))
10208 (widen))
10209 (goto-char destination))))
10210 (t (browse-url-at-point))))))
10211 (t (user-error "No link found")))))
10212 (run-hook-with-args 'org-follow-link-hook)))
10214 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10215 "Offer links in the current entry and return the selected link.
10216 If there is only one link, return it.
10217 If NTH is an integer, return the NTH link found.
10218 If ZERO is a string, check also this string for a link, and if
10219 there is one, return it."
10220 (with-current-buffer buffer
10221 (org-with-wide-buffer
10222 (goto-char marker)
10223 (let ((cnt ?0)
10224 have-zero end links link c)
10225 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10226 (push (match-string 0 zero) links)
10227 (setq cnt (1- cnt) have-zero t))
10228 (save-excursion
10229 (org-back-to-heading t)
10230 (setq end (save-excursion (outline-next-heading) (point)))
10231 (while (re-search-forward org-any-link-re end t)
10232 (push (match-string 0) links))
10233 (setq links (org-uniquify (reverse links))))
10234 (cond
10235 ((null links)
10236 (message "No links"))
10237 ((equal (length links) 1)
10238 (setq link (car links)))
10239 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10240 (setq link (nth (if have-zero nth (1- nth)) links)))
10241 (t ; we have to select a link
10242 (save-excursion
10243 (save-window-excursion
10244 (delete-other-windows)
10245 (with-output-to-temp-buffer "*Select Link*"
10246 (dolist (l links)
10247 (cond
10248 ((not (string-match org-bracket-link-regexp l))
10249 (princ (format "[%c] %s\n" (cl-incf cnt)
10250 (org-unbracket-string "<" ">" l))))
10251 ((match-end 3)
10252 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10253 (match-string 3 l) (match-string 1 l))))
10254 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10255 (match-string 1 l)))))))
10256 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10257 (message "Select link to open, RET to open all:")
10258 (setq c (read-char-exclusive))
10259 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10260 (when (equal c ?q) (user-error "Abort"))
10261 (if (equal c ?\C-m)
10262 (setq link links)
10263 (setq nth (- c ?0))
10264 (when have-zero (setq nth (1+ nth)))
10265 (unless (and (integerp nth) (>= (length links) nth))
10266 (user-error "Invalid link selection"))
10267 (setq link (nth (1- nth) links)))))
10268 (cons link end)))))
10270 ;; TODO: These functions are deprecated since `org-open-at-point'
10271 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10272 (defun org-open-file-with-system (path)
10273 "Open file at PATH using the system way of opening it."
10274 (org-open-file path 'system))
10275 (defun org-open-file-with-emacs (path)
10276 "Open file at PATH in Emacs."
10277 (org-open-file path 'emacs))
10280 ;;; File search
10282 (defvar org-create-file-search-functions nil
10283 "List of functions to construct the right search string for a file link.
10284 These functions are called in turn with point at the location to
10285 which the link should point.
10287 A function in the hook should first test if it would like to
10288 handle this file type, for example by checking the `major-mode'
10289 or the file extension. If it decides not to handle this file, it
10290 should just return nil to give other functions a chance. If it
10291 does handle the file, it must return the search string to be used
10292 when following the link. The search string will be part of the
10293 file link, given after a double colon, and `org-open-at-point'
10294 will automatically search for it. If special measures must be
10295 taken to make the search successful, another function should be
10296 added to the companion hook `org-execute-file-search-functions',
10297 which see.
10299 A function in this hook may also use `setq' to set the variable
10300 `description' to provide a suggestion for the descriptive text to
10301 be used for this link when it gets inserted into an Org buffer
10302 with \\[org-insert-link].")
10304 (defvar org-execute-file-search-functions nil
10305 "List of functions to execute a file search triggered by a link.
10307 Functions added to this hook must accept a single argument, the
10308 search string that was part of the file link, the part after the
10309 double colon. The function must first check if it would like to
10310 handle this search, for example by checking the `major-mode' or
10311 the file extension. If it decides not to handle this search, it
10312 should just return nil to give other functions a chance. If it
10313 does handle the search, it must return a non-nil value to keep
10314 other functions from trying.
10316 Each function can access the current prefix argument through the
10317 variable `current-prefix-arg'. Note that a single prefix is used
10318 to force opening a link in Emacs, so it may be good to only use a
10319 numeric or double prefix to guide the search function.
10321 In case this is needed, a function in this hook can also restore
10322 the window configuration before `org-open-at-point' was called using:
10324 (set-window-configuration org-window-config-before-follow-link)")
10326 (defun org-search-radio-target (target)
10327 "Search a radio target matching TARGET in current buffer.
10328 White spaces are not significant."
10329 (let ((re (format "<<<%s>>>"
10330 (mapconcat #'regexp-quote
10331 (split-string target)
10332 "[ \t]+\\(?:\n[ \t]*\\)?")))
10333 (origin (point)))
10334 (goto-char (point-min))
10335 (catch :radio-match
10336 (while (re-search-forward re nil t)
10337 (backward-char)
10338 (let ((object (org-element-context)))
10339 (when (eq (org-element-type object) 'radio-target)
10340 (goto-char (org-element-property :begin object))
10341 (org-show-context 'link-search)
10342 (throw :radio-match nil))))
10343 (goto-char origin)
10344 (user-error "No match for radio target: %s" target))))
10346 (defun org-link-search (s &optional avoid-pos stealth)
10347 "Search for a search string S.
10349 If S starts with \"#\", it triggers a custom ID search.
10351 If S is enclosed within parenthesis, it initiates a coderef
10352 search.
10354 If S is surrounded by forward slashes, it is interpreted as
10355 a regular expression. In Org mode files, this will create an
10356 `org-occur' sparse tree. In ordinary files, `occur' will be used
10357 to list matches. If the current buffer is in `dired-mode', grep
10358 will be used to search in all files.
10360 When AVOID-POS is given, ignore matches near that position.
10362 When optional argument STEALTH is non-nil, do not modify
10363 visibility around point, thus ignoring `org-show-context-detail'
10364 variable.
10366 Search is case-insensitive and ignores white spaces. Return type
10367 of matched result, which is either `dedicated' or `fuzzy'."
10368 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10369 (let* ((case-fold-search t)
10370 (origin (point))
10371 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10372 (starred (eq (string-to-char normalized) ?*))
10373 (words (split-string (if starred (substring s 1) s)))
10374 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10375 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10376 type)
10377 (cond
10378 ;; Check if there are any special search functions.
10379 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10380 ((eq (string-to-char s) ?#)
10381 ;; Look for a custom ID S if S starts with "#".
10382 (let* ((id (substring normalized 1))
10383 (match (org-find-property "CUSTOM_ID" id)))
10384 (if match (progn (goto-char match) (setf type 'dedicated))
10385 (error "No match for custom ID: %s" id))))
10386 ((string-match "\\`(\\(.*\\))\\'" normalized)
10387 ;; Look for coderef targets if S is enclosed within parenthesis.
10388 (let ((coderef (match-string-no-properties 1 normalized))
10389 (re (substring s-single-re 1 -1)))
10390 (goto-char (point-min))
10391 (catch :coderef-match
10392 (while (re-search-forward re nil t)
10393 (let ((element (org-element-at-point)))
10394 (when (and (memq (org-element-type element)
10395 '(example-block src-block))
10396 ;; Build proper regexp according to current
10397 ;; block's label format.
10398 (let ((label-fmt
10399 (regexp-quote
10400 (or (org-element-property :label-fmt element)
10401 org-coderef-label-format))))
10402 (save-excursion
10403 (beginning-of-line)
10404 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10405 (format label-fmt coderef))))))
10406 (setq type 'dedicated)
10407 (goto-char (match-beginning 1))
10408 (throw :coderef-match nil))))
10409 (goto-char origin)
10410 (error "No match for coderef: %s" coderef))))
10411 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10412 ;; Look for a regular expression.
10413 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10414 (match-string 1 s)))
10415 ;; From here, we handle fuzzy links.
10417 ;; Look for targets, only if not in a headline search.
10418 ((and (not starred)
10419 (let ((target (format "<<%s>>" s-multi-re)))
10420 (catch :target-match
10421 (goto-char (point-min))
10422 (while (re-search-forward target nil t)
10423 (backward-char)
10424 (let ((context (org-element-context)))
10425 (when (eq (org-element-type context) 'target)
10426 (setq type 'dedicated)
10427 (goto-char (org-element-property :begin context))
10428 (throw :target-match t))))
10429 nil))))
10430 ;; Look for elements named after S, only if not in a headline
10431 ;; search.
10432 ((and (not starred)
10433 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10434 (catch :name-match
10435 (goto-char (point-min))
10436 (while (re-search-forward name nil t)
10437 (let ((element (org-element-at-point)))
10438 (when (equal words
10439 (split-string
10440 (org-element-property :name element)))
10441 (setq type 'dedicated)
10442 (beginning-of-line)
10443 (throw :name-match t))))
10444 nil))))
10445 ;; Regular text search. Prefer headlines in Org mode buffers.
10446 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10447 ;; statistics cookies and tags.
10448 ((and (derived-mode-p 'org-mode)
10449 (let ((title-re
10450 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10451 org-outline-regexp-bol
10452 org-comment-string
10453 (mapconcat #'regexp-quote words ".+")))
10454 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10455 (comment-re (eval-when-compile
10456 (format "\\`%s[ \t]+" org-comment-string))))
10457 (goto-char (point-min))
10458 (catch :found
10459 (while (re-search-forward title-re nil t)
10460 (when (equal words
10461 (split-string
10462 (replace-regexp-in-string
10463 cookie-re ""
10464 (replace-regexp-in-string
10465 comment-re "" (org-get-heading t t t)))))
10466 (throw :found t)))
10467 nil)))
10468 (beginning-of-line)
10469 (setq type 'dedicated))
10470 ;; Offer to create non-existent headline depending on
10471 ;; `org-link-search-must-match-exact-headline'.
10472 ((and (derived-mode-p 'org-mode)
10473 (not org-link-search-inhibit-query)
10474 (eq org-link-search-must-match-exact-headline 'query-to-create)
10475 (yes-or-no-p "No match - create this as a new heading? "))
10476 (goto-char (point-max))
10477 (unless (bolp) (newline))
10478 (org-insert-heading nil t t)
10479 (insert s "\n")
10480 (beginning-of-line 0))
10481 ;; Only headlines are looked after. No need to process
10482 ;; further: throw an error.
10483 ((and (derived-mode-p 'org-mode)
10484 (or starred org-link-search-must-match-exact-headline))
10485 (goto-char origin)
10486 (error "No match for fuzzy expression: %s" normalized))
10487 ;; Regular text search.
10488 ((catch :fuzzy-match
10489 (goto-char (point-min))
10490 (while (re-search-forward s-multi-re nil t)
10491 ;; Skip match if it contains AVOID-POS or it is included in
10492 ;; a link with a description but outside the description.
10493 (unless (or (and avoid-pos
10494 (<= (match-beginning 0) avoid-pos)
10495 (> (match-end 0) avoid-pos))
10496 (and (save-match-data
10497 (org-in-regexp org-bracket-link-regexp))
10498 (match-beginning 3)
10499 (or (> (match-beginning 3) (point))
10500 (<= (match-end 3) (point)))
10501 (org-element-lineage
10502 (save-match-data (org-element-context))
10503 '(link) t)))
10504 (goto-char (match-beginning 0))
10505 (setq type 'fuzzy)
10506 (throw :fuzzy-match t)))
10507 nil))
10508 ;; All failed. Throw an error.
10509 (t (goto-char origin)
10510 (error "No match for fuzzy expression: %s" normalized)))
10511 ;; Disclose surroundings of match, if appropriate.
10512 (when (and (derived-mode-p 'org-mode) (not stealth))
10513 (org-show-context 'link-search))
10514 type))
10516 (defun org-get-buffer-for-internal-link (buffer)
10517 "Return a buffer to be used for displaying the link target of internal links."
10518 (cond
10519 ((not org-display-internal-link-with-indirect-buffer)
10520 buffer)
10521 ((string-suffix-p "(Clone)" (buffer-name buffer))
10522 (message "Buffer is already a clone, not making another one")
10523 ;; we also do not modify visibility in this case
10524 buffer)
10525 (t ; make a new indirect buffer for displaying the link
10526 (let* ((bn (buffer-name buffer))
10527 (ibn (concat bn "(Clone)"))
10528 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10529 (with-current-buffer ib (org-overview))
10530 ib))))
10532 (defun org-do-occur (regexp &optional cleanup)
10533 "Call the Emacs command `occur'.
10534 If CLEANUP is non-nil, remove the printout of the regular expression
10535 in the *Occur* buffer. This is useful if the regex is long and not useful
10536 to read."
10537 (occur regexp)
10538 (when cleanup
10539 (let ((cwin (selected-window)) win beg end)
10540 (when (setq win (get-buffer-window "*Occur*"))
10541 (select-window win))
10542 (goto-char (point-min))
10543 (when (re-search-forward "match[a-z]+" nil t)
10544 (setq beg (match-end 0))
10545 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10546 (setq end (1- (match-beginning 0)))))
10547 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10548 (goto-char (point-min))
10549 (select-window cwin))))
10551 ;;; The mark ring for links jumps
10553 (defvar org-mark-ring nil
10554 "Mark ring for positions before jumps in Org mode.")
10555 (defvar org-mark-ring-last-goto nil
10556 "Last position in the mark ring used to go back.")
10557 ;; Fill and close the ring
10558 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10559 (dotimes (_ org-mark-ring-length)
10560 (push (make-marker) org-mark-ring))
10561 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10562 org-mark-ring)
10564 (defun org-mark-ring-push (&optional pos buffer)
10565 "Put the current position or POS into the mark ring and rotate it."
10566 (interactive)
10567 (setq pos (or pos (point)))
10568 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10569 (move-marker (car org-mark-ring)
10570 (or pos (point))
10571 (or buffer (current-buffer)))
10572 (message "%s"
10573 (substitute-command-keys
10574 "Position saved to mark ring, go back with \
10575 `\\[org-mark-ring-goto]'.")))
10577 (defun org-mark-ring-goto (&optional n)
10578 "Jump to the previous position in the mark ring.
10579 With prefix arg N, jump back that many stored positions. When
10580 called several times in succession, walk through the entire ring.
10581 Org mode commands jumping to a different position in the current file,
10582 or to another Org file, automatically push the old position onto the ring."
10583 (interactive "p")
10584 (let (p m)
10585 (if (eq last-command this-command)
10586 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10587 (setq p org-mark-ring))
10588 (setq org-mark-ring-last-goto p)
10589 (setq m (car p))
10590 (pop-to-buffer-same-window (marker-buffer m))
10591 (goto-char m)
10592 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10594 (defun org-add-angle-brackets (s)
10595 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10596 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10599 ;;; Following specific links
10601 (defvar org-agenda-buffer-tmp-name)
10602 (defvar org-agenda-start-on-weekday)
10603 (defun org-follow-timestamp-link ()
10604 "Open an agenda view for the time-stamp date/range at point."
10605 (cond
10606 ((org-at-date-range-p t)
10607 (let ((org-agenda-start-on-weekday)
10608 (t1 (match-string 1))
10609 (t2 (match-string 2)) tt1 tt2)
10610 (setq tt1 (time-to-days (org-time-string-to-time t1))
10611 tt2 (time-to-days (org-time-string-to-time t2)))
10612 (let ((org-agenda-buffer-tmp-name
10613 (format "*Org Agenda(a:%s)"
10614 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10615 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10616 ((org-at-timestamp-p 'lax)
10617 (let ((org-agenda-buffer-tmp-name
10618 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10619 (org-agenda-list nil (time-to-days (org-time-string-to-time
10620 (substring (match-string 1) 0 10)))
10621 1)))
10622 (t (error "This should not happen"))))
10625 ;;; Following file links
10626 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10627 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10628 (declare-function mailcap-mime-info
10629 "mailcap" (string &optional request no-decode))
10630 (defvar org-wait nil)
10631 (defun org-open-file (path &optional in-emacs line search)
10632 "Open the file at PATH.
10633 First, this expands any special file name abbreviations. Then the
10634 configuration variable `org-file-apps' is checked if it contains an
10635 entry for this file type, and if yes, the corresponding command is launched.
10637 If no application is found, Emacs simply visits the file.
10639 With optional prefix argument IN-EMACS, Emacs will visit the file.
10640 With a double \\[universal-argument] \\[universal-argument] \
10641 prefix arg, Org tries to avoid opening in Emacs
10642 and to use an external application to visit the file.
10644 Optional LINE specifies a line to go to, optional SEARCH a string
10645 to search for. If LINE or SEARCH is given, the file will be
10646 opened in Emacs, unless an entry from org-file-apps that makes
10647 use of groups in a regexp matches.
10649 If you want to change the way frames are used when following a
10650 link, please customize `org-link-frame-setup'.
10652 If the file does not exist, an error is thrown."
10653 (let* ((file (if (equal path "")
10654 buffer-file-name
10655 (substitute-in-file-name (expand-file-name path))))
10656 (file-apps (append org-file-apps (org-default-apps)))
10657 (apps (cl-remove-if
10658 'org-file-apps-entry-match-against-dlink-p file-apps))
10659 (apps-dlink (cl-remove-if-not
10660 'org-file-apps-entry-match-against-dlink-p file-apps))
10661 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10662 (dirp (unless remp (file-directory-p file)))
10663 (file (if (and dirp org-open-directory-means-index-dot-org)
10664 (concat (file-name-as-directory file) "index.org")
10665 file))
10666 (a-m-a-p (assq 'auto-mode apps))
10667 (dfile (downcase file))
10668 ;; Reconstruct the original link from the PATH, LINE and
10669 ;; SEARCH args.
10670 (link (cond (line (concat file "::" (number-to-string line)))
10671 (search (concat file "::" search))
10672 (t file)))
10673 (dlink (downcase link))
10674 (ext
10675 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10676 (match-string 1 dfile)))
10677 (save-position-maybe
10678 (let ((old-buffer (current-buffer))
10679 (old-pos (point))
10680 (old-mode major-mode))
10681 (lambda ()
10682 (and (derived-mode-p 'org-mode)
10683 (eq old-mode 'org-mode)
10684 (or (not (eq old-buffer (current-buffer)))
10685 (not (eq old-pos (point))))
10686 (org-mark-ring-push old-pos old-buffer)))))
10687 cmd link-match-data)
10688 (cond
10689 ((member in-emacs '((16) system))
10690 (setq cmd (cdr (assq 'system apps))))
10691 (in-emacs (setq cmd 'emacs))
10693 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10694 (and dirp (cdr (assq 'directory apps)))
10695 ;; First, try matching against apps-dlink if we
10696 ;; get a match here, store the match data for
10697 ;; later.
10698 (let ((match (assoc-default dlink apps-dlink
10699 'string-match)))
10700 (if match
10701 (progn (setq link-match-data (match-data))
10702 match)
10703 (progn (setq in-emacs (or in-emacs line search))
10704 nil))) ; if we have no match in apps-dlink,
10705 ; always open the file in emacs if line or search
10706 ; is given (for backwards compatibility)
10707 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10708 'string-match)
10709 (cdr (assoc ext apps))
10710 (cdr (assq t apps))))))
10711 (when (eq cmd 'system)
10712 (setq cmd (cdr (assq 'system apps))))
10713 (when (eq cmd 'default)
10714 (setq cmd (cdr (assoc t apps))))
10715 (when (eq cmd 'mailcap)
10716 (require 'mailcap)
10717 (mailcap-parse-mailcaps)
10718 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10719 (command (mailcap-mime-info mime-type)))
10720 (if (stringp command)
10721 (setq cmd command)
10722 (setq cmd 'emacs))))
10723 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10724 (not (file-exists-p file))
10725 (not org-open-non-existing-files))
10726 (user-error "No such file: %s" file))
10727 (cond
10728 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10729 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10730 (while (string-match "['\"]%s['\"]" cmd)
10731 (setq cmd (replace-match "%s" t t cmd)))
10732 (setq cmd (replace-regexp-in-string
10733 "%s"
10734 (shell-quote-argument (convert-standard-filename file))
10736 nil t))
10738 ;; Replace "%1", "%2" etc. in command with group matches from regex
10739 (save-match-data
10740 (let ((match-index 1)
10741 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10742 (set-match-data link-match-data)
10743 (while (<= match-index number-of-groups)
10744 (let ((regex (concat "%" (number-to-string match-index)))
10745 (replace-with (match-string match-index dlink)))
10746 (while (string-match regex cmd)
10747 (setq cmd (replace-match replace-with t t cmd))))
10748 (setq match-index (+ match-index 1)))))
10750 (save-window-excursion
10751 (message "Running %s...done" cmd)
10752 (start-process-shell-command cmd nil cmd)
10753 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10754 ((or (stringp cmd)
10755 (eq cmd 'emacs))
10756 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10757 (widen)
10758 (cond (line (org-goto-line line)
10759 (when (derived-mode-p 'org-mode) (org-reveal)))
10760 (search (condition-case err
10761 (org-link-search search)
10762 ;; Save position before error-ing out so user
10763 ;; can easily move back to the original buffer.
10764 (error (funcall save-position-maybe)
10765 (error (nth 1 err)))))))
10766 ((functionp cmd)
10767 (save-match-data
10768 (set-match-data link-match-data)
10769 (condition-case nil
10770 (funcall cmd file link)
10771 ;; FIXME: Remove this check when most default installations
10772 ;; of Emacs have at least Org 9.0.
10773 ((debug wrong-number-of-arguments wrong-type-argument
10774 invalid-function)
10775 (user-error "Please see Org News for version 9.0 about \
10776 `org-file-apps'--Lisp error: %S" cmd)))))
10777 ((consp cmd)
10778 ;; FIXME: Remove this check when most default installations of
10779 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10780 ;; fall back to `org-link-frame-setup' for an old usage of
10781 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10782 (user-error "Please see Org News for version 9.0 about \
10783 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10784 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10785 (funcall save-position-maybe)))
10787 (defun org-file-apps-entry-match-against-dlink-p (entry)
10788 "This function returns non-nil if `entry' uses a regular
10789 expression which should be matched against the whole link by
10790 org-open-file.
10792 It assumes that is the case when the entry uses a regular
10793 expression which has at least one grouping construct and the
10794 action is either a lisp form or a command string containing
10795 `%1', i.e. using at least one subexpression match as a
10796 parameter."
10797 (let ((selector (car entry))
10798 (action (cdr entry)))
10799 (if (stringp selector)
10800 (and (> (regexp-opt-depth selector) 0)
10801 (or (and (stringp action)
10802 (string-match "%[0-9]" action))
10803 (consp action)))
10804 nil)))
10806 (defun org-default-apps ()
10807 "Return the default applications for this operating system."
10808 (cond
10809 ((eq system-type 'darwin)
10810 org-file-apps-defaults-macosx)
10811 ((eq system-type 'windows-nt)
10812 org-file-apps-defaults-windowsnt)
10813 (t org-file-apps-defaults-gnu)))
10815 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10816 "Convert extensions to regular expressions in the cars of LIST.
10817 Also, weed out any non-string entries, because the return value is used
10818 only for regexp matching.
10819 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10820 point to the symbol `emacs', indicating that the file should
10821 be opened in Emacs."
10822 (append
10823 (delq nil
10824 (mapcar (lambda (x)
10825 (unless (not (stringp (car x)))
10826 (if (string-match "\\W" (car x))
10828 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10829 list))
10830 (when add-auto-mode
10831 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10833 (defvar ange-ftp-name-format)
10834 (defun org-file-remote-p (file)
10835 "Test whether FILE specifies a location on a remote system.
10836 Return non-nil if the location is indeed remote.
10838 For example, the filename \"/user@host:/foo\" specifies a location
10839 on the system \"/user@host:\"."
10840 (cond ((fboundp 'file-remote-p)
10841 (file-remote-p file))
10842 ((fboundp 'tramp-handle-file-remote-p)
10843 (tramp-handle-file-remote-p file))
10844 ((and (boundp 'ange-ftp-name-format)
10845 (string-match (car ange-ftp-name-format) file))
10846 t)))
10849 ;;;; Refiling
10851 (defun org-get-org-file ()
10852 "Read a filename, with default directory `org-directory'."
10853 (let ((default (or org-default-notes-file remember-data-file)))
10854 (read-file-name (format "File name [%s]: " default)
10855 (file-name-as-directory org-directory)
10856 default)))
10858 (defun org-notes-order-reversed-p ()
10859 "Check if the current file should receive notes in reversed order."
10860 (cond
10861 ((not org-reverse-note-order) nil)
10862 ((eq t org-reverse-note-order) t)
10863 ((not (listp org-reverse-note-order)) nil)
10864 (t (catch 'exit
10865 (dolist (entry org-reverse-note-order)
10866 (when (string-match (car entry) buffer-file-name)
10867 (throw 'exit (cdr entry))))))))
10869 (defvar org-refile-target-table nil
10870 "The list of refile targets, created by `org-refile'.")
10872 (defvar org-agenda-new-buffers nil
10873 "Buffers created to visit agenda files.")
10875 (defvar org-refile-cache nil
10876 "Cache for refile targets.")
10878 (defvar org-refile-markers nil
10879 "All the markers used for caching refile locations.")
10881 (defun org-refile-marker (pos)
10882 "Get a new refile marker, but only if caching is in use."
10883 (if (not org-refile-use-cache)
10885 (let ((m (make-marker)))
10886 (move-marker m pos)
10887 (push m org-refile-markers)
10888 m)))
10890 (defun org-refile-cache-clear ()
10891 "Clear the refile cache and disable all the markers."
10892 (dolist (m org-refile-markers) (move-marker m nil))
10893 (setq org-refile-markers nil)
10894 (setq org-refile-cache nil)
10895 (message "Refile cache has been cleared"))
10897 (defun org-refile-cache-check-set (set)
10898 "Check if all the markers in the cache still have live buffers."
10899 (let (marker)
10900 (catch 'exit
10901 (while (and set (setq marker (nth 3 (pop set))))
10902 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10903 (when (and marker (null (marker-buffer marker)))
10904 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10905 (sit-for 3)
10906 (throw 'exit nil)))
10907 t)))
10909 (defun org-refile-cache-put (set &rest identifiers)
10910 "Push the refile targets SET into the cache, under IDENTIFIERS."
10911 (let* ((key (sha1 (prin1-to-string identifiers)))
10912 (entry (assoc key org-refile-cache)))
10913 (if entry
10914 (setcdr entry set)
10915 (push (cons key set) org-refile-cache))))
10917 (defun org-refile-cache-get (&rest identifiers)
10918 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10919 (cond
10920 ((not org-refile-cache) nil)
10921 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10923 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10924 org-refile-cache))))
10925 (and set (org-refile-cache-check-set set) set)))))
10927 (defvar org-outline-path-cache nil
10928 "Alist between buffer positions and outline paths.
10929 It value is an alist (POSITION . PATH) where POSITION is the
10930 buffer position at the beginning of an entry and PATH is a list
10931 of strings describing the outline path for that entry, in reverse
10932 order.")
10934 (defun org-refile-get-targets (&optional default-buffer)
10935 "Produce a table with refile targets."
10936 (let ((case-fold-search nil)
10937 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10938 (entries (or org-refile-targets '((nil . (:level . 1)))))
10939 targets tgs files desc descre)
10940 (message "Getting targets...")
10941 (with-current-buffer (or default-buffer (current-buffer))
10942 (dolist (entry entries)
10943 (setq files (car entry) desc (cdr entry))
10944 (cond
10945 ((null files) (setq files (list (current-buffer))))
10946 ((eq files 'org-agenda-files)
10947 (setq files (org-agenda-files 'unrestricted)))
10948 ((and (symbolp files) (fboundp files))
10949 (setq files (funcall files)))
10950 ((and (symbolp files) (boundp files))
10951 (setq files (symbol-value files))))
10952 (when (stringp files) (setq files (list files)))
10953 (cond
10954 ((eq (car desc) :tag)
10955 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10956 ((eq (car desc) :todo)
10957 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10958 ((eq (car desc) :regexp)
10959 (setq descre (cdr desc)))
10960 ((eq (car desc) :level)
10961 (setq descre (concat "^\\*\\{" (number-to-string
10962 (if org-odd-levels-only
10963 (1- (* 2 (cdr desc)))
10964 (cdr desc)))
10965 "\\}[ \t]")))
10966 ((eq (car desc) :maxlevel)
10967 (setq descre (concat "^\\*\\{1," (number-to-string
10968 (if org-odd-levels-only
10969 (1- (* 2 (cdr desc)))
10970 (cdr desc)))
10971 "\\}[ \t]")))
10972 (t (error "Bad refiling target description %s" desc)))
10973 (dolist (f files)
10974 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10976 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10977 (progn
10978 (when (bufferp f)
10979 (setq f (buffer-file-name (buffer-base-buffer f))))
10980 (setq f (and f (expand-file-name f)))
10981 (when (eq org-refile-use-outline-path 'file)
10982 (push (list (file-name-nondirectory f) f nil nil) tgs))
10983 (when (eq org-refile-use-outline-path 'buffer-name)
10984 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10985 (when (eq org-refile-use-outline-path 'full-file-path)
10986 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10987 (org-with-wide-buffer
10988 (goto-char (point-min))
10989 (setq org-outline-path-cache nil)
10990 (while (re-search-forward descre nil t)
10991 (beginning-of-line)
10992 (let ((case-fold-search nil))
10993 (looking-at org-complex-heading-regexp))
10994 (let ((begin (point))
10995 (heading (match-string-no-properties 4)))
10996 (unless (or (and
10997 org-refile-target-verify-function
10998 (not
10999 (funcall org-refile-target-verify-function)))
11000 (not heading))
11001 (let ((re (format org-complex-heading-regexp-format
11002 (regexp-quote heading)))
11003 (target
11004 (if (not org-refile-use-outline-path) heading
11005 (mapconcat
11006 #'identity
11007 (append
11008 (pcase org-refile-use-outline-path
11009 (`file (list (file-name-nondirectory
11010 (buffer-file-name
11011 (buffer-base-buffer)))))
11012 (`full-file-path
11013 (list (buffer-file-name
11014 (buffer-base-buffer))))
11015 (`buffer-name
11016 (list (buffer-name
11017 (buffer-base-buffer))))
11018 (_ nil))
11019 (mapcar (lambda (s) (replace-regexp-in-string
11020 "/" "\\/" s nil t))
11021 (org-get-outline-path t t)))
11022 "/"))))
11023 (push (list target f re (org-refile-marker (point)))
11024 tgs)))
11025 (when (= (point) begin)
11026 ;; Verification function has not moved point.
11027 (end-of-line)))))))
11028 (when org-refile-use-cache
11029 (org-refile-cache-put tgs (buffer-file-name) descre))
11030 (setq targets (append tgs targets))))))
11031 (message "Getting targets...done")
11032 (delete-dups (nreverse targets))))
11034 (defun org--get-outline-path-1 (&optional use-cache)
11035 "Return outline path to current headline.
11037 Outline path is a list of strings, in reverse order. When
11038 optional argument USE-CACHE is non-nil, make use of a cache. See
11039 `org-get-outline-path' for details.
11041 Assume buffer is widened and point is on a headline."
11042 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11043 (let ((p (point))
11044 (heading (let ((case-fold-search nil))
11045 (looking-at org-complex-heading-regexp)
11046 (if (not (match-end 4)) ""
11047 ;; Remove statistics cookies.
11048 (org-trim
11049 (org-link-display-format
11050 (replace-regexp-in-string
11051 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11052 (match-string-no-properties 4))))))))
11053 (if (org-up-heading-safe)
11054 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11055 (when use-cache
11056 (push (cons p path) org-outline-path-cache))
11057 path)
11058 ;; This is a new root node. Since we assume we are moving
11059 ;; forward, we can drop previous cache so as to limit number
11060 ;; of associations there.
11061 (let ((path (list heading)))
11062 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11063 path)))))
11065 (defun org-get-outline-path (&optional with-self use-cache)
11066 "Return the outline path to the current entry.
11068 An outline path is a list of ancestors for current headline, as
11069 a list of strings. Statistics cookies are removed and links are
11070 replaced with their description, if any, or their path otherwise.
11072 When optional argument WITH-SELF is non-nil, the path also
11073 includes the current headline.
11075 When optional argument USE-CACHE is non-nil, cache outline paths
11076 between calls to this function so as to avoid backtracking. This
11077 argument is useful when planning to find more than one outline
11078 path in the same document. In that case, there are two
11079 conditions to satisfy:
11080 - `org-outline-path-cache' is set to nil before starting the
11081 process;
11082 - outline paths are computed by increasing buffer positions."
11083 (org-with-wide-buffer
11084 (and (or (and with-self (org-back-to-heading t))
11085 (org-up-heading-safe))
11086 (reverse (org--get-outline-path-1 use-cache)))))
11088 (defun org-format-outline-path (path &optional width prefix separator)
11089 "Format the outline path PATH for display.
11090 WIDTH is the maximum number of characters that is available.
11091 PREFIX is a prefix to be included in the returned string,
11092 such as the file name.
11093 SEPARATOR is inserted between the different parts of the path,
11094 the default is \"/\"."
11095 (setq width (or width 79))
11096 (setq path (delq nil path))
11097 (unless (> width 0)
11098 (user-error "Argument `width' must be positive"))
11099 (setq separator (or separator "/"))
11100 (let* ((org-odd-levels-only nil)
11101 (fpath (concat
11102 prefix (and prefix path separator)
11103 (mapconcat
11104 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11105 (cl-loop for head in path
11106 for n from 0
11107 collect (org-add-props
11108 head nil 'face
11109 (nth (% n org-n-level-faces) org-level-faces)))
11110 separator))))
11111 (when (> (length fpath) width)
11112 (if (< width 7)
11113 ;; It's unlikely that `width' will be this small, but don't
11114 ;; waste characters by adding ".." if it is.
11115 (setq fpath (substring fpath 0 width))
11116 (setf (substring fpath (- width 2)) "..")))
11117 fpath))
11119 (defun org-display-outline-path (&optional file current separator just-return-string)
11120 "Display the current outline path in the echo area.
11122 If FILE is non-nil, prepend the output with the file name.
11123 If CURRENT is non-nil, append the current heading to the output.
11124 SEPARATOR is passed through to `org-format-outline-path'. It separates
11125 the different parts of the path and defaults to \"/\".
11126 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11127 (interactive "P")
11128 (let* (case-fold-search
11129 (bfn (buffer-file-name (buffer-base-buffer)))
11130 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11131 res)
11132 (when current (setq path (append path
11133 (save-excursion
11134 (org-back-to-heading t)
11135 (when (looking-at org-complex-heading-regexp)
11136 (list (match-string 4)))))))
11137 (setq res
11138 (org-format-outline-path
11139 path
11140 (1- (frame-width))
11141 (and file bfn (concat (file-name-nondirectory bfn) separator))
11142 separator))
11143 (if just-return-string
11144 (org-no-properties res)
11145 (org-unlogged-message "%s" res))))
11147 (defvar org-refile-history nil
11148 "History for refiling operations.")
11150 (defvar org-after-refile-insert-hook nil
11151 "Hook run after `org-refile' has inserted its stuff at the new location.
11152 Note that this is still *before* the stuff will be removed from
11153 the *old* location.")
11155 (defvar org-capture-last-stored-marker)
11156 (defvar org-refile-keep nil
11157 "Non-nil means `org-refile' will copy instead of refile.")
11159 (defun org-copy ()
11160 "Like `org-refile', but copy."
11161 (interactive)
11162 (let ((org-refile-keep t))
11163 (funcall 'org-refile nil nil nil "Copy")))
11165 (defun org-refile (&optional arg default-buffer rfloc msg)
11166 "Move the entry or entries at point to another heading.
11168 The list of target headings is compiled using the information in
11169 `org-refile-targets', which see.
11171 At the target location, the entry is filed as a subitem of the
11172 target heading. Depending on `org-reverse-note-order', the new
11173 subitem will either be the first or the last subitem.
11175 If there is an active region, all entries in that region will be
11176 refiled. However, the region must fulfill the requirement that
11177 the first heading sets the top-level of the moved text.
11179 With a `\\[universal-argument]' ARG, the command will only visit the target \
11180 location
11181 and not actually move anything.
11183 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11184 location where the last
11185 refiling operation has put the subtree.
11187 With a numeric prefix argument of `2', refile to the running clock.
11189 With a numeric prefix argument of `3', emulate `org-refile-keep'
11190 being set to t and copy to the target location, don't move it.
11191 Beware that keeping refiled entries may result in duplicated ID
11192 properties.
11194 RFLOC can be a refile location obtained in a different way.
11196 MSG is a string to replace \"Refile\" in the default prompt with
11197 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11199 See also `org-refile-use-outline-path'.
11201 If you are using target caching (see `org-refile-use-cache'), you
11202 have to clear the target cache in order to find new targets.
11203 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11204 prefix argument (`C-u C-u C-u C-c C-w')."
11205 (interactive "P")
11206 (if (member arg '(0 (64)))
11207 (org-refile-cache-clear)
11208 (let* ((actionmsg (cond (msg msg)
11209 ((equal arg 3) "Refile (and keep)")
11210 (t "Refile")))
11211 (regionp (org-region-active-p))
11212 (region-start (and regionp (region-beginning)))
11213 (region-end (and regionp (region-end)))
11214 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11215 pos it nbuf file level reversed)
11216 (setq last-command nil)
11217 (when regionp
11218 (goto-char region-start)
11219 (or (bolp) (goto-char (point-at-bol)))
11220 (setq region-start (point))
11221 (unless (or (org-kill-is-subtree-p
11222 (buffer-substring region-start region-end))
11223 (prog1 org-refile-active-region-within-subtree
11224 (let ((s (point-at-eol)))
11225 (org-toggle-heading)
11226 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11227 (user-error "The region is not a (sequence of) subtree(s)")))
11228 (if (equal arg '(16))
11229 (org-refile-goto-last-stored)
11230 (when (or
11231 (and (equal arg 2)
11232 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11233 (prog1
11234 (setq it (list (or org-clock-heading "running clock")
11235 (buffer-file-name
11236 (marker-buffer org-clock-hd-marker))
11238 (marker-position org-clock-hd-marker)))
11239 (setq arg nil)))
11240 (setq it
11241 (or rfloc
11242 (let (heading-text)
11243 (save-excursion
11244 (unless (and arg (listp arg))
11245 (org-back-to-heading t)
11246 (setq heading-text
11247 (replace-regexp-in-string
11248 org-bracket-link-regexp
11249 "\\3"
11250 (or (nth 4 (org-heading-components))
11251 ""))))
11252 (org-refile-get-location
11253 (cond ((and arg (listp arg)) "Goto")
11254 (regionp (concat actionmsg " region to"))
11255 (t (concat actionmsg " subtree \""
11256 heading-text "\" to")))
11257 default-buffer
11258 (and (not (equal '(4) arg))
11259 org-refile-allow-creating-parent-nodes)))))))
11260 (setq file (nth 1 it)
11261 pos (nth 3 it))
11262 (when (and (not arg)
11264 (equal (buffer-file-name) file)
11265 (if regionp
11266 (and (>= pos region-start)
11267 (<= pos region-end))
11268 (and (>= pos (point))
11269 (< pos (save-excursion
11270 (org-end-of-subtree t t))))))
11271 (error "Cannot refile to position inside the tree or region"))
11272 (setq nbuf (or (find-buffer-visiting file)
11273 (find-file-noselect file)))
11274 (if (and arg (not (equal arg 3)))
11275 (progn
11276 (pop-to-buffer-same-window nbuf)
11277 (goto-char (cond (pos)
11278 ((org-notes-order-reversed-p) (point-min))
11279 (t (point-max))))
11280 (org-show-context 'org-goto))
11281 (if regionp
11282 (progn
11283 (org-kill-new (buffer-substring region-start region-end))
11284 (org-save-markers-in-region region-start region-end))
11285 (org-copy-subtree 1 nil t))
11286 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11287 (find-file-noselect file)))
11288 (setq reversed (org-notes-order-reversed-p))
11289 (org-with-wide-buffer
11290 (if pos
11291 (progn
11292 (goto-char pos)
11293 (setq level (org-get-valid-level (funcall outline-level) 1))
11294 (goto-char
11295 (if reversed
11296 (or (outline-next-heading) (point-max))
11297 (or (save-excursion (org-get-next-sibling))
11298 (org-end-of-subtree t t)
11299 (point-max)))))
11300 (setq level 1)
11301 (if (not reversed)
11302 (goto-char (point-max))
11303 (goto-char (point-min))
11304 (or (outline-next-heading) (goto-char (point-max)))))
11305 (unless (bolp) (newline))
11306 (org-paste-subtree level nil nil t)
11307 (when org-log-refile
11308 (org-add-log-setup 'refile nil nil org-log-refile)
11309 (unless (eq org-log-refile 'note)
11310 (save-excursion (org-add-log-note))))
11311 (and org-auto-align-tags
11312 (let ((org-loop-over-headlines-in-active-region nil))
11313 (org-set-tags nil t)))
11314 (let ((bookmark-name (plist-get org-bookmark-names-plist
11315 :last-refile)))
11316 (when bookmark-name
11317 (with-demoted-errors
11318 (bookmark-set bookmark-name))))
11319 ;; If we are refiling for capture, make sure that the
11320 ;; last-capture pointers point here
11321 (when (bound-and-true-p org-capture-is-refiling)
11322 (let ((bookmark-name (plist-get org-bookmark-names-plist
11323 :last-capture-marker)))
11324 (when bookmark-name
11325 (with-demoted-errors
11326 (bookmark-set bookmark-name))))
11327 (move-marker org-capture-last-stored-marker (point)))
11328 (when (fboundp 'deactivate-mark) (deactivate-mark))
11329 (run-hooks 'org-after-refile-insert-hook)))
11330 (unless org-refile-keep
11331 (if regionp
11332 (delete-region (point) (+ (point) (- region-end region-start)))
11333 (org-preserve-local-variables
11334 (delete-region
11335 (and (org-back-to-heading t) (point))
11336 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11337 (when (featurep 'org-inlinetask)
11338 (org-inlinetask-remove-END-maybe))
11339 (setq org-markers-to-move nil)
11340 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11342 (defun org-refile-goto-last-stored ()
11343 "Go to the location where the last refile was stored."
11344 (interactive)
11345 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11346 (message "This is the location of the last refile"))
11348 (defun org-refile--get-location (refloc tbl)
11349 "When user refile to REFLOC, find the associated target in TBL.
11350 Also check `org-refile-target-table'."
11351 (car (delq
11353 (mapcar
11354 (lambda (r) (or (assoc r tbl)
11355 (assoc r org-refile-target-table)))
11356 (list (replace-regexp-in-string "/$" "" refloc)
11357 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11359 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11360 "Prompt the user for a refile location, using PROMPT.
11361 PROMPT should not be suffixed with a colon and a space, because
11362 this function appends the default value from
11363 `org-refile-history' automatically, if that is not empty."
11364 (let ((org-refile-targets org-refile-targets)
11365 (org-refile-use-outline-path org-refile-use-outline-path))
11366 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11367 (unless org-refile-target-table
11368 (user-error "No refile targets"))
11369 (let* ((cbuf (current-buffer))
11370 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11371 (cfunc (if (and org-refile-use-outline-path
11372 org-outline-path-complete-in-steps)
11373 #'org-olpath-completing-read
11374 #'completing-read))
11375 (extra (if org-refile-use-outline-path "/" ""))
11376 (cbnex (concat (buffer-name) extra))
11377 (filename (and cfn (expand-file-name cfn)))
11378 (tbl (mapcar
11379 (lambda (x)
11380 (if (and (not (member org-refile-use-outline-path
11381 '(file full-file-path)))
11382 (not (equal filename (nth 1 x))))
11383 (cons (concat (car x) extra " ("
11384 (file-name-nondirectory (nth 1 x)) ")")
11385 (cdr x))
11386 (cons (concat (car x) extra) (cdr x))))
11387 org-refile-target-table))
11388 (completion-ignore-case t)
11389 cdef
11390 (prompt (concat prompt
11391 (or (and (car org-refile-history)
11392 (concat " (default " (car org-refile-history) ")"))
11393 (and (assoc cbnex tbl) (setq cdef cbnex)
11394 (concat " (default " cbnex ")"))) ": "))
11395 pa answ parent-target child parent old-hist)
11396 (setq old-hist org-refile-history)
11397 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11398 nil 'org-refile-history (or cdef (car org-refile-history))))
11399 (if (setq pa (org-refile--get-location answ tbl))
11400 (progn
11401 (org-refile-check-position pa)
11402 (when (or (not org-refile-history)
11403 (not (eq old-hist org-refile-history))
11404 (not (equal (car pa) (car org-refile-history))))
11405 (setq org-refile-history
11406 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11407 org-refile-history
11408 (cdr org-refile-history))))
11409 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11410 (pop org-refile-history)))
11412 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11413 (progn
11414 (setq parent (match-string 1 answ)
11415 child (match-string 2 answ))
11416 (setq parent-target (org-refile--get-location parent tbl))
11417 (when (and parent-target
11418 (or (eq new-nodes t)
11419 (and (eq new-nodes 'confirm)
11420 (y-or-n-p (format "Create new node \"%s\"? "
11421 child)))))
11422 (org-refile-new-child parent-target child)))
11423 (user-error "Invalid target location")))))
11425 (declare-function org-string-nw-p "org-macs" (s))
11426 (defun org-refile-check-position (refile-pointer)
11427 "Check if the refile pointer matches the headline to which it points."
11428 (let* ((file (nth 1 refile-pointer))
11429 (re (nth 2 refile-pointer))
11430 (pos (nth 3 refile-pointer))
11431 buffer)
11432 (if (and (not (markerp pos)) (not file))
11433 (user-error "Please indicate a target file in the refile path")
11434 (when (org-string-nw-p re)
11435 (setq buffer (if (markerp pos)
11436 (marker-buffer pos)
11437 (or (find-buffer-visiting file)
11438 (find-file-noselect file))))
11439 (with-current-buffer buffer
11440 (org-with-wide-buffer
11441 (goto-char pos)
11442 (beginning-of-line 1)
11443 (unless (looking-at-p re)
11444 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11446 (defun org-refile-new-child (parent-target child)
11447 "Use refile target PARENT-TARGET to add new CHILD below it."
11448 (unless parent-target
11449 (error "Cannot find parent for new node"))
11450 (let ((file (nth 1 parent-target))
11451 (pos (nth 3 parent-target))
11452 level)
11453 (with-current-buffer (or (find-buffer-visiting file)
11454 (find-file-noselect file))
11455 (org-with-wide-buffer
11456 (if pos
11457 (goto-char pos)
11458 (goto-char (point-max))
11459 (unless (bolp) (newline)))
11460 (when (looking-at org-outline-regexp)
11461 (setq level (funcall outline-level))
11462 (org-end-of-subtree t t))
11463 (org-back-over-empty-lines)
11464 (insert "\n" (make-string
11465 (if pos (org-get-valid-level level 1) 1) ?*)
11466 " " child "\n")
11467 (beginning-of-line 0)
11468 (list (concat (car parent-target) "/" child) file "" (point))))))
11470 (defun org-olpath-completing-read (prompt collection &rest args)
11471 "Read an outline path like a file name."
11472 (let ((thetable collection))
11473 (apply #'completing-read
11474 prompt
11475 (lambda (string predicate &optional flag)
11476 (cond
11477 ((eq flag nil) (try-completion string thetable))
11478 ((eq flag t)
11479 (let ((l (length string)))
11480 (mapcar (lambda (x)
11481 (let ((r (substring x l))
11482 (f (if (string-match " ([^)]*)$" x)
11483 (match-string 0 x)
11484 "")))
11485 (if (string-match "/" r)
11486 (concat string (substring r 0 (match-end 0)) f)
11487 x)))
11488 (all-completions string thetable predicate))))
11489 ;; Exact match?
11490 ((eq flag 'lambda) (assoc string thetable))))
11491 args)))
11493 ;;;; Dynamic blocks
11495 (defun org-find-dblock (name)
11496 "Find the first dynamic block with name NAME in the buffer.
11497 If not found, stay at current position and return nil."
11498 (let ((case-fold-search t) pos)
11499 (save-excursion
11500 (goto-char (point-min))
11501 (setq pos (and (re-search-forward
11502 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11503 (match-beginning 0))))
11504 (when pos (goto-char pos))
11505 pos))
11507 (defun org-create-dblock (plist)
11508 "Create a dynamic block section, with parameters taken from PLIST.
11509 PLIST must contain a :name entry which is used as the name of the block."
11510 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11511 (end-of-line 1)
11512 (newline))
11513 (let ((col (current-column))
11514 (name (plist-get plist :name)))
11515 (insert "#+BEGIN: " name)
11516 (while plist
11517 (if (eq (car plist) :name)
11518 (setq plist (cddr plist))
11519 (insert " " (prin1-to-string (pop plist)))))
11520 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11521 (beginning-of-line -2)))
11523 (defun org-prepare-dblock ()
11524 "Prepare dynamic block for refresh.
11525 This empties the block, puts the cursor at the insert position and returns
11526 the property list including an extra property :name with the block name."
11527 (unless (looking-at org-dblock-start-re)
11528 (user-error "Not at a dynamic block"))
11529 (let* ((begdel (1+ (match-end 0)))
11530 (name (org-no-properties (match-string 1)))
11531 (params (append (list :name name)
11532 (read (concat "(" (match-string 3) ")")))))
11533 (save-excursion
11534 (beginning-of-line 1)
11535 (skip-chars-forward " \t")
11536 (setq params (plist-put params :indentation-column (current-column))))
11537 (unless (re-search-forward org-dblock-end-re nil t)
11538 (error "Dynamic block not terminated"))
11539 (setq params
11540 (append params
11541 (list :content (buffer-substring
11542 begdel (match-beginning 0)))))
11543 (delete-region begdel (match-beginning 0))
11544 (goto-char begdel)
11545 (open-line 1)
11546 params))
11548 (defun org-map-dblocks (&optional command)
11549 "Apply COMMAND to all dynamic blocks in the current buffer.
11550 If COMMAND is not given, use `org-update-dblock'."
11551 (let ((cmd (or command 'org-update-dblock)))
11552 (save-excursion
11553 (goto-char (point-min))
11554 (while (re-search-forward org-dblock-start-re nil t)
11555 (goto-char (match-beginning 0))
11556 (save-excursion
11557 (condition-case nil
11558 (funcall cmd)
11559 (error (message "Error during update of dynamic block"))))
11560 (unless (re-search-forward org-dblock-end-re nil t)
11561 (error "Dynamic block not terminated"))))))
11563 (defun org-dblock-update (&optional arg)
11564 "User command for updating dynamic blocks.
11565 Update the dynamic block at point. With prefix ARG, update all dynamic
11566 blocks in the buffer."
11567 (interactive "P")
11568 (if arg
11569 (org-update-all-dblocks)
11570 (or (looking-at org-dblock-start-re)
11571 (org-beginning-of-dblock))
11572 (org-update-dblock)))
11574 (defun org-update-dblock ()
11575 "Update the dynamic block at point.
11576 This means to empty the block, parse for parameters and then call
11577 the correct writing function."
11578 (interactive)
11579 (save-excursion
11580 (let* ((win (selected-window))
11581 (pos (point))
11582 (line (org-current-line))
11583 (params (org-prepare-dblock))
11584 (name (plist-get params :name))
11585 (indent (plist-get params :indentation-column))
11586 (cmd (intern (concat "org-dblock-write:" name))))
11587 (message "Updating dynamic block `%s' at line %d..." name line)
11588 (funcall cmd params)
11589 (message "Updating dynamic block `%s' at line %d...done" name line)
11590 (goto-char pos)
11591 (when (and indent (> indent 0))
11592 (setq indent (make-string indent ?\ ))
11593 (save-excursion
11594 (select-window win)
11595 (org-beginning-of-dblock)
11596 (forward-line 1)
11597 (while (not (looking-at org-dblock-end-re))
11598 (insert indent)
11599 (beginning-of-line 2))
11600 (when (looking-at org-dblock-end-re)
11601 (and (looking-at "[ \t]+")
11602 (replace-match ""))
11603 (insert indent)))))))
11605 (defun org-beginning-of-dblock ()
11606 "Find the beginning of the dynamic block at point.
11607 Error if there is no such block at point."
11608 (let ((pos (point))
11609 beg)
11610 (end-of-line 1)
11611 (if (and (re-search-backward org-dblock-start-re nil t)
11612 (setq beg (match-beginning 0))
11613 (re-search-forward org-dblock-end-re nil t)
11614 (> (match-end 0) pos))
11615 (goto-char beg)
11616 (goto-char pos)
11617 (error "Not in a dynamic block"))))
11619 (defun org-update-all-dblocks ()
11620 "Update all dynamic blocks in the buffer.
11621 This function can be used in a hook."
11622 (interactive)
11623 (when (derived-mode-p 'org-mode)
11624 (org-map-dblocks 'org-update-dblock)))
11627 ;;;; Completion
11629 (declare-function org-export-backend-options "ox" (cl-x) t)
11630 (defun org-get-export-keywords ()
11631 "Return a list of all currently understood export keywords.
11632 Export keywords include options, block names, attributes and
11633 keywords relative to each registered export back-end."
11634 (let (keywords)
11635 (dolist (backend
11636 (bound-and-true-p org-export-registered-backends)
11637 (delq nil keywords))
11638 ;; Back-end name (for keywords, like #+LATEX:)
11639 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11640 (dolist (option-entry (org-export-backend-options backend))
11641 ;; Back-end options.
11642 (push (nth 1 option-entry) keywords)))))
11644 (defconst org-options-keywords
11645 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11646 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11647 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11648 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11649 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11651 (defcustom org-structure-template-alist
11652 '((?a . "export ascii")
11653 (?c . "center")
11654 (?C . "comment")
11655 (?e . "example")
11656 (?E . "export")
11657 (?h . "export html")
11658 (?l . "export latex")
11659 (?q . "quote")
11660 (?s . "src")
11661 (?v . "verse"))
11662 "Structure completion elements.
11663 This is an alist of characters and values. When
11664 `org-insert-structure-template' is called, an additional key is
11665 read. The key is first looked up in this alist, and the
11666 corresponding structure is inserted, with \"#+BEGIN_\" and
11667 \"#+END_\" added automatically."
11668 :group 'org-edit-structure
11669 :type '(repeat
11670 (cons (character :tag "Key")
11671 (string :tag "Template")))
11672 :package-version '(Org . "9.2"))
11674 (defun org-insert-structure-template (type)
11675 "Insert a block structure of the type #+begin_foo/#+end_foo.
11676 First read a character, which can be one of the keys in
11677 `org-structure-template-alist'. When it is <TAB>, prompt the
11678 user for a string to use. With an active region, wrap the region
11679 in the block. Otherwise, insert an empty block."
11680 (interactive
11681 (list
11682 (let* ((key (read-key "Key: "))
11683 (struct-string
11684 (or (cdr (assq key org-structure-template-alist))
11685 (and (= key ?\t)
11686 (read-string "Structure type: "))
11687 (user-error "`%c' has no structure definition" key))))
11688 struct-string)))
11689 (let* ((region? (use-region-p))
11690 (s (if region? (region-beginning) (point)))
11691 (e (copy-marker (if region? (region-end) (point)) t))
11692 column)
11693 (when (string-match-p
11694 (concat "\\`" (regexp-opt '("example" "export" "src")))
11695 type)
11696 (org-escape-code-in-region s e))
11697 (goto-char s)
11698 (setq column (current-indentation))
11699 (beginning-of-line)
11700 (indent-to column)
11701 (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
11702 (goto-char e)
11703 (if (bolp)
11704 (progn
11705 (skip-chars-backward " \n\t")
11706 (forward-line))
11707 (end-of-line)
11708 (insert "\n"))
11709 (indent-to column)
11710 (insert (format "#+end_%s\n"
11711 (car (split-string type))))
11712 (when (or (not region?)
11713 (string-match-p "src\\|\\`export\\'" type))
11714 (goto-char s)
11715 (end-of-line))
11716 (set-marker e nil)))
11718 ;;;; TODO, DEADLINE, Comments
11720 (defun org-toggle-comment ()
11721 "Change the COMMENT state of an entry."
11722 (interactive)
11723 (save-excursion
11724 (org-back-to-heading)
11725 (let ((case-fold-search nil))
11726 (looking-at org-complex-heading-regexp))
11727 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11728 (skip-chars-forward " \t")
11729 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11730 (if (org-in-commented-heading-p t)
11731 (delete-region (point)
11732 (progn (search-forward " " (line-end-position) 'move)
11733 (skip-chars-forward " \t")
11734 (point)))
11735 (insert org-comment-string)
11736 (unless (eolp) (insert " ")))))
11738 (defvar org-last-todo-state-is-todo nil
11739 "This is non-nil when the last TODO state change led to a TODO state.
11740 If the last change removed the TODO tag or switched to DONE, then
11741 this is nil.")
11743 (defvar org-setting-tags nil) ; dynamically skipped
11745 (defvar org-todo-setup-filter-hook nil
11746 "Hook for functions that pre-filter todo specs.
11747 Each function takes a todo spec and returns either nil or the spec
11748 transformed into canonical form." )
11750 (defvar org-todo-get-default-hook nil
11751 "Hook for functions that get a default item for todo.
11752 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11753 nil or a string to be used for the todo mark." )
11755 (defvar org-agenda-headline-snapshot-before-repeat)
11757 (defun org-current-effective-time ()
11758 "Return current time adjusted for `org-extend-today-until' variable."
11759 (let* ((ct (org-current-time))
11760 (dct (decode-time ct))
11761 (ct1
11762 (cond
11763 (org-use-last-clock-out-time-as-effective-time
11764 (or (org-clock-get-last-clock-out-time) ct))
11765 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11766 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11767 (t ct))))
11768 ct1))
11770 (defun org-todo-yesterday (&optional arg)
11771 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11772 (interactive "P")
11773 (if (eq major-mode 'org-agenda-mode)
11774 (apply 'org-agenda-todo-yesterday arg)
11775 (let* ((org-use-effective-time t)
11776 (hour (nth 2 (decode-time (org-current-time))))
11777 (org-extend-today-until (1+ hour)))
11778 (org-todo arg))))
11780 (defvar org-block-entry-blocking ""
11781 "First entry preventing the TODO state change.")
11783 (defun org-cancel-repeater ()
11784 "Cancel a repeater by setting its numeric value to zero."
11785 (interactive)
11786 (save-excursion
11787 (org-back-to-heading t)
11788 (let ((bound1 (point))
11789 (bound0 (save-excursion (outline-next-heading) (point))))
11790 (when (and (re-search-forward
11791 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11792 org-deadline-time-regexp "\\)\\|\\("
11793 org-ts-regexp "\\)")
11794 bound0 t)
11795 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11796 bound1 t))
11797 (replace-match "0" t nil nil 1)))))
11799 (defvar org-state)
11800 (defvar org-blocked-by-checkboxes)
11801 (defun org-todo (&optional arg)
11802 "Change the TODO state of an item.
11804 The state of an item is given by a keyword at the start of the heading,
11805 like
11806 *** TODO Write paper
11807 *** DONE Call mom
11809 The different keywords are specified in the variable `org-todo-keywords'.
11810 By default the available states are \"TODO\" and \"DONE\". So, for this
11811 example: when the item starts with TODO, it is changed to DONE.
11812 When it starts with DONE, the DONE is removed. And when neither TODO nor
11813 DONE are present, add TODO at the beginning of the heading.
11815 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11816 state.
11817 With numeric prefix ARG, switch to that state.
11818 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11819 next set of TODO \
11820 keywords (nextset).
11821 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11822 prefix, circumvent any state blocking.
11823 With a numeric prefix arg of 0, inhibit note taking for the change.
11824 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11826 When called through ELisp, arg is also interpreted in the following way:
11827 `none' -> empty state
11828 \"\" -> switch to empty state
11829 `done' -> switch to DONE
11830 `nextset' -> switch to the next set of keywords
11831 `previousset' -> switch to the previous set of keywords
11832 \"WAITING\" -> switch to the specified keyword, but only if it
11833 really is a member of `org-todo-keywords'."
11834 (interactive "P")
11835 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11836 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11837 'region-start-level 'region))
11838 org-loop-over-headlines-in-active-region)
11839 (org-map-entries
11840 `(org-todo ,arg)
11841 org-loop-over-headlines-in-active-region
11842 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11843 (when (equal arg '(16)) (setq arg 'nextset))
11844 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11845 (let ((org-blocker-hook org-blocker-hook)
11846 commentp
11847 case-fold-search)
11848 (when (equal arg '(64))
11849 (setq arg nil org-blocker-hook nil))
11850 (when (and org-blocker-hook
11851 (or org-inhibit-blocking
11852 (org-entry-get nil "NOBLOCKING")))
11853 (setq org-blocker-hook nil))
11854 (save-excursion
11855 (catch 'exit
11856 (org-back-to-heading t)
11857 (when (org-in-commented-heading-p t)
11858 (org-toggle-comment)
11859 (setq commentp t))
11860 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11861 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11862 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11863 (let* ((match-data (match-data))
11864 (startpos (copy-marker (line-beginning-position)))
11865 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11866 (org-log-done org-log-done)
11867 (org-log-repeat org-log-repeat)
11868 (org-todo-log-states org-todo-log-states)
11869 (org-inhibit-logging
11870 (if (equal arg 0)
11871 (progn (setq arg nil) 'note) org-inhibit-logging))
11872 (this (match-string 1))
11873 (hl-pos (match-beginning 0))
11874 (head (org-get-todo-sequence-head this))
11875 (ass (assoc head org-todo-kwd-alist))
11876 (interpret (nth 1 ass))
11877 (done-word (nth 3 ass))
11878 (final-done-word (nth 4 ass))
11879 (org-last-state (or this ""))
11880 (completion-ignore-case t)
11881 (member (member this org-todo-keywords-1))
11882 (tail (cdr member))
11883 (org-state (cond
11884 ((and org-todo-key-trigger
11885 (or (and (equal arg '(4))
11886 (eq org-use-fast-todo-selection 'prefix))
11887 (and (not arg) org-use-fast-todo-selection
11888 (not (eq org-use-fast-todo-selection
11889 'prefix)))))
11890 ;; Use fast selection.
11891 (org-fast-todo-selection))
11892 ((and (equal arg '(4))
11893 (or (not org-use-fast-todo-selection)
11894 (not org-todo-key-trigger)))
11895 ;; Read a state with completion.
11896 (completing-read
11897 "State: " (mapcar #'list org-todo-keywords-1)
11898 nil t))
11899 ((eq arg 'right)
11900 (if this
11901 (if tail (car tail) nil)
11902 (car org-todo-keywords-1)))
11903 ((eq arg 'left)
11904 (unless (equal member org-todo-keywords-1)
11905 (if this
11906 (nth (- (length org-todo-keywords-1)
11907 (length tail) 2)
11908 org-todo-keywords-1)
11909 (org-last org-todo-keywords-1))))
11910 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11911 (setq arg nil))) ;hack to fall back to cycling
11912 (arg
11913 ;; User or caller requests a specific state.
11914 (cond
11915 ((equal arg "") nil)
11916 ((eq arg 'none) nil)
11917 ((eq arg 'done) (or done-word (car org-done-keywords)))
11918 ((eq arg 'nextset)
11919 (or (car (cdr (member head org-todo-heads)))
11920 (car org-todo-heads)))
11921 ((eq arg 'previousset)
11922 (let ((org-todo-heads (reverse org-todo-heads)))
11923 (or (car (cdr (member head org-todo-heads)))
11924 (car org-todo-heads))))
11925 ((car (member arg org-todo-keywords-1)))
11926 ((stringp arg)
11927 (user-error "State `%s' not valid in this file" arg))
11928 ((nth (1- (prefix-numeric-value arg))
11929 org-todo-keywords-1))))
11930 ((null member) (or head (car org-todo-keywords-1)))
11931 ((equal this final-done-word) nil) ;-> make empty
11932 ((null tail) nil) ;-> first entry
11933 ((memq interpret '(type priority))
11934 (if (eq this-command last-command)
11935 (car tail)
11936 (if (> (length tail) 0)
11937 (or done-word (car org-done-keywords))
11938 nil)))
11940 (car tail))))
11941 (org-state (or
11942 (run-hook-with-args-until-success
11943 'org-todo-get-default-hook org-state org-last-state)
11944 org-state))
11945 (next (if org-state (concat " " org-state " ") " "))
11946 (change-plist (list :type 'todo-state-change :from this :to org-state
11947 :position startpos))
11948 dolog now-done-p)
11949 (when org-blocker-hook
11950 (let (org-blocked-by-checkboxes block-reason)
11951 (setq org-last-todo-state-is-todo
11952 (not (member this org-done-keywords)))
11953 (unless (save-excursion
11954 (save-match-data
11955 (org-with-wide-buffer
11956 (run-hook-with-args-until-failure
11957 'org-blocker-hook change-plist))))
11958 (setq block-reason (if org-blocked-by-checkboxes
11959 "contained checkboxes"
11960 (format "\"%s\"" org-block-entry-blocking)))
11961 (if (called-interactively-p 'interactive)
11962 (user-error "TODO state change from %s to %s blocked (by %s)"
11963 this org-state block-reason)
11964 ;; Fail silently.
11965 (message "TODO state change from %s to %s blocked (by %s)"
11966 this org-state block-reason)
11967 (throw 'exit nil)))))
11968 (store-match-data match-data)
11969 (replace-match next t t)
11970 (cond ((equal this org-state)
11971 (message "TODO state was already %s" (org-trim next)))
11972 ((not (pos-visible-in-window-p hl-pos))
11973 (message "TODO state changed to %s" (org-trim next))))
11974 (unless head
11975 (setq head (org-get-todo-sequence-head org-state)
11976 ass (assoc head org-todo-kwd-alist)
11977 interpret (nth 1 ass)
11978 done-word (nth 3 ass)
11979 final-done-word (nth 4 ass)))
11980 (when (memq arg '(nextset previousset))
11981 (message "Keyword-Set %d/%d: %s"
11982 (- (length org-todo-sets) -1
11983 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11984 (length org-todo-sets)
11985 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11986 (setq org-last-todo-state-is-todo
11987 (not (member org-state org-done-keywords)))
11988 (setq now-done-p (and (member org-state org-done-keywords)
11989 (not (member this org-done-keywords))))
11990 (and logging (org-local-logging logging))
11991 (when (and (or org-todo-log-states org-log-done)
11992 (not (eq org-inhibit-logging t))
11993 (not (memq arg '(nextset previousset))))
11994 ;; We need to look at recording a time and note.
11995 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11996 (nth 2 (assoc this org-todo-log-states))))
11997 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11998 (setq dolog 'time))
11999 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12000 (and org-state
12001 (member org-state org-not-done-keywords)
12002 (not (member this org-not-done-keywords))))
12003 ;; This is now a todo state and was not one before
12004 ;; If there was a CLOSED time stamp, get rid of it.
12005 (org-add-planning-info nil nil 'closed))
12006 (when (and now-done-p org-log-done)
12007 ;; It is now done, and it was not done before.
12008 (org-add-planning-info 'closed (org-current-effective-time))
12009 (when (and (not dolog) (eq 'note org-log-done))
12010 (org-add-log-setup 'done org-state this 'note)))
12011 (when (and org-state dolog)
12012 ;; This is a non-nil state, and we need to log it.
12013 (org-add-log-setup 'state org-state this dolog)))
12014 ;; Fixup tag positioning.
12015 (org-todo-trigger-tag-changes org-state)
12016 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12017 (when org-provide-todo-statistics
12018 (org-update-parent-todo-statistics))
12019 (run-hooks 'org-after-todo-state-change-hook)
12020 (when (and arg (not (member org-state org-done-keywords)))
12021 (setq head (org-get-todo-sequence-head org-state)))
12022 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12023 ;; Do we need to trigger a repeat?
12024 (when now-done-p
12025 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12026 ;; This is for the agenda, take a snapshot of the headline.
12027 (save-match-data
12028 (setq org-agenda-headline-snapshot-before-repeat
12029 (org-get-heading))))
12030 (org-auto-repeat-maybe org-state))
12031 ;; Fixup cursor location if close to the keyword.
12032 (when (and (outline-on-heading-p)
12033 (not (bolp))
12034 (save-excursion (beginning-of-line 1)
12035 (looking-at org-todo-line-regexp))
12036 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12037 (goto-char (or (match-end 2) (match-end 1)))
12038 (and (looking-at " ") (just-one-space)))
12039 (when org-trigger-hook
12040 (save-excursion
12041 (run-hook-with-args 'org-trigger-hook change-plist)))
12042 (when commentp (org-toggle-comment))))))))
12044 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12045 "Block turning an entry into a TODO, using the hierarchy.
12046 This checks whether the current task should be blocked from state
12047 changes. Such blocking occurs when:
12049 1. The task has children which are not all in a completed state.
12051 2. A task has a parent with the property :ORDERED:, and there
12052 are siblings prior to the current task with incomplete
12053 status.
12055 3. The parent of the task is blocked because it has siblings that should
12056 be done first, or is child of a block grandparent TODO entry."
12058 (if (not org-enforce-todo-dependencies)
12059 t ; if locally turned off don't block
12060 (catch 'dont-block
12061 ;; If this is not a todo state change, or if this entry is already DONE,
12062 ;; do not block
12063 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12064 (member (plist-get change-plist :from)
12065 (cons 'done org-done-keywords))
12066 (member (plist-get change-plist :to)
12067 (cons 'todo org-not-done-keywords))
12068 (not (plist-get change-plist :to)))
12069 (throw 'dont-block t))
12070 ;; If this task has children, and any are undone, it's blocked
12071 (save-excursion
12072 (org-back-to-heading t)
12073 (let ((this-level (funcall outline-level)))
12074 (outline-next-heading)
12075 (let ((child-level (funcall outline-level)))
12076 (while (and (not (eobp))
12077 (> child-level this-level))
12078 ;; this todo has children, check whether they are all
12079 ;; completed
12080 (when (and (not (org-entry-is-done-p))
12081 (org-entry-is-todo-p))
12082 (setq org-block-entry-blocking (org-get-heading))
12083 (throw 'dont-block nil))
12084 (outline-next-heading)
12085 (setq child-level (funcall outline-level))))))
12086 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12087 ;; any previous siblings are undone, it's blocked
12088 (save-excursion
12089 (org-back-to-heading t)
12090 (let* ((pos (point))
12091 (parent-pos (and (org-up-heading-safe) (point)))
12092 (case-fold-search nil))
12093 (unless parent-pos (throw 'dont-block t)) ; no parent
12094 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12095 (forward-line 1)
12096 (re-search-forward org-not-done-heading-regexp pos t))
12097 (setq org-block-entry-blocking (match-string 0))
12098 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12099 ;; Search further up the hierarchy, to see if an ancestor is blocked
12100 (while t
12101 (goto-char parent-pos)
12102 (unless (looking-at org-not-done-heading-regexp)
12103 (throw 'dont-block t)) ; do not block, parent is not a TODO
12104 (setq pos (point))
12105 (setq parent-pos (and (org-up-heading-safe) (point)))
12106 (unless parent-pos (throw 'dont-block t)) ; no parent
12107 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12108 (forward-line 1)
12109 (re-search-forward org-not-done-heading-regexp pos t)
12110 (setq org-block-entry-blocking (org-get-heading)))
12111 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12113 (defcustom org-track-ordered-property-with-tag nil
12114 "Should the ORDERED property also be shown as a tag?
12115 The ORDERED property decides if an entry should require subtasks to be
12116 completed in sequence. Since a property is not very visible, setting
12117 this option means that toggling the ORDERED property with the command
12118 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12119 not relevant for the behavior, but it makes things more visible.
12121 Note that toggling the tag with tags commands will not change the property
12122 and therefore not influence behavior!
12124 This can be t, meaning the tag ORDERED should be used, It can also be a
12125 string to select a different tag for this task."
12126 :group 'org-todo
12127 :type '(choice
12128 (const :tag "No tracking" nil)
12129 (const :tag "Track with ORDERED tag" t)
12130 (string :tag "Use other tag")))
12132 (defun org-toggle-ordered-property ()
12133 "Toggle the ORDERED property of the current entry.
12134 For better visibility, you can track the value of this property with a tag.
12135 See variable `org-track-ordered-property-with-tag'."
12136 (interactive)
12137 (let* ((t1 org-track-ordered-property-with-tag)
12138 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12139 (save-excursion
12140 (org-back-to-heading)
12141 (if (org-entry-get nil "ORDERED")
12142 (progn
12143 (org-delete-property "ORDERED")
12144 (and tag (org-toggle-tag tag 'off))
12145 (message "Subtasks can be completed in arbitrary order"))
12146 (org-entry-put nil "ORDERED" "t")
12147 (and tag (org-toggle-tag tag 'on))
12148 (message "Subtasks must be completed in sequence")))))
12150 (defun org-block-todo-from-checkboxes (change-plist)
12151 "Block turning an entry into a TODO, using checkboxes.
12152 This checks whether the current task should be blocked from state
12153 changes because there are unchecked boxes in this entry."
12154 (if (not org-enforce-todo-checkbox-dependencies)
12155 t ; if locally turned off don't block
12156 (catch 'dont-block
12157 ;; If this is not a todo state change, or if this entry is already DONE,
12158 ;; do not block
12159 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12160 (member (plist-get change-plist :from)
12161 (cons 'done org-done-keywords))
12162 (member (plist-get change-plist :to)
12163 (cons 'todo org-not-done-keywords))
12164 (not (plist-get change-plist :to)))
12165 (throw 'dont-block t))
12166 ;; If this task has checkboxes that are not checked, it's blocked
12167 (save-excursion
12168 (org-back-to-heading t)
12169 (let ((beg (point)) end)
12170 (outline-next-heading)
12171 (setq end (point))
12172 (goto-char beg)
12173 (when (org-list-search-forward
12174 (concat (org-item-beginning-re)
12175 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12176 "\\[[- ]\\]")
12177 end t)
12178 (when (boundp 'org-blocked-by-checkboxes)
12179 (setq org-blocked-by-checkboxes t))
12180 (throw 'dont-block nil))))
12181 t))) ; do not block
12183 (defun org-entry-blocked-p ()
12184 "Non-nil if entry at point is blocked."
12185 (and (not (org-entry-get nil "NOBLOCKING"))
12186 (member (org-entry-get nil "TODO") org-not-done-keywords)
12187 (not (run-hook-with-args-until-failure
12188 'org-blocker-hook
12189 (list :type 'todo-state-change
12190 :position (point)
12191 :from 'todo
12192 :to 'done)))))
12194 (defun org-update-statistics-cookies (all)
12195 "Update the statistics cookie, either from TODO or from checkboxes.
12196 This should be called with the cursor in a line with a statistics
12197 cookie. When called with a \\[universal-argument] prefix, update
12198 all statistics cookies in the buffer."
12199 (interactive "P")
12200 (if all
12201 (progn
12202 (org-update-checkbox-count 'all)
12203 (org-map-entries 'org-update-parent-todo-statistics))
12204 (if (not (org-at-heading-p))
12205 (org-update-checkbox-count)
12206 (let ((pos (point-marker))
12207 end l1 l2)
12208 (ignore-errors (org-back-to-heading t))
12209 (if (not (org-at-heading-p))
12210 (org-update-checkbox-count)
12211 (setq l1 (org-outline-level))
12212 (setq end (save-excursion
12213 (outline-next-heading)
12214 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12215 (point)))
12216 (if (and (save-excursion
12217 (re-search-forward
12218 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12219 (not (save-excursion (re-search-forward
12220 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12221 (org-update-checkbox-count)
12222 (if (and l2 (> l2 l1))
12223 (progn
12224 (goto-char end)
12225 (org-update-parent-todo-statistics))
12226 (goto-char pos)
12227 (beginning-of-line 1)
12228 (while (re-search-forward
12229 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12230 (point-at-eol) t)
12231 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12232 (goto-char pos)
12233 (move-marker pos nil)))))
12235 (defvar org-entry-property-inherited-from) ;; defined below
12236 (defun org-update-parent-todo-statistics ()
12237 "Update any statistics cookie in the parent of the current headline.
12238 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12239 the entire subtree and this will travel up the hierarchy and update
12240 statistics everywhere."
12241 (let* ((prop (save-excursion (org-up-heading-safe)
12242 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12243 (recursive (or (not org-hierarchical-todo-statistics)
12244 (and prop (string-match "\\<recursive\\>" prop))))
12245 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12247 (first t)
12248 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12249 level ltoggle l1 new ndel
12250 (cnt-all 0) (cnt-done 0) is-percent kwd
12251 checkbox-beg cookie-present)
12252 (catch 'exit
12253 (save-excursion
12254 (beginning-of-line 1)
12255 (setq ltoggle (funcall outline-level))
12256 ;; Three situations are to consider:
12258 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12259 ;; to the top-level ancestor on the headline;
12261 ;; 2. If parent has "recursive" property, repeat up to the
12262 ;; headline setting that property, taking inheritance into
12263 ;; account;
12265 ;; 3. Else, move up to direct parent and proceed only once.
12266 (while (and (setq level (org-up-heading-safe))
12267 (or recursive first)
12268 (>= (point) lim))
12269 (setq first nil cookie-present nil)
12270 (unless (and level
12271 (not (string-match
12272 "\\<checkbox\\>"
12273 (downcase (or (org-entry-get nil "COOKIE_DATA")
12274 "")))))
12275 (throw 'exit nil))
12276 (while (re-search-forward box-re (point-at-eol) t)
12277 (setq cnt-all 0 cnt-done 0 cookie-present t)
12278 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12279 (save-match-data
12280 (unless (outline-next-heading) (throw 'exit nil))
12281 (while (and (looking-at org-complex-heading-regexp)
12282 (> (setq l1 (length (match-string 1))) level))
12283 (setq kwd (and (or recursive (= l1 ltoggle))
12284 (match-string 2)))
12285 (if (or (eq org-provide-todo-statistics 'all-headlines)
12286 (and (eq org-provide-todo-statistics t)
12287 (or (member kwd org-done-keywords)))
12288 (and (listp org-provide-todo-statistics)
12289 (stringp (car org-provide-todo-statistics))
12290 (or (member kwd org-provide-todo-statistics)
12291 (member kwd org-done-keywords)))
12292 (and (listp org-provide-todo-statistics)
12293 (listp (car org-provide-todo-statistics))
12294 (or (member kwd (car org-provide-todo-statistics))
12295 (and (member kwd org-done-keywords)
12296 (member kwd (cadr org-provide-todo-statistics))))))
12297 (setq cnt-all (1+ cnt-all))
12298 (and (eq org-provide-todo-statistics t)
12300 (setq cnt-all (1+ cnt-all))))
12301 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12302 (member kwd org-done-keywords))
12303 (and (listp org-provide-todo-statistics)
12304 (listp (car org-provide-todo-statistics))
12305 (member kwd org-done-keywords)
12306 (member kwd (cadr org-provide-todo-statistics)))
12307 (and (listp org-provide-todo-statistics)
12308 (stringp (car org-provide-todo-statistics))
12309 (member kwd org-done-keywords)))
12310 (setq cnt-done (1+ cnt-done)))
12311 (outline-next-heading)))
12312 (setq new
12313 (if is-percent
12314 (format "[%d%%]" (floor (* 100.0 cnt-done)
12315 (max 1 cnt-all)))
12316 (format "[%d/%d]" cnt-done cnt-all))
12317 ndel (- (match-end 0) checkbox-beg))
12318 (goto-char checkbox-beg)
12319 (insert new)
12320 (delete-region (point) (+ (point) ndel))
12321 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12322 (when cookie-present
12323 (run-hook-with-args 'org-after-todo-statistics-hook
12324 cnt-done (- cnt-all cnt-done))))))
12325 (run-hooks 'org-todo-statistics-hook)))
12327 (defvar org-after-todo-statistics-hook nil
12328 "Hook that is called after a TODO statistics cookie has been updated.
12329 Each function is called with two arguments: the number of not-done entries
12330 and the number of done entries.
12332 For example, the following function, when added to this hook, will switch
12333 an entry to DONE when all children are done, and back to TODO when new
12334 entries are set to a TODO status. Note that this hook is only called
12335 when there is a statistics cookie in the headline!
12337 (defun org-summary-todo (n-done n-not-done)
12338 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12339 (let (org-log-done org-log-states) ; turn off logging
12340 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12343 (defvar org-todo-statistics-hook nil
12344 "Hook that is run whenever Org thinks TODO statistics should be updated.
12345 This hook runs even if there is no statistics cookie present, in which case
12346 `org-after-todo-statistics-hook' would not run.")
12348 (defun org-todo-trigger-tag-changes (state)
12349 "Apply the changes defined in `org-todo-state-tags-triggers'."
12350 (let ((l org-todo-state-tags-triggers)
12351 changes)
12352 (when (or (not state) (equal state ""))
12353 (setq changes (append changes (cdr (assoc "" l)))))
12354 (when (and (stringp state) (> (length state) 0))
12355 (setq changes (append changes (cdr (assoc state l)))))
12356 (when (member state org-not-done-keywords)
12357 (setq changes (append changes (cdr (assq 'todo l)))))
12358 (when (member state org-done-keywords)
12359 (setq changes (append changes (cdr (assq 'done l)))))
12360 (dolist (c changes)
12361 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12363 (defun org-local-logging (value)
12364 "Get logging settings from a property VALUE."
12365 ;; Directly set the variables, they are already local.
12366 (setq org-log-done nil
12367 org-log-repeat nil
12368 org-todo-log-states nil)
12369 (dolist (w (split-string value))
12370 (let (a)
12371 (cond
12372 ((setq a (assoc w org-startup-options))
12373 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12374 (set (nth 1 a) (nth 2 a))))
12375 ((setq a (org-extract-log-state-settings w))
12376 (and (member (car a) org-todo-keywords-1)
12377 (push a org-todo-log-states)))))))
12379 (defun org-get-todo-sequence-head (kwd)
12380 "Return the head of the TODO sequence to which KWD belongs.
12381 If KWD is not set, check if there is a text property remembering the
12382 right sequence."
12383 (let (p)
12384 (cond
12385 ((not kwd)
12386 (or (get-text-property (point-at-bol) 'org-todo-head)
12387 (progn
12388 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12389 nil (point-at-eol)))
12390 (get-text-property p 'org-todo-head))))
12391 ((not (member kwd org-todo-keywords-1))
12392 (car org-todo-keywords-1))
12393 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12395 (defun org-fast-todo-selection ()
12396 "Fast TODO keyword selection with single keys.
12397 Returns the new TODO keyword, or nil if no state change should occur."
12398 (let* ((fulltable org-todo-key-alist)
12399 (done-keywords org-done-keywords) ;; needed for the faces.
12400 (maxlen (apply 'max (mapcar
12401 (lambda (x)
12402 (if (stringp (car x)) (string-width (car x)) 0))
12403 fulltable)))
12404 (expert nil)
12405 (fwidth (+ maxlen 3 1 3))
12406 (ncol (/ (- (window-width) 4) fwidth))
12407 tg cnt e c tbl
12408 groups ingroup)
12409 (save-excursion
12410 (save-window-excursion
12411 (if expert
12412 (set-buffer (get-buffer-create " *Org todo*"))
12413 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12414 (erase-buffer)
12415 (setq-local org-done-keywords done-keywords)
12416 (setq tbl fulltable cnt 0)
12417 (while (setq e (pop tbl))
12418 (cond
12419 ((equal e '(:startgroup))
12420 (push '() groups) (setq ingroup t)
12421 (unless (= cnt 0)
12422 (setq cnt 0)
12423 (insert "\n"))
12424 (insert "{ "))
12425 ((equal e '(:endgroup))
12426 (setq ingroup nil cnt 0)
12427 (insert "}\n"))
12428 ((equal e '(:newline))
12429 (unless (= cnt 0)
12430 (setq cnt 0)
12431 (insert "\n")
12432 (setq e (car tbl))
12433 (while (equal (car tbl) '(:newline))
12434 (insert "\n")
12435 (setq tbl (cdr tbl)))))
12437 (setq tg (car e) c (cdr e))
12438 (when ingroup (push tg (car groups)))
12439 (setq tg (org-add-props tg nil 'face
12440 (org-get-todo-face tg)))
12441 (when (and (= cnt 0) (not ingroup)) (insert " "))
12442 (insert "[" c "] " tg (make-string
12443 (- fwidth 4 (length tg)) ?\ ))
12444 (when (= (setq cnt (1+ cnt)) ncol)
12445 (insert "\n")
12446 (when ingroup (insert " "))
12447 (setq cnt 0)))))
12448 (insert "\n")
12449 (goto-char (point-min))
12450 (unless expert (org-fit-window-to-buffer))
12451 (message "[a-z..]:Set [SPC]:clear")
12452 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12453 (cond
12454 ((or (= c ?\C-g)
12455 (and (= c ?q) (not (rassoc c fulltable))))
12456 (setq quit-flag t))
12457 ((= c ?\ ) nil)
12458 ((setq e (rassoc c fulltable) tg (car e))
12460 (t (setq quit-flag t)))))))
12462 (defun org-entry-is-todo-p ()
12463 (member (org-get-todo-state) org-not-done-keywords))
12465 (defun org-entry-is-done-p ()
12466 (member (org-get-todo-state) org-done-keywords))
12468 (defun org-get-todo-state ()
12469 "Return the TODO keyword of the current subtree."
12470 (save-excursion
12471 (org-back-to-heading t)
12472 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12473 (match-end 2)
12474 (match-string 2))))
12476 (defun org-at-date-range-p (&optional inactive-ok)
12477 "Non-nil if point is inside a date range.
12479 When optional argument INACTIVE-OK is non-nil, also consider
12480 inactive time ranges.
12482 When this function returns a non-nil value, match data is set
12483 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12484 on INACTIVE-OK."
12485 (interactive)
12486 (save-excursion
12487 (catch 'exit
12488 (let ((pos (point)))
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 (skip-chars-backward "^<[\r\n")
12495 (skip-chars-backward "<[")
12496 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12497 (>= (match-end 0) pos)
12498 (throw 'exit t)))
12499 nil)))
12501 (defun org-get-repeat (&optional timestamp)
12502 "Check if there is a time-stamp with repeater in this entry.
12504 Return the repeater, as a string, or nil. Also return nil when
12505 this function is called before first heading.
12507 When optional argument TIMESTAMP is a string, extract the
12508 repeater from there instead."
12509 (save-match-data
12510 (cond (timestamp
12511 (and (string-match org-repeat-re timestamp)
12512 (match-string-no-properties 1 timestamp)))
12513 ((org-before-first-heading-p) nil)
12515 (save-excursion
12516 (org-back-to-heading t)
12517 (let ((end (org-entry-end-position)))
12518 (catch :repeat
12519 (while (re-search-forward org-repeat-re end t)
12520 (when (save-match-data (org-at-timestamp-p 'agenda))
12521 (throw :repeat (match-string-no-properties 1)))))))))))
12523 (defvar org-last-changed-timestamp)
12524 (defvar org-last-inserted-timestamp)
12525 (defvar org-log-post-message)
12526 (defvar org-log-note-purpose)
12527 (defvar org-log-note-how nil)
12528 (defvar org-log-note-extra)
12529 (defun org-auto-repeat-maybe (done-word)
12530 "Check if the current headline contains a repeated time-stamp.
12532 If yes, set TODO state back to what it was and change the base date
12533 of repeating deadline/scheduled time stamps to new date.
12535 This function is run automatically after each state change to a DONE state."
12536 (let* ((repeat (org-get-repeat))
12537 (aa (assoc org-last-state org-todo-kwd-alist))
12538 (interpret (nth 1 aa))
12539 (head (nth 2 aa))
12540 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12541 (msg "Entry repeats: ")
12542 (org-log-done nil)
12543 (org-todo-log-states nil)
12544 (end (copy-marker (org-entry-end-position))))
12545 (unwind-protect
12546 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12547 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12548 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12549 (and (stringp org-todo-repeat-to-state)
12550 org-todo-repeat-to-state)
12551 (and org-todo-repeat-to-state org-last-state))))
12552 (org-todo (cond
12553 ((and to-state (member to-state org-todo-keywords-1))
12554 to-state)
12555 ((eq interpret 'type) org-last-state)
12556 (head)
12557 (t 'none))))
12558 (org-back-to-heading t)
12559 (org-add-planning-info nil nil 'closed)
12560 ;; When `org-log-repeat' is non-nil or entry contains
12561 ;; a clock, set LAST_REPEAT property.
12562 (when (or org-log-repeat
12563 (catch :clock
12564 (save-excursion
12565 (while (re-search-forward org-clock-line-re end t)
12566 (when (org-at-clock-log-p) (throw :clock t))))))
12567 (org-entry-put nil "LAST_REPEAT" (format-time-string
12568 (org-time-stamp-format t t)
12569 (current-time))))
12570 (when org-log-repeat
12571 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12572 (memq 'org-add-log-note post-command-hook))
12573 ;; We are already setup for some record.
12574 (when (eq org-log-repeat 'note)
12575 ;; Make sure we take a note, not only a time stamp.
12576 (setq org-log-note-how 'note))
12577 ;; Set up for taking a record.
12578 (org-add-log-setup 'state
12579 (or done-word (car org-done-keywords))
12580 org-last-state
12581 org-log-repeat)))
12582 (let ((planning-re (regexp-opt
12583 (list org-scheduled-string org-deadline-string))))
12584 (while (re-search-forward org-ts-regexp end t)
12585 (let* ((ts (match-string 0))
12586 (planning? (org-at-planning-p))
12587 (type (if (not planning?) "Plain:"
12588 (save-excursion
12589 (re-search-backward
12590 planning-re (line-beginning-position) t)
12591 (match-string 0)))))
12592 (cond
12593 ;; Ignore fake time-stamps (e.g., within comments).
12594 ((not (org-at-timestamp-p 'agenda)))
12595 ;; Time-stamps without a repeater are usually
12596 ;; skipped. However, a SCHEDULED time-stamp without
12597 ;; one is removed, as they are no longer relevant.
12598 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12599 ts))
12600 (when (equal type org-scheduled-string)
12601 (org-remove-timestamp-with-keyword type)))
12603 (let ((n (string-to-number (match-string 2 ts)))
12604 (what (match-string 3 ts)))
12605 (when (equal what "w") (setq n (* n 7) what "d"))
12606 (when (and (equal what "h")
12607 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12608 ts)))
12609 (user-error
12610 "Cannot repeat in Repeat in %d hour(s) because no hour \
12611 has been set"
12613 ;; Preparation, see if we need to modify the start
12614 ;; date for the change.
12615 (when (match-end 1)
12616 (let ((time (save-match-data
12617 (org-time-string-to-time ts))))
12618 (cond
12619 ((equal (match-string 1 ts) ".")
12620 ;; Shift starting date to today
12621 (org-timestamp-change
12622 (- (org-today) (time-to-days time))
12623 'day))
12624 ((equal (match-string 1 ts) "+")
12625 (let ((nshiftmax 10)
12626 (nshift 0))
12627 (while (or (= nshift 0)
12628 (not (time-less-p (current-time) time)))
12629 (when (= (cl-incf nshift) nshiftmax)
12630 (or (y-or-n-p
12631 (format "%d repeater intervals were not \
12632 enough to shift date past today. Continue? "
12633 nshift))
12634 (user-error "Abort")))
12635 (org-timestamp-change n (cdr (assoc what whata)))
12636 (org-in-regexp org-ts-regexp3)
12637 (setq ts (match-string 1))
12638 (setq time
12639 (save-match-data
12640 (org-time-string-to-time ts)))))
12641 (org-timestamp-change (- n) (cdr (assoc what whata)))
12642 ;; Rematch, so that we have everything in place
12643 ;; for the real shift.
12644 (org-in-regexp org-ts-regexp3)
12645 (setq ts (match-string 1))
12646 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12647 ts)))))
12648 (save-excursion
12649 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12650 (setq msg
12651 (concat
12652 msg type " " org-last-changed-timestamp " "))))))))
12653 (setq org-log-post-message msg)
12654 (message "%s" msg))
12655 (set-marker end nil))))
12657 (defun org-show-todo-tree (arg)
12658 "Make a compact tree which shows all headlines marked with TODO.
12659 The tree will show the lines where the regexp matches, and all higher
12660 headlines above the match.
12661 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12662 With a numeric prefix N, construct a sparse tree for the Nth element
12663 of `org-todo-keywords-1'."
12664 (interactive "P")
12665 (let ((case-fold-search nil)
12666 (kwd-re
12667 (cond ((null arg) org-not-done-regexp)
12668 ((equal arg '(4))
12669 (let ((kwd
12670 (completing-read "Keyword (or KWD1|KWD2|...): "
12671 (mapcar #'list org-todo-keywords-1))))
12672 (concat "\\("
12673 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12674 "\\)\\>")))
12675 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12676 (regexp-quote (nth (1- (prefix-numeric-value arg))
12677 org-todo-keywords-1)))
12678 (t (user-error "Invalid prefix argument: %s" arg)))))
12679 (message "%d TODO entries found"
12680 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12682 (defun org--deadline-or-schedule (arg type time)
12683 "Insert DEADLINE or SCHEDULE information in current entry.
12684 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12685 `org-schedule' for information about ARG and TIME arguments."
12686 (let* ((deadline? (eq type 'deadline))
12687 (keyword (if deadline? org-deadline-string org-scheduled-string))
12688 (log (if deadline? org-log-redeadline org-log-reschedule))
12689 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12690 (old-date-time (and old-date (org-time-string-to-time old-date)))
12691 ;; Save repeater cookie from either TIME or current scheduled
12692 ;; time stamp. We are going to insert it back at the end of
12693 ;; the process.
12694 (repeater (or (and (org-string-nw-p time)
12695 ;; We use `org-repeat-re' because we need
12696 ;; to tell the difference between a real
12697 ;; repeater and a time delta, e.g. "+2d".
12698 (string-match org-repeat-re time)
12699 (match-string 1 time))
12700 (and (org-string-nw-p old-date)
12701 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12702 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12703 old-date)
12704 (match-string 1 old-date)))))
12705 (pcase arg
12706 (`(4)
12707 (when (and old-date log)
12708 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12709 nil old-date log))
12710 (org-remove-timestamp-with-keyword keyword)
12711 (message (if deadline? "Item no longer has a deadline."
12712 "Item is no longer scheduled.")))
12713 (`(16)
12714 (save-excursion
12715 (org-back-to-heading t)
12716 (let ((regexp (if deadline? org-deadline-time-regexp
12717 org-scheduled-time-regexp)))
12718 (if (not (re-search-forward regexp (line-end-position 2) t))
12719 (user-error (if deadline? "No deadline information to update"
12720 "No scheduled information to update"))
12721 (let* ((rpl0 (match-string 1))
12722 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12723 (msg (if deadline? "Warn starting from" "Delay until")))
12724 (replace-match
12725 (concat keyword
12726 " <" rpl
12727 (format " -%dd"
12728 (abs (- (time-to-days
12729 (save-match-data
12730 (org-read-date
12731 nil t nil msg old-date-time)))
12732 (time-to-days old-date-time))))
12733 ">") t t))))))
12735 (org-add-planning-info type time 'closed)
12736 (when (and old-date
12738 (not (equal old-date org-last-inserted-timestamp)))
12739 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12740 org-last-inserted-timestamp
12741 old-date
12742 log))
12743 (when repeater
12744 (save-excursion
12745 (org-back-to-heading t)
12746 (when (re-search-forward
12747 (concat keyword " " org-last-inserted-timestamp)
12748 (line-end-position 2)
12750 (goto-char (1- (match-end 0)))
12751 (insert " " repeater)
12752 (setq org-last-inserted-timestamp
12753 (concat (substring org-last-inserted-timestamp 0 -1)
12754 " " repeater
12755 (substring org-last-inserted-timestamp -1))))))
12756 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12757 org-last-inserted-timestamp)))))
12759 (defun org-deadline (arg &optional time)
12760 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12761 With one universal prefix argument, remove any deadline from the item.
12762 With two universal prefix arguments, prompt for a warning delay.
12763 With argument TIME, set the deadline at the corresponding date. TIME
12764 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12765 (interactive "P")
12766 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12767 (org-map-entries
12768 (lambda () (org--deadline-or-schedule arg 'deadline time))
12770 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12771 'region-start-level
12772 'region)
12773 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12774 (org--deadline-or-schedule arg 'deadline time)))
12776 (defun org-schedule (arg &optional time)
12777 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12778 With one universal prefix argument, remove any scheduling date from the item.
12779 With two universal prefix arguments, prompt for a delay cookie.
12780 With argument TIME, scheduled at the corresponding date. TIME can
12781 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12782 (interactive "P")
12783 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12784 (org-map-entries
12785 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12787 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12788 'region-start-level
12789 'region)
12790 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12791 (org--deadline-or-schedule arg 'scheduled time)))
12793 (defun org-get-scheduled-time (pom &optional inherit)
12794 "Get the scheduled time as a time tuple, of a format suitable
12795 for calling org-schedule with, or if there is no scheduling,
12796 returns nil."
12797 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12798 (when time
12799 (apply 'encode-time (org-parse-time-string time)))))
12801 (defun org-get-deadline-time (pom &optional inherit)
12802 "Get the deadline as a time tuple, of a format suitable for
12803 calling org-deadline with, or if there is no scheduling, returns
12804 nil."
12805 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12806 (when time
12807 (apply 'encode-time (org-parse-time-string time)))))
12809 (defun org-remove-timestamp-with-keyword (keyword)
12810 "Remove all time stamps with KEYWORD in the current entry."
12811 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12812 beg)
12813 (save-excursion
12814 (org-back-to-heading t)
12815 (setq beg (point))
12816 (outline-next-heading)
12817 (while (re-search-backward re beg t)
12818 (replace-match "")
12819 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12820 (equal (char-before) ?\ ))
12821 (backward-delete-char 1)
12822 (when (string-match "^[ \t]*$" (buffer-substring
12823 (point-at-bol) (point-at-eol)))
12824 (delete-region (point-at-bol)
12825 (min (point-max) (1+ (point-at-eol))))))))))
12827 (defvar org-time-was-given) ; dynamically scoped parameter
12828 (defvar org-end-time-was-given) ; dynamically scoped parameter
12830 (defun org-at-planning-p ()
12831 "Non-nil when point is on a planning info line."
12832 ;; This is as accurate and faster than `org-element-at-point' since
12833 ;; planning info location is fixed in the section.
12834 (org-with-wide-buffer
12835 (beginning-of-line)
12836 (and (looking-at-p org-planning-line-re)
12837 (eq (point)
12838 (ignore-errors
12839 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12840 (org-back-to-heading t)
12841 (org-with-limited-levels (org-back-to-heading t)))
12842 (line-beginning-position 2))))))
12844 (defun org-add-planning-info (what &optional time &rest remove)
12845 "Insert new timestamp with keyword in the planning line.
12846 WHAT indicates what kind of time stamp to add. It is a symbol
12847 among `closed', `deadline', `scheduled' and nil. TIME indicates
12848 the time to use. If none is given, the user is prompted for
12849 a date. REMOVE indicates what kind of entries to remove. An old
12850 WHAT entry will also be removed."
12851 (let (org-time-was-given org-end-time-was-given default-time default-input)
12852 (catch 'exit
12853 (when (and (memq what '(scheduled deadline))
12854 (or (not time)
12855 (and (stringp time)
12856 (string-match "^[-+]+[0-9]" time))))
12857 ;; Try to get a default date/time from existing timestamp
12858 (save-excursion
12859 (org-back-to-heading t)
12860 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12861 (when (re-search-forward (if (eq what 'scheduled)
12862 org-scheduled-time-regexp
12863 org-deadline-time-regexp)
12864 end t)
12865 (setq ts (match-string 1)
12866 default-time (apply 'encode-time (org-parse-time-string ts))
12867 default-input (and ts (org-get-compact-tod ts)))))))
12868 (when what
12869 (setq time
12870 (if (stringp time)
12871 ;; This is a string (relative or absolute), set
12872 ;; proper date.
12873 (apply #'encode-time
12874 (org-read-date-analyze
12875 time default-time (decode-time default-time)))
12876 ;; If necessary, get the time from the user
12877 (or time (org-read-date nil 'to-time nil nil
12878 default-time default-input)))))
12880 (org-with-wide-buffer
12881 (org-back-to-heading t)
12882 (forward-line)
12883 (unless (bolp) (insert "\n"))
12884 (cond ((looking-at-p org-planning-line-re)
12885 ;; Move to current indentation.
12886 (skip-chars-forward " \t")
12887 ;; Check if we have to remove something.
12888 (dolist (type (if what (cons what remove) remove))
12889 (save-excursion
12890 (when (re-search-forward
12891 (cl-case type
12892 (closed org-closed-time-regexp)
12893 (deadline org-deadline-time-regexp)
12894 (scheduled org-scheduled-time-regexp)
12895 (otherwise
12896 (error "Invalid planning type: %s" type)))
12897 (line-end-position) t)
12898 ;; Delete until next keyword or end of line.
12899 (delete-region
12900 (match-beginning 0)
12901 (if (re-search-forward org-keyword-time-not-clock-regexp
12902 (line-end-position)
12904 (match-beginning 0)
12905 (line-end-position))))))
12906 ;; If there is nothing more to add and no more keyword
12907 ;; is left, remove the line completely.
12908 (if (and (looking-at-p "[ \t]*$") (not what))
12909 (delete-region (line-beginning-position)
12910 (line-beginning-position 2))
12911 ;; If we removed last keyword, do not leave trailing
12912 ;; white space at the end of line.
12913 (let ((p (point)))
12914 (save-excursion
12915 (end-of-line)
12916 (unless (= (skip-chars-backward " \t" p) 0)
12917 (delete-region (point) (line-end-position)))))))
12918 ((not what) (throw 'exit nil)) ; Nothing to do.
12919 (t (insert-before-markers "\n")
12920 (backward-char 1)
12921 (when org-adapt-indentation
12922 (indent-to-column (1+ (org-outline-level))))))
12923 (when what
12924 ;; Insert planning keyword.
12925 (insert (cl-case what
12926 (closed org-closed-string)
12927 (deadline org-deadline-string)
12928 (scheduled org-scheduled-string)
12929 (otherwise (error "Invalid planning type: %s" what)))
12930 " ")
12931 ;; Insert associated timestamp.
12932 (let ((ts (org-insert-time-stamp
12933 time
12934 (or org-time-was-given
12935 (and (eq what 'closed) org-log-done-with-time))
12936 (eq what 'closed)
12937 nil nil (list org-end-time-was-given))))
12938 (unless (eolp) (insert " "))
12939 ts))))))
12941 (defvar org-log-note-marker (make-marker)
12942 "Marker pointing at the entry where the note is to be inserted.")
12943 (defvar org-log-note-purpose nil)
12944 (defvar org-log-note-state nil)
12945 (defvar org-log-note-previous-state nil)
12946 (defvar org-log-note-extra nil)
12947 (defvar org-log-note-window-configuration nil)
12948 (defvar org-log-note-return-to (make-marker))
12949 (defvar org-log-note-effective-time nil
12950 "Remembered current time so that dynamically scoped
12951 `org-extend-today-until' affects timestamps in state change log")
12953 (defvar org-log-post-message nil
12954 "Message to be displayed after a log note has been stored.
12955 The auto-repeater uses this.")
12957 (defun org-add-note ()
12958 "Add a note to the current entry.
12959 This is done in the same way as adding a state change note."
12960 (interactive)
12961 (org-add-log-setup 'note))
12963 (defun org-log-beginning (&optional create)
12964 "Return expected start of log notes in current entry.
12965 When optional argument CREATE is non-nil, the function creates
12966 a drawer to store notes, if necessary. Returned position ignores
12967 narrowing."
12968 (org-with-wide-buffer
12969 (let ((drawer (org-log-into-drawer)))
12970 (cond
12971 (drawer
12972 (org-end-of-meta-data)
12973 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
12974 (end (if (org-at-heading-p) (point)
12975 (save-excursion (outline-next-heading) (point))))
12976 (case-fold-search t))
12977 (catch 'exit
12978 ;; Try to find existing drawer.
12979 (while (re-search-forward regexp end t)
12980 (let ((element (org-element-at-point)))
12981 (when (eq (org-element-type element) 'drawer)
12982 (let ((cend (org-element-property :contents-end element)))
12983 (when (and (not org-log-states-order-reversed) cend)
12984 (goto-char cend)))
12985 (throw 'exit nil))))
12986 ;; No drawer found. Create one, if permitted.
12987 (when create
12988 (unless (bolp) (insert "\n"))
12989 (let ((beg (point)))
12990 (insert ":" drawer ":\n:END:\n")
12991 (org-indent-region beg (point))
12992 (org-flag-region
12993 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
12994 (end-of-line -1)))))
12996 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
12997 (skip-chars-forward " \t\n")
12998 (beginning-of-line)
12999 (unless org-log-states-order-reversed
13000 (org-skip-over-state-notes)
13001 (skip-chars-backward " \t\n")
13002 (forward-line)))))
13003 (if (bolp) (point) (line-beginning-position 2))))
13005 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13006 "Set up the post command hook to take a note.
13007 If this is about to TODO state change, the new state is expected in STATE.
13008 HOW is an indicator what kind of note should be created.
13009 EXTRA is additional text that will be inserted into the notes buffer."
13010 (move-marker org-log-note-marker (point))
13011 (setq org-log-note-purpose purpose
13012 org-log-note-state state
13013 org-log-note-previous-state prev-state
13014 org-log-note-how how
13015 org-log-note-extra extra
13016 org-log-note-effective-time (org-current-effective-time))
13017 (add-hook 'post-command-hook 'org-add-log-note 'append))
13019 (defun org-skip-over-state-notes ()
13020 "Skip past the list of State notes in an entry."
13021 (when (ignore-errors (goto-char (org-in-item-p)))
13022 (let* ((struct (org-list-struct))
13023 (prevs (org-list-prevs-alist struct))
13024 (regexp
13025 (concat "[ \t]*- +"
13026 (replace-regexp-in-string
13027 " +" " +"
13028 (org-replace-escapes
13029 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13030 `(("%d" . ,org-ts-regexp-inactive)
13031 ("%D" . ,org-ts-regexp)
13032 ("%s" . "\"\\S-+\"")
13033 ("%S" . "\"\\S-+\"")
13034 ("%t" . ,org-ts-regexp-inactive)
13035 ("%T" . ,org-ts-regexp)
13036 ("%u" . ".*?")
13037 ("%U" . ".*?")))))))
13038 (while (looking-at-p regexp)
13039 (goto-char (or (org-list-get-next-item (point) struct prevs)
13040 (org-list-get-item-end (point) struct)))))))
13042 (defun org-add-log-note (&optional _purpose)
13043 "Pop up a window for taking a note, and add this note later."
13044 (remove-hook 'post-command-hook 'org-add-log-note)
13045 (setq org-log-note-window-configuration (current-window-configuration))
13046 (delete-other-windows)
13047 (move-marker org-log-note-return-to (point))
13048 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13049 (goto-char org-log-note-marker)
13050 (org-switch-to-buffer-other-window "*Org Note*")
13051 (erase-buffer)
13052 (if (memq org-log-note-how '(time state))
13053 (org-store-log-note)
13054 (let ((org-inhibit-startup t)) (org-mode))
13055 (insert (format "# Insert note for %s.
13056 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13057 (cond
13058 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13059 ((eq org-log-note-purpose 'done) "closed todo item")
13060 ((eq org-log-note-purpose 'state)
13061 (format "state change from \"%s\" to \"%s\""
13062 (or org-log-note-previous-state "")
13063 (or org-log-note-state "")))
13064 ((eq org-log-note-purpose 'reschedule)
13065 "rescheduling")
13066 ((eq org-log-note-purpose 'delschedule)
13067 "no longer scheduled")
13068 ((eq org-log-note-purpose 'redeadline)
13069 "changing deadline")
13070 ((eq org-log-note-purpose 'deldeadline)
13071 "removing deadline")
13072 ((eq org-log-note-purpose 'refile)
13073 "refiling")
13074 ((eq org-log-note-purpose 'note)
13075 "this entry")
13076 (t (error "This should not happen")))))
13077 (when org-log-note-extra (insert org-log-note-extra))
13078 (setq-local org-finish-function 'org-store-log-note)
13079 (run-hooks 'org-log-buffer-setup-hook)))
13081 (defvar org-note-abort nil) ; dynamically scoped
13082 (defun org-store-log-note ()
13083 "Finish taking a log note, and insert it to where it belongs."
13084 (let ((txt (prog1 (buffer-string)
13085 (kill-buffer)))
13086 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13087 lines)
13088 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13089 (setq txt (replace-match "" t t txt)))
13090 (when (string-match "\\s-+\\'" txt)
13091 (setq txt (replace-match "" t t txt)))
13092 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13093 (when (org-string-nw-p note)
13094 (setq note
13095 (org-replace-escapes
13096 note
13097 (list (cons "%u" (user-login-name))
13098 (cons "%U" user-full-name)
13099 (cons "%t" (format-time-string
13100 (org-time-stamp-format 'long 'inactive)
13101 org-log-note-effective-time))
13102 (cons "%T" (format-time-string
13103 (org-time-stamp-format 'long nil)
13104 org-log-note-effective-time))
13105 (cons "%d" (format-time-string
13106 (org-time-stamp-format nil 'inactive)
13107 org-log-note-effective-time))
13108 (cons "%D" (format-time-string
13109 (org-time-stamp-format nil nil)
13110 org-log-note-effective-time))
13111 (cons "%s" (cond
13112 ((not org-log-note-state) "")
13113 ((string-match-p org-ts-regexp
13114 org-log-note-state)
13115 (format "\"[%s]\""
13116 (substring org-log-note-state 1 -1)))
13117 (t (format "\"%s\"" org-log-note-state))))
13118 (cons "%S"
13119 (cond
13120 ((not org-log-note-previous-state) "")
13121 ((string-match-p org-ts-regexp
13122 org-log-note-previous-state)
13123 (format "\"[%s]\""
13124 (substring
13125 org-log-note-previous-state 1 -1)))
13126 (t (format "\"%s\""
13127 org-log-note-previous-state)))))))
13128 (when lines (setq note (concat note " \\\\")))
13129 (push note lines))
13130 (when (and lines (not org-note-abort))
13131 (with-current-buffer (marker-buffer org-log-note-marker)
13132 (org-with-wide-buffer
13133 ;; Find location for the new note.
13134 (goto-char org-log-note-marker)
13135 (set-marker org-log-note-marker nil)
13136 ;; Note associated to a clock is to be located right after
13137 ;; the clock. Do not move point.
13138 (unless (eq org-log-note-purpose 'clock-out)
13139 (goto-char (org-log-beginning t)))
13140 ;; Make sure point is at the beginning of an empty line.
13141 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13142 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13143 ;; In an existing list, add a new item at the top level.
13144 ;; Otherwise, indent line like a regular one.
13145 (let ((itemp (org-in-item-p)))
13146 (if itemp
13147 (indent-line-to
13148 (let ((struct (save-excursion
13149 (goto-char itemp) (org-list-struct))))
13150 (org-list-get-ind (org-list-get-top-point struct) struct)))
13151 (org-indent-line)))
13152 (insert (org-list-bullet-string "-") (pop lines))
13153 (let ((ind (org-list-item-body-column (line-beginning-position))))
13154 (dolist (line lines)
13155 (insert "\n")
13156 (indent-line-to ind)
13157 (insert line)))
13158 (message "Note stored")
13159 (org-back-to-heading t))
13160 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13161 ;; from within `org-add-log-note' because `buffer-undo-list'
13162 ;; is then modified outside of `org-with-remote-undo'.
13163 (when (eq this-command 'org-agenda-todo)
13164 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13165 ;; Don't add undo information when called from `org-agenda-todo'.
13166 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13167 (set-window-configuration org-log-note-window-configuration)
13168 (with-current-buffer (marker-buffer org-log-note-return-to)
13169 (goto-char org-log-note-return-to))
13170 (move-marker org-log-note-return-to nil)
13171 (when org-log-post-message (message "%s" org-log-post-message))))
13173 (defun org-remove-empty-drawer-at (pos)
13174 "Remove an empty drawer at position POS.
13175 POS may also be a marker."
13176 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13177 (org-with-wide-buffer
13178 (goto-char pos)
13179 (let ((drawer (org-element-at-point)))
13180 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13181 (not (org-element-property :contents-begin drawer)))
13182 (delete-region (org-element-property :begin drawer)
13183 (progn (goto-char (org-element-property :end drawer))
13184 (skip-chars-backward " \r\t\n")
13185 (forward-line)
13186 (point))))))))
13188 (defvar org-ts-type nil)
13189 (defun org-sparse-tree (&optional arg type)
13190 "Create a sparse tree, prompt for the details.
13191 This command can create sparse trees. You first need to select the type
13192 of match used to create the tree:
13194 t Show all TODO entries.
13195 T Show entries with a specific TODO keyword.
13196 m Show entries selected by a tags/property match.
13197 p Enter a property name and its value (both with completion on existing
13198 names/values) and show entries with that property.
13199 r Show entries matching a regular expression (`/' can be used as well).
13200 b Show deadlines and scheduled items before a date.
13201 a Show deadlines and scheduled items after a date.
13202 d Show deadlines due within `org-deadline-warning-days'.
13203 D Show deadlines and scheduled items between a date range."
13204 (interactive "P")
13205 (setq type (or type org-sparse-tree-default-date-type))
13206 (setq org-ts-type type)
13207 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13208 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13209 \[c]ycle through date types: %s"
13210 (cl-case type
13211 (all "all timestamps")
13212 (scheduled "only scheduled")
13213 (deadline "only deadline")
13214 (active "only active timestamps")
13215 (inactive "only inactive timestamps")
13216 (closed "with a closed time-stamp")
13217 (otherwise "scheduled/deadline")))
13218 (let ((answer (read-char-exclusive)))
13219 (cl-case answer
13221 (org-sparse-tree
13223 (cadr
13224 (memq type '(nil all scheduled deadline active inactive closed)))))
13225 (?d (call-interactively 'org-check-deadlines))
13226 (?b (call-interactively 'org-check-before-date))
13227 (?a (call-interactively 'org-check-after-date))
13228 (?D (call-interactively 'org-check-dates-range))
13229 (?t (call-interactively 'org-show-todo-tree))
13230 (?T (org-show-todo-tree '(4)))
13231 (?m (call-interactively 'org-match-sparse-tree))
13232 ((?p ?P)
13233 (let* ((kwd (completing-read
13234 "Property: " (mapcar #'list (org-buffer-property-keys))))
13235 (value (completing-read
13236 "Value: " (mapcar #'list (org-property-values kwd)))))
13237 (unless (string-match "\\`{.*}\\'" value)
13238 (setq value (concat "\"" value "\"")))
13239 (org-match-sparse-tree arg (concat kwd "=" value))))
13240 ((?r ?R ?/) (call-interactively 'org-occur))
13241 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13243 (defvar-local org-occur-highlights nil
13244 "List of overlays used for occur matches.")
13245 (defvar-local org-occur-parameters nil
13246 "Parameters of the active org-occur calls.
13247 This is a list, each call to org-occur pushes as cons cell,
13248 containing the regular expression and the callback, onto the list.
13249 The list can contain several entries if `org-occur' has been called
13250 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13251 will only contain one set of parameters. When the highlights are
13252 removed (for example with `C-c C-c', or with the next edit (depending
13253 on `org-remove-highlights-with-change'), this variable is emptied
13254 as well.")
13256 (defun org-occur (regexp &optional keep-previous callback)
13257 "Make a compact tree which shows all matches of REGEXP.
13259 The tree will show the lines where the regexp matches, and any other context
13260 defined in `org-show-context-detail', which see.
13262 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13263 done by a previous call to `org-occur' will be kept, to allow stacking of
13264 calls to this command.
13266 Optional argument CALLBACK can be a function of no argument. In this case,
13267 it is called with point at the end of the match, match data being set
13268 accordingly. Current match is shown only if the return value is non-nil.
13269 The function must neither move point nor alter narrowing."
13270 (interactive "sRegexp: \nP")
13271 (when (equal regexp "")
13272 (user-error "Regexp cannot be empty"))
13273 (unless keep-previous
13274 (org-remove-occur-highlights nil nil t))
13275 (push (cons regexp callback) org-occur-parameters)
13276 (let ((cnt 0))
13277 (save-excursion
13278 (goto-char (point-min))
13279 (when (or (not keep-previous) ; do not want to keep
13280 (not org-occur-highlights)) ; no previous matches
13281 ;; hide everything
13282 (org-overview))
13283 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13284 (isearch-no-upper-case-p regexp t)
13285 org-occur-case-fold-search)))
13286 (while (re-search-forward regexp nil t)
13287 (when (or (not callback)
13288 (save-match-data (funcall callback)))
13289 (setq cnt (1+ cnt))
13290 (when org-highlight-sparse-tree-matches
13291 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13292 (org-show-context 'occur-tree)))))
13293 (when org-remove-highlights-with-change
13294 (add-hook 'before-change-functions 'org-remove-occur-highlights
13295 nil 'local))
13296 (unless org-sparse-tree-open-archived-trees
13297 (org-hide-archived-subtrees (point-min) (point-max)))
13298 (run-hooks 'org-occur-hook)
13299 (when (called-interactively-p 'interactive)
13300 (message "%d match(es) for regexp %s" cnt regexp))
13301 cnt))
13303 (defun org-occur-next-match (&optional n _reset)
13304 "Function for `next-error-function' to find sparse tree matches.
13305 N is the number of matches to move, when negative move backwards.
13306 This function always goes back to the starting point when no
13307 match is found."
13308 (let* ((limit (if (< n 0) (point-min) (point-max)))
13309 (search-func (if (< n 0)
13310 'previous-single-char-property-change
13311 'next-single-char-property-change))
13312 (n (abs n))
13313 (pos (point))
13315 (catch 'exit
13316 (while (setq p1 (funcall search-func (point) 'org-type))
13317 (when (equal p1 limit)
13318 (goto-char pos)
13319 (user-error "No more matches"))
13320 (when (equal (get-char-property p1 'org-type) 'org-occur)
13321 (setq n (1- n))
13322 (when (= n 0)
13323 (goto-char p1)
13324 (throw 'exit (point))))
13325 (goto-char p1))
13326 (goto-char p1)
13327 (user-error "No more matches"))))
13329 (defun org-highlight-new-match (beg end)
13330 "Highlight from BEG to END and mark the highlight is an occur headline."
13331 (let ((ov (make-overlay beg end)))
13332 (overlay-put ov 'face 'secondary-selection)
13333 (overlay-put ov 'org-type 'org-occur)
13334 (push ov org-occur-highlights)))
13336 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13337 "Remove the occur highlights from the buffer.
13338 BEG and END are ignored. If NOREMOVE is nil, remove this function
13339 from the `before-change-functions' in the current buffer."
13340 (interactive)
13341 (unless org-inhibit-highlight-removal
13342 (mapc #'delete-overlay org-occur-highlights)
13343 (setq org-occur-highlights nil)
13344 (setq org-occur-parameters nil)
13345 (unless noremove
13346 (remove-hook 'before-change-functions
13347 'org-remove-occur-highlights 'local))))
13349 ;;;; Priorities
13351 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13352 "Regular expression matching the priority indicator.")
13354 (defvar org-remove-priority-next-time nil)
13356 (defun org-priority-up ()
13357 "Increase the priority of the current item."
13358 (interactive)
13359 (org-priority 'up))
13361 (defun org-priority-down ()
13362 "Decrease the priority of the current item."
13363 (interactive)
13364 (org-priority 'down))
13366 (defun org-priority (&optional action _show)
13367 "Change the priority of an item.
13368 ACTION can be `set', `up', `down', or a character."
13369 (interactive "P")
13370 (if (equal action '(4))
13371 (org-show-priority)
13372 (unless org-enable-priority-commands
13373 (user-error "Priority commands are disabled"))
13374 (setq action (or action 'set))
13375 (let (current new news have remove)
13376 (save-excursion
13377 (org-back-to-heading t)
13378 (when (looking-at org-priority-regexp)
13379 (setq current (string-to-char (match-string 2))
13380 have t))
13381 (cond
13382 ((eq action 'remove)
13383 (setq remove t new ?\ ))
13384 ((or (eq action 'set)
13385 (integerp action))
13386 (if (not (eq action 'set))
13387 (setq new action)
13388 (message "Priority %c-%c, SPC to remove: "
13389 org-highest-priority org-lowest-priority)
13390 (save-match-data
13391 (setq new (read-char-exclusive))))
13392 (when (and (= (upcase org-highest-priority) org-highest-priority)
13393 (= (upcase org-lowest-priority) org-lowest-priority))
13394 (setq new (upcase new)))
13395 (cond ((equal new ?\ ) (setq remove t))
13396 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13397 (user-error "Priority must be between `%c' and `%c'"
13398 org-highest-priority org-lowest-priority))))
13399 ((eq action 'up)
13400 (setq new (if have
13401 (1- current) ; normal cycling
13402 ;; last priority was empty
13403 (if (eq last-command this-command)
13404 org-lowest-priority ; wrap around empty to lowest
13405 ;; default
13406 (if org-priority-start-cycle-with-default
13407 org-default-priority
13408 (1- org-default-priority))))))
13409 ((eq action 'down)
13410 (setq new (if have
13411 (1+ current) ; normal cycling
13412 ;; last priority was empty
13413 (if (eq last-command this-command)
13414 org-highest-priority ; wrap around empty to highest
13415 ;; default
13416 (if org-priority-start-cycle-with-default
13417 org-default-priority
13418 (1+ org-default-priority))))))
13419 (t (user-error "Invalid action")))
13420 (when (or (< (upcase new) org-highest-priority)
13421 (> (upcase new) org-lowest-priority))
13422 (if (and (memq action '(up down))
13423 (not have) (not (eq last-command this-command)))
13424 ;; `new' is from default priority
13425 (error
13426 "The default can not be set, see `org-default-priority' why")
13427 ;; normal cycling: `new' is beyond highest/lowest priority
13428 ;; and is wrapped around to the empty priority
13429 (setq remove t)))
13430 (setq news (format "%c" new))
13431 (if have
13432 (if remove
13433 (replace-match "" t t nil 1)
13434 (replace-match news t t nil 2))
13435 (if remove
13436 (user-error "No priority cookie found in line")
13437 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13438 (if (match-end 2)
13439 (progn
13440 (goto-char (match-end 2))
13441 (insert " [#" news "]"))
13442 (goto-char (match-beginning 3))
13443 (insert "[#" news "] "))))
13444 (org-set-tags nil 'align))
13445 (if remove
13446 (message "Priority removed")
13447 (message "Priority of current item set to %s" news)))))
13449 (defun org-show-priority ()
13450 "Show the priority of the current item.
13451 This priority is composed of the main priority given with the [#A] cookies,
13452 and by additional input from the age of a schedules or deadline entry."
13453 (interactive)
13454 (let ((pri (if (eq major-mode 'org-agenda-mode)
13455 (org-get-at-bol 'priority)
13456 (save-excursion
13457 (save-match-data
13458 (beginning-of-line)
13459 (and (looking-at org-heading-regexp)
13460 (org-get-priority (match-string 0))))))))
13461 (message "Priority is %d" (if pri pri -1000))))
13463 (defun org-get-priority (s)
13464 "Find priority cookie and return priority."
13465 (save-match-data
13466 (if (functionp org-get-priority-function)
13467 (funcall org-get-priority-function)
13468 (if (not (string-match org-priority-regexp s))
13469 (* 1000 (- org-lowest-priority org-default-priority))
13470 (* 1000 (- org-lowest-priority
13471 (string-to-char (match-string 2 s))))))))
13473 ;;;; Tags
13475 (defvar org-agenda-archives-mode)
13476 (defvar org-map-continue-from nil
13477 "Position from where mapping should continue.
13478 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13480 (defvar org-scanner-tags nil
13481 "The current tag list while the tags scanner is running.")
13483 (defvar org-trust-scanner-tags nil
13484 "Should `org-get-tags-at' use the tags for the scanner.
13485 This is for internal dynamical scoping only.
13486 When this is non-nil, the function `org-get-tags-at' will return the value
13487 of `org-scanner-tags' instead of building the list by itself. This
13488 can lead to large speed-ups when the tags scanner is used in a file with
13489 many entries, and when the list of tags is retrieved, for example to
13490 obtain a list of properties. Building the tags list for each entry in such
13491 a file becomes an N^2 operation - but with this variable set, it scales
13492 as N.")
13494 (defvar org--matcher-tags-todo-only nil)
13496 (defun org-scan-tags (action matcher todo-only &optional start-level)
13497 "Scan headline tags with inheritance and produce output ACTION.
13499 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13500 or `agenda' to produce an entry list for an agenda view. It can also be
13501 a Lisp form or a function that should be called at each matched headline, in
13502 this case the return value is a list of all return values from these calls.
13504 MATCHER is a function accepting three arguments, returning
13505 a non-nil value whenever a given set of tags qualifies a headline
13506 for inclusion. See `org-make-tags-matcher' for more information.
13507 As a special case, it can also be set to t (respectively nil) in
13508 order to match all (respectively none) headline.
13510 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13511 included in the output.
13513 START-LEVEL can be a string with asterisks, reducing the scope to
13514 headlines matching this string."
13515 (require 'org-agenda)
13516 (let* ((re (concat "^"
13517 (if start-level
13518 ;; Get the correct level to match
13519 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13520 org-outline-regexp)
13521 " *\\(\\<\\("
13522 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13523 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13524 (props (list 'face 'default
13525 'done-face 'org-agenda-done
13526 'undone-face 'default
13527 'mouse-face 'highlight
13528 'org-not-done-regexp org-not-done-regexp
13529 'org-todo-regexp org-todo-regexp
13530 'org-complex-heading-regexp org-complex-heading-regexp
13531 'help-echo
13532 (format "mouse-2 or RET jump to Org file %S"
13533 (abbreviate-file-name
13534 (or (buffer-file-name (buffer-base-buffer))
13535 (buffer-name (buffer-base-buffer)))))))
13536 (org-map-continue-from nil)
13537 lspos tags tags-list
13538 (tags-alist (list (cons 0 org-file-tags)))
13539 (llast 0) rtn rtn1 level category i txt
13540 todo marker entry priority
13541 ts-date ts-date-type ts-date-pair)
13542 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13543 (setq action (list 'lambda nil action)))
13544 (save-excursion
13545 (goto-char (point-min))
13546 (when (eq action 'sparse-tree)
13547 (org-overview)
13548 (org-remove-occur-highlights))
13549 (while (let (case-fold-search)
13550 (re-search-forward re nil t))
13551 (setq org-map-continue-from nil)
13552 (catch :skip
13553 (setq todo
13554 ;; TODO: is the 1-2 difference a bug?
13555 (when (match-end 1) (match-string-no-properties 2))
13556 tags (when (match-end 4) (match-string-no-properties 4)))
13557 (goto-char (setq lspos (match-beginning 0)))
13558 (setq level (org-reduced-level (org-outline-level))
13559 category (org-get-category))
13560 (when (eq action 'agenda)
13561 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13562 ts-date (car ts-date-pair)
13563 ts-date-type (cdr ts-date-pair)))
13564 (setq i llast llast level)
13565 ;; remove tag lists from same and sublevels
13566 (while (>= i level)
13567 (when (setq entry (assoc i tags-alist))
13568 (setq tags-alist (delete entry tags-alist)))
13569 (setq i (1- i)))
13570 ;; add the next tags
13571 (when tags
13572 (setq tags (org-split-string tags ":")
13573 tags-alist
13574 (cons (cons level tags) tags-alist)))
13575 ;; compile tags for current headline
13576 (setq tags-list
13577 (if org-use-tag-inheritance
13578 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13579 tags)
13580 org-scanner-tags tags-list)
13581 (when org-use-tag-inheritance
13582 (setcdr (car tags-alist)
13583 (mapcar (lambda (x)
13584 (setq x (copy-sequence x))
13585 (org-add-prop-inherited x))
13586 (cdar tags-alist))))
13587 (when (and tags org-use-tag-inheritance
13588 (or (not (eq t org-use-tag-inheritance))
13589 org-tags-exclude-from-inheritance))
13590 ;; Selective inheritance, remove uninherited ones.
13591 (setcdr (car tags-alist)
13592 (org-remove-uninherited-tags (cdar tags-alist))))
13593 (when (and
13595 ;; eval matcher only when the todo condition is OK
13596 (and (or (not todo-only) (member todo org-todo-keywords-1))
13597 (if (functionp matcher)
13598 (let ((case-fold-search t) (org-trust-scanner-tags t))
13599 (funcall matcher todo tags-list level))
13600 matcher))
13602 ;; Call the skipper, but return t if it does not
13603 ;; skip, so that the `and' form continues evaluating.
13604 (progn
13605 (unless (eq action 'sparse-tree) (org-agenda-skip))
13608 ;; Check if timestamps are deselecting this entry
13609 (or (not todo-only)
13610 (and (member todo org-todo-keywords-1)
13611 (or (not org-agenda-tags-todo-honor-ignore-options)
13612 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13614 ;; select this headline
13615 (cond
13616 ((eq action 'sparse-tree)
13617 (and org-highlight-sparse-tree-matches
13618 (org-get-heading) (match-end 0)
13619 (org-highlight-new-match
13620 (match-beginning 1) (match-end 1)))
13621 (org-show-context 'tags-tree))
13622 ((eq action 'agenda)
13623 (setq txt (org-agenda-format-item
13625 (concat
13626 (if (eq org-tags-match-list-sublevels 'indented)
13627 (make-string (1- level) ?.) "")
13628 (org-get-heading))
13629 (make-string level ?\s)
13630 category
13631 tags-list)
13632 priority (org-get-priority txt))
13633 (goto-char lspos)
13634 (setq marker (org-agenda-new-marker))
13635 (org-add-props txt props
13636 'org-marker marker 'org-hd-marker marker 'org-category category
13637 'todo-state todo
13638 'ts-date ts-date
13639 'priority priority
13640 'type (concat "tagsmatch" ts-date-type))
13641 (push txt rtn))
13642 ((functionp action)
13643 (setq org-map-continue-from nil)
13644 (save-excursion
13645 (setq rtn1 (funcall action))
13646 (push rtn1 rtn)))
13647 (t (user-error "Invalid action")))
13649 ;; if we are to skip sublevels, jump to end of subtree
13650 (unless org-tags-match-list-sublevels
13651 (org-end-of-subtree t)
13652 (backward-char 1))))
13653 ;; Get the correct position from where to continue
13654 (if org-map-continue-from
13655 (goto-char org-map-continue-from)
13656 (and (= (point) lspos) (end-of-line 1)))))
13657 (when (and (eq action 'sparse-tree)
13658 (not org-sparse-tree-open-archived-trees))
13659 (org-hide-archived-subtrees (point-min) (point-max)))
13660 (nreverse rtn)))
13662 (defun org-remove-uninherited-tags (tags)
13663 "Remove all tags that are not inherited from the list TAGS."
13664 (cond
13665 ((eq org-use-tag-inheritance t)
13666 (if org-tags-exclude-from-inheritance
13667 (org-delete-all org-tags-exclude-from-inheritance tags)
13668 tags))
13669 ((not org-use-tag-inheritance) nil)
13670 ((stringp org-use-tag-inheritance)
13671 (delq nil (mapcar
13672 (lambda (x)
13673 (if (and (string-match org-use-tag-inheritance x)
13674 (not (member x org-tags-exclude-from-inheritance)))
13675 x nil))
13676 tags)))
13677 ((listp org-use-tag-inheritance)
13678 (delq nil (mapcar
13679 (lambda (x)
13680 (if (member x org-use-tag-inheritance) x nil))
13681 tags)))))
13683 (defun org-match-sparse-tree (&optional todo-only match)
13684 "Create a sparse tree according to tags string MATCH.
13686 MATCH is a string with match syntax. It can contain a selection
13687 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13688 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13689 those. See the manual for details.
13691 If optional argument TODO-ONLY is non-nil, only select lines that
13692 are also TODO tasks."
13693 (interactive "P")
13694 (org-agenda-prepare-buffers (list (current-buffer)))
13695 (let ((org--matcher-tags-todo-only todo-only))
13696 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13697 org--matcher-tags-todo-only)))
13699 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13701 (defvar org-cached-props nil)
13702 (defun org-cached-entry-get (pom property)
13703 (if (or (eq t org-use-property-inheritance)
13704 (and (stringp org-use-property-inheritance)
13705 (let ((case-fold-search t))
13706 (string-match-p org-use-property-inheritance property)))
13707 (and (listp org-use-property-inheritance)
13708 (member-ignore-case property org-use-property-inheritance)))
13709 ;; Caching is not possible, check it directly.
13710 (org-entry-get pom property 'inherit)
13711 ;; Get all properties, so we can do complicated checks easily.
13712 (cdr (assoc-string property
13713 (or org-cached-props
13714 (setq org-cached-props (org-entry-properties pom)))
13715 t))))
13717 (defun org-global-tags-completion-table (&optional files)
13718 "Return the list of all tags in all agenda buffer/files.
13719 Optional FILES argument is a list of files which can be used
13720 instead of the agenda files."
13721 (save-excursion
13722 (org-uniquify
13723 (delq nil
13724 (apply #'append
13725 (mapcar
13726 (lambda (file)
13727 (set-buffer (find-file-noselect file))
13728 (mapcar (lambda (x)
13729 (and (stringp (car-safe x))
13730 (list (car-safe x))))
13731 (or org-current-tag-alist (org-get-buffer-tags))))
13732 (if (car-safe files) files
13733 (org-agenda-files))))))))
13735 (defun org-make-tags-matcher (match)
13736 "Create the TAGS/TODO matcher form for the selection string MATCH.
13738 Returns a cons of the selection string MATCH and a function
13739 implementing the matcher.
13741 The matcher is to be called at an Org entry, with point on the
13742 headline, and returns non-nil if the entry matches the selection
13743 string MATCH. It must be called with three arguments: the TODO
13744 keyword at the entry (or nil if none), the list of all tags at
13745 the entry including inherited ones and the reduced level of the
13746 headline. Additionally, the category of the entry, if any, must
13747 be specified as the text property `org-category' on the headline.
13749 This function sets the variable `org--matcher-tags-todo-only' to
13750 a non-nil value if the matcher restricts matching to TODO
13751 entries, otherwise it is not touched.
13753 See also `org-scan-tags'."
13754 (unless match
13755 ;; Get a new match request, with completion against the global
13756 ;; tags table and the local tags in current buffer.
13757 (let ((org-last-tags-completion-table
13758 (org-uniquify
13759 (delq nil (append (org-get-buffer-tags)
13760 (org-global-tags-completion-table))))))
13761 (setq match
13762 (completing-read
13763 "Match: "
13764 'org-tags-completion-function nil nil nil 'org-tags-history))))
13766 (let ((match0 match)
13767 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
13768 (start 0)
13769 tagsmatch todomatch tagsmatcher todomatcher)
13771 ;; Expand group tags.
13772 (setq match (org-tags-expand match))
13774 ;; Check if there is a TODO part of this match, which would be the
13775 ;; part after a "/". To make sure that this slash is not part of
13776 ;; a property value to be matched against, we also check that
13777 ;; there is no / after that slash. First, find the last slash.
13778 (let ((s 0))
13779 (while (string-match "/+" match s)
13780 (setq start (match-beginning 0))
13781 (setq s (match-end 0))))
13782 (if (and (string-match "/+" match start)
13783 (not (string-match-p "\"" match start)))
13784 ;; Match contains also a TODO-matching request.
13785 (progn
13786 (setq tagsmatch (substring match 0 (match-beginning 0)))
13787 (setq todomatch (substring match (match-end 0)))
13788 (when (string-prefix-p "!" todomatch)
13789 (setq org--matcher-tags-todo-only t)
13790 (setq todomatch (substring todomatch 1)))
13791 (when (string-match "\\`\\s-*\\'" todomatch)
13792 (setq todomatch nil)))
13793 ;; Only matching tags.
13794 (setq tagsmatch match)
13795 (setq todomatch nil))
13797 ;; Make the tags matcher.
13798 (when (org-string-nw-p tagsmatch)
13799 (let ((orlist nil)
13800 (orterms (org-split-string tagsmatch "|"))
13801 term)
13802 (while (setq term (pop orterms))
13803 (while (and (equal (substring term -1) "\\") orterms)
13804 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13805 (while (string-match re term)
13806 (let* ((rest (substring term (match-end 0)))
13807 (minus (and (match-end 1)
13808 (equal (match-string 1 term) "-")))
13809 (tag (save-match-data
13810 (replace-regexp-in-string
13811 "\\\\-" "-" (match-string 2 term))))
13812 (regexp (eq (string-to-char tag) ?{))
13813 (levelp (match-end 4))
13814 (propp (match-end 5))
13816 (cond
13817 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13818 (levelp
13819 `(,(org-op-to-function (match-string 3 term))
13820 level
13821 ,(string-to-number (match-string 4 term))))
13822 (propp
13823 (let* ((gv (pcase (upcase (match-string 5 term))
13824 ("CATEGORY"
13825 '(get-text-property (point) 'org-category))
13826 ("TODO" 'todo)
13827 (p `(org-cached-entry-get nil ,p))))
13828 (pv (match-string 7 term))
13829 (regexp (eq (string-to-char pv) ?{))
13830 (strp (eq (string-to-char pv) ?\"))
13831 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13832 (po (org-op-to-function (match-string 6 term)
13833 (if timep 'time strp))))
13834 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13835 (when timep (setq pv (org-matcher-time pv)))
13836 (cond ((and regexp (eq po 'org<>))
13837 `(not (string-match ,pv (or ,gv ""))))
13838 (regexp `(string-match ,pv (or ,gv "")))
13839 (strp `(,po (or ,gv "") ,pv))
13841 `(,po
13842 (string-to-number (or ,gv ""))
13843 ,(string-to-number pv))))))
13844 (t `(member ,tag tags-list)))))
13845 (push (if minus `(not ,mm) mm) tagsmatcher)
13846 (setq term rest)))
13847 (push `(and ,@tagsmatcher) orlist)
13848 (setq tagsmatcher nil))
13849 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13851 ;; Make the TODO matcher.
13852 (when (org-string-nw-p todomatch)
13853 (let ((orlist nil))
13854 (dolist (term (org-split-string todomatch "|"))
13855 (while (string-match re term)
13856 (let* ((minus (and (match-end 1)
13857 (equal (match-string 1 term) "-")))
13858 (kwd (match-string 2 term))
13859 (regexp (eq (string-to-char kwd) ?{))
13860 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13861 `(equal todo ,kwd))))
13862 (push (if minus `(not ,mm) mm) todomatcher))
13863 (setq term (substring term (match-end 0))))
13864 (push (if (> (length todomatcher) 1)
13865 (cons 'and todomatcher)
13866 (car todomatcher))
13867 orlist)
13868 (setq todomatcher nil))
13869 (setq todomatcher (cons 'or orlist))))
13871 ;; Return the string and function of the matcher. If no
13872 ;; tags-specific or todo-specific matcher exists, match
13873 ;; everything.
13874 (let ((matcher (if (and tagsmatcher todomatcher)
13875 `(and ,tagsmatcher ,todomatcher)
13876 (or tagsmatcher todomatcher t))))
13877 (when org--matcher-tags-todo-only
13878 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
13879 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
13881 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
13882 "Expand group tags in MATCH.
13884 This replaces every group tag in MATCH with a regexp tag search.
13885 For example, a group tag \"Work\" defined as { Work : Lab Conf }
13886 will be replaced like this:
13888 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13889 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13890 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13892 Replacing by a regexp preserves the structure of the match.
13893 E.g., this expansion
13895 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
13897 will match anything tagged with \"Lab\" and \"Home\", or tagged
13898 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
13900 A group tag in MATCH can contain regular expressions of its own.
13901 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
13902 will be replaced like this:
13904 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
13906 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
13907 assumed to be a single group tag, and the function will return
13908 the list of tags in this group.
13910 When DOWNCASE is non-nil, expand downcased TAGS."
13911 (if org-group-tags
13912 (let* ((case-fold-search t)
13913 (stable org-mode-syntax-table)
13914 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
13915 (taggroups (if downcased
13916 (mapcar (lambda (tg) (mapcar #'downcase tg))
13917 taggroups)
13918 taggroups))
13919 (taggroups-keys (mapcar #'car taggroups))
13920 (return-match (if downcased (downcase match) match))
13921 (count 0)
13922 (work-already-expanded tags-already-expanded)
13923 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
13924 ;; @ and _ are allowed as word-components in tags.
13925 (modify-syntax-entry ?@ "w" stable)
13926 (modify-syntax-entry ?_ "w" stable)
13927 ;; Temporarily replace regexp-expressions in the match-expression.
13928 (while (string-match "{.+?}" return-match)
13929 (cl-incf count)
13930 (push (match-string 0 return-match) regexps-in-match)
13931 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
13932 (while (and taggroups-keys
13933 (with-syntax-table stable
13934 (string-match
13935 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
13936 (regexp-opt taggroups-keys) "\\>\\)")
13937 return-match)))
13938 (let* ((dir (match-string 1 return-match))
13939 (tag (match-string 2 return-match))
13940 (tag (if downcased (downcase tag) tag)))
13941 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
13942 (member tag work-already-expanded))
13943 (setq tags-in-group (assoc tag taggroups))
13944 (push tag work-already-expanded)
13945 ;; Recursively expand each tag in the group, if the tag hasn't
13946 ;; already been expanded. Restore the match-data after all recursive calls.
13947 (save-match-data
13948 (let (tags-expanded)
13949 (dolist (x (cdr tags-in-group))
13950 (if (and (member x taggroups-keys)
13951 (not (member x work-already-expanded)))
13952 (setq tags-expanded
13953 (delete-dups
13954 (append
13955 (org-tags-expand x t downcased
13956 work-already-expanded)
13957 tags-expanded)))
13958 (setq tags-expanded
13959 (append (list x) tags-expanded)))
13960 (setq work-already-expanded
13961 (delete-dups
13962 (append tags-expanded
13963 work-already-expanded))))
13964 (setq tags-in-group
13965 (delete-dups (cons (car tags-in-group)
13966 tags-expanded)))))
13967 ;; Filter tag-regexps from tags.
13968 (setq regexp-in-group-escaped
13969 (delq nil (mapcar (lambda (x)
13970 (if (stringp x)
13971 (and (equal "{" (substring x 0 1))
13972 (equal "}" (substring x -1))
13975 tags-in-group))
13976 regexp-in-group
13977 (mapcar (lambda (x)
13978 (substring x 1 -1))
13979 regexp-in-group-escaped)
13980 tags-in-group
13981 (delq nil (mapcar (lambda (x)
13982 (if (stringp x)
13983 (and (not (equal "{" (substring x 0 1)))
13984 (not (equal "}" (substring x -1)))
13987 tags-in-group)))
13988 ;; If single-as-list, do no more in the while-loop.
13989 (if (not single-as-list)
13990 (progn
13991 (when regexp-in-group
13992 (setq regexp-in-group
13993 (concat "\\|"
13994 (mapconcat 'identity regexp-in-group
13995 "\\|"))))
13996 (setq tags-in-group
13997 (concat dir
13998 "{\\<"
13999 (regexp-opt tags-in-group)
14000 "\\>"
14001 regexp-in-group
14002 "}"))
14003 (when (stringp tags-in-group)
14004 (org-add-props tags-in-group '(grouptag t)))
14005 (setq return-match
14006 (replace-match tags-in-group t t return-match)))
14007 (setq tags-in-group
14008 (append regexp-in-group-escaped tags-in-group))))
14009 (setq taggroups-keys (delete tag taggroups-keys))))
14010 ;; Add the regular expressions back into the match-expression again.
14011 (while regexps-in-match
14012 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14013 (pop regexps-in-match)
14014 return-match t t))
14015 (cl-decf count))
14016 (if single-as-list
14017 (if tags-in-group tags-in-group (list return-match))
14018 return-match))
14019 (if single-as-list
14020 (list (if downcased (downcase match) match))
14021 match)))
14023 (defun org-op-to-function (op &optional stringp)
14024 "Turn an operator into the appropriate function."
14025 (setq op
14026 (cond
14027 ((equal op "<" ) '(< string< org-time<))
14028 ((equal op ">" ) '(> org-string> org-time>))
14029 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14030 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14031 ((member op '("=" "==")) '(= string= org-time=))
14032 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14033 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14035 (defun org<> (a b) (not (= a b)))
14036 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14037 (defun org-string>= (a b) (not (string< a b)))
14038 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14039 (defun org-string<> (a b) (not (string= a b)))
14040 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14041 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14042 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14043 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14044 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14045 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14046 (defun org-2ft (s)
14047 "Convert S to a floating point time.
14048 If S is already a number, just return it. If it is a string, parse
14049 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14050 (cond
14051 ((numberp s) s)
14052 ((stringp s)
14053 (condition-case nil
14054 (float-time (apply #'encode-time (org-parse-time-string s)))
14055 (error 0.)))
14056 (t 0.)))
14058 (defun org-time-today ()
14059 "Time in seconds today at 0:00.
14060 Returns the float number of seconds since the beginning of the
14061 epoch to the beginning of today (00:00)."
14062 (float-time (apply 'encode-time
14063 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14065 (defun org-matcher-time (s)
14066 "Interpret a time comparison value."
14067 (save-match-data
14068 (cond
14069 ((string= s "<now>") (float-time))
14070 ((string= s "<today>") (org-time-today))
14071 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14072 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14073 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14074 (+ (org-time-today)
14075 (* (string-to-number (match-string 1 s))
14076 (cdr (assoc (match-string 2 s)
14077 '(("d" . 86400.0) ("w" . 604800.0)
14078 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14079 (t (org-2ft s)))))
14081 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14082 (defvar org-tags-overlay (make-overlay 1 1))
14083 (delete-overlay org-tags-overlay)
14085 (defun org-get-local-tags-at (&optional pos)
14086 "Get a list of tags defined in the current headline."
14087 (org-get-tags-at pos 'local))
14089 (defun org-get-local-tags ()
14090 "Get a list of tags defined in the current headline."
14091 (org-get-tags-at nil 'local))
14093 (defun org-get-tags-at (&optional pos local)
14094 "Get a list of all headline tags applicable at POS.
14095 POS defaults to point. If tags are inherited, the list contains
14096 the targets in the same sequence as the headlines appear, i.e.
14097 the tags of the current headline come last.
14098 When LOCAL is non-nil, only return tags from the current headline,
14099 ignore inherited ones."
14100 (interactive)
14101 (if (and org-trust-scanner-tags
14102 (or (not pos) (equal pos (point)))
14103 (not local))
14104 org-scanner-tags
14105 (let (tags ltags lastpos parent)
14106 (save-excursion
14107 (save-restriction
14108 (widen)
14109 (goto-char (or pos (point)))
14110 (save-match-data
14111 (catch 'done
14112 (condition-case nil
14113 (progn
14114 (org-back-to-heading t)
14115 (while (not (equal lastpos (point)))
14116 (setq lastpos (point))
14117 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14118 (setq ltags (org-split-string
14119 (match-string-no-properties 1) ":"))
14120 (when parent
14121 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14122 (setq tags (append
14123 (if parent
14124 (org-remove-uninherited-tags ltags)
14125 ltags)
14126 tags)))
14127 (or org-use-tag-inheritance (throw 'done t))
14128 (when local (throw 'done t))
14129 (or (org-up-heading-safe) (error nil))
14130 (setq parent t)))
14131 (error nil)))))
14132 (if local
14133 tags
14134 (reverse (delete-dups
14135 (reverse (append
14136 (org-remove-uninherited-tags
14137 org-file-tags)
14138 tags)))))))))
14140 (defun org-add-prop-inherited (s)
14141 (add-text-properties 0 (length s) '(inherited t) s)
14144 (defun org-toggle-tag (tag &optional onoff)
14145 "Toggle the tag TAG for the current line.
14146 If ONOFF is `on' or `off', don't toggle but set to this state."
14147 (save-excursion
14148 (org-back-to-heading t)
14149 (let ((current
14150 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14151 (line-end-position) t)
14152 (let ((tags (match-string 1)))
14153 ;; Clear current tags.
14154 (replace-match "")
14155 ;; Reverse the tags list so any new tag is appended to
14156 ;; the current list of tags.
14157 (nreverse (org-split-string tags ":")))))
14158 res)
14159 (pcase onoff
14160 (`off (setq current (delete tag current)))
14161 ((or `on (guard (not (member tag current))))
14162 (setq res t)
14163 (cl-pushnew tag current :test #'equal))
14164 (_ (setq current (delete tag current))))
14165 (end-of-line)
14166 (if current
14167 (progn
14168 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14169 (org-set-tags nil t))
14170 (delete-horizontal-space))
14171 (run-hooks 'org-after-tags-change-hook)
14172 res)))
14174 (defun org--align-tags-here (to-col)
14175 "Align tags on the current headline to TO-COL.
14176 Assume point is on a headline."
14177 (let ((pos (point)))
14178 (beginning-of-line)
14179 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14180 (>= pos (match-beginning 2)))
14181 ;; No tags or point within tags: do not align.
14182 (goto-char pos)
14183 (goto-char (match-beginning 1))
14184 (let ((shift (max (- (if (>= to-col 0) to-col
14185 (- (abs to-col) (string-width (match-string 2))))
14186 (current-column))
14187 1)))
14188 (replace-match (make-string shift ?\s) nil nil nil 1)
14189 ;; Preserve initial position, if possible. In any case, stop
14190 ;; before tags.
14191 (when (< pos (point)) (goto-char pos))))))
14193 (defun org-set-tags-command (&optional arg just-align)
14194 "Call the set-tags command for the current entry."
14195 (interactive "P")
14196 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14197 (org-set-tags arg just-align)
14198 (save-excursion
14199 (unless (and (org-region-active-p)
14200 org-loop-over-headlines-in-active-region)
14201 (org-back-to-heading t))
14202 (org-set-tags arg just-align))))
14204 (defun org-set-tags-to (data)
14205 "Set the tags of the current entry to DATA, replacing the current tags.
14206 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14207 If DATA is nil or the empty string, any tags will be removed."
14208 (interactive "sTags: ")
14209 (setq data
14210 (cond
14211 ((eq data nil) "")
14212 ((equal data "") "")
14213 ((stringp data)
14214 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14215 ":"))
14216 ((listp data)
14217 (concat ":" (mapconcat 'identity data ":") ":"))))
14218 (when data
14219 (save-excursion
14220 (org-back-to-heading t)
14221 (when (let ((case-fold-search nil))
14222 (looking-at org-complex-heading-regexp))
14223 (if (match-end 5)
14224 (progn
14225 (goto-char (match-beginning 5))
14226 (insert data)
14227 (delete-region (point) (point-at-eol))
14228 (org-set-tags nil 'align))
14229 (goto-char (point-at-eol))
14230 (insert " " data)
14231 (org-set-tags nil 'align)))
14232 (beginning-of-line 1)
14233 (when (looking-at ".*?\\([ \t]+\\)$")
14234 (delete-region (match-beginning 1) (match-end 1))))))
14236 (defun org-align-all-tags ()
14237 "Align the tags in all headings."
14238 (interactive)
14239 (save-excursion
14240 (or (ignore-errors (org-back-to-heading t))
14241 (outline-next-heading))
14242 (if (org-at-heading-p)
14243 (org-set-tags t)
14244 (message "No headings"))))
14246 (defvar org-indent-indentation-per-level)
14247 (defun org-set-tags (&optional arg just-align)
14248 "Set the tags for the current headline.
14249 With prefix ARG, realign all tags in headings in the current buffer.
14250 When JUST-ALIGN is non-nil, only align tags."
14251 (interactive "P")
14252 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14253 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14254 'region-start-level
14255 'region))
14256 org-loop-over-headlines-in-active-region)
14257 (org-map-entries
14258 ;; We don't use ARG and JUST-ALIGN here because these args
14259 ;; are not useful when looping over headlines.
14260 #'org-set-tags
14261 org-loop-over-headlines-in-active-region
14263 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14264 (let ((org-setting-tags t))
14265 (if arg
14266 (save-excursion
14267 (goto-char (point-min))
14268 (while (re-search-forward org-outline-regexp-bol nil t)
14269 (org-set-tags nil t)
14270 (end-of-line))
14271 (message "All tags realigned to column %d" org-tags-column))
14272 (let* ((current (org-get-tags-string))
14273 (tags
14274 (if just-align current
14275 ;; Get a new set of tags from the user.
14276 (save-excursion
14277 (let* ((seen)
14278 (table
14279 (setq
14280 org-last-tags-completion-table
14281 ;; Uniquify tags in alists, yet preserve
14282 ;; structure (i.e., keywords).
14283 (delq nil
14284 (mapcar
14285 (lambda (pair)
14286 (let ((head (car pair)))
14287 (cond ((symbolp head) pair)
14288 ((member head seen) nil)
14289 (t (push head seen)
14290 pair))))
14291 (append
14292 (or org-current-tag-alist
14293 (org-get-buffer-tags))
14294 (and
14295 org-complete-tags-always-offer-all-agenda-tags
14296 (org-global-tags-completion-table
14297 (org-agenda-files))))))))
14298 (current-tags (org-split-string current ":"))
14299 (inherited-tags
14300 (nreverse (nthcdr (length current-tags)
14301 (nreverse (org-get-tags-at))))))
14302 (replace-regexp-in-string
14303 "\\([-+&]+\\|,\\)"
14305 (if (or (eq t org-use-fast-tag-selection)
14306 (and org-use-fast-tag-selection
14307 (delq nil (mapcar #'cdr table))))
14308 (org-fast-tag-selection
14309 current-tags inherited-tags table
14310 (and org-fast-tag-selection-include-todo
14311 org-todo-key-alist))
14312 (let ((org-add-colon-after-tag-completion
14313 (< 1 (length table))))
14314 (org-trim
14315 (completing-read
14316 "Tags: "
14317 #'org-tags-completion-function
14318 nil nil current 'org-tags-history))))))))))
14320 (when org-tags-sort-function
14321 (setq tags
14322 (mapconcat
14323 #'identity
14324 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14325 org-tags-sort-function)
14326 ":")))
14328 (if (or (string= ":" tags)
14329 (string= "::" tags))
14330 (setq tags ""))
14331 (if (not (org-string-nw-p tags)) (setq tags "")
14332 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14333 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14335 ;; Insert new tags at the correct column.
14336 (unless (equal current tags)
14337 (save-excursion
14338 (beginning-of-line)
14339 (let ((case-fold-search nil))
14340 (looking-at org-complex-heading-regexp))
14341 ;; Remove current tags, if any.
14342 (when (match-end 5) (replace-match "" nil nil nil 5))
14343 ;; Insert new tags, if any. Otherwise, remove trailing
14344 ;; white spaces.
14345 (end-of-line)
14346 (if (not (equal tags ""))
14347 ;; When text is being inserted on an invisible
14348 ;; region boundary, it can be inadvertently sucked
14349 ;; into invisibility.
14350 (org-flag-region (point) (progn (insert " " tags) (point))
14352 'outline)
14353 (skip-chars-backward " \t")
14354 (delete-region (point) (line-end-position)))))
14355 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14356 ;; is on.
14357 (unless (equal tags "")
14358 (let* ((level (save-excursion
14359 (beginning-of-line)
14360 (skip-chars-forward "\\*")))
14361 (offset (if (bound-and-true-p org-indent-mode)
14362 (* (1- org-indent-indentation-per-level)
14363 (1- level))
14365 (tags-column
14366 (+ org-tags-column
14367 (if (> org-tags-column 0) (- offset) offset))))
14368 (org--align-tags-here tags-column))))
14369 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14371 (defun org-change-tag-in-region (beg end tag off)
14372 "Add or remove TAG for each entry in the region.
14373 This works in the agenda, and also in an Org buffer."
14374 (interactive
14375 (list (region-beginning) (region-end)
14376 (let ((org-last-tags-completion-table
14377 (if (derived-mode-p 'org-mode)
14378 (org-uniquify
14379 (delq nil (append (org-get-buffer-tags)
14380 (org-global-tags-completion-table))))
14381 (org-global-tags-completion-table))))
14382 (completing-read
14383 "Tag: " 'org-tags-completion-function nil nil nil
14384 'org-tags-history))
14385 (progn
14386 (message "[s]et or [r]emove? ")
14387 (equal (read-char-exclusive) ?r))))
14388 (when (fboundp 'deactivate-mark) (deactivate-mark))
14389 (let ((agendap (equal major-mode 'org-agenda-mode))
14390 l1 l2 m buf pos newhead (cnt 0))
14391 (goto-char end)
14392 (setq l2 (1- (org-current-line)))
14393 (goto-char beg)
14394 (setq l1 (org-current-line))
14395 (cl-loop for l from l1 to l2 do
14396 (org-goto-line l)
14397 (setq m (get-text-property (point) 'org-hd-marker))
14398 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14399 (and agendap m))
14400 (setq buf (if agendap (marker-buffer m) (current-buffer))
14401 pos (if agendap m (point)))
14402 (with-current-buffer buf
14403 (save-excursion
14404 (save-restriction
14405 (goto-char pos)
14406 (setq cnt (1+ cnt))
14407 (org-toggle-tag tag (if off 'off 'on))
14408 (setq newhead (org-get-heading)))))
14409 (and agendap (org-agenda-change-all-lines newhead m))))
14410 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14412 (defun org-tags-completion-function (string _predicate &optional flag)
14413 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14414 (confirm (lambda (x) (stringp (car x)))))
14415 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14416 (setq s1 (match-string 1 string)
14417 s2 (match-string 2 string))
14418 (setq s1 "" s2 string))
14419 (cond
14420 ((eq flag nil)
14421 ;; try completion
14422 (setq rtn (try-completion s2 ctable confirm))
14423 (when (stringp rtn)
14424 (setq rtn
14425 (concat s1 s2 (substring rtn (length s2))
14426 (if (and org-add-colon-after-tag-completion
14427 (assoc rtn ctable))
14428 ":" ""))))
14429 rtn)
14430 ((eq flag t)
14431 ;; all-completions
14432 (all-completions s2 ctable confirm))
14433 ((eq flag 'lambda)
14434 ;; exact match?
14435 (assoc s2 ctable)))))
14437 (defun org-fast-tag-insert (kwd tags face &optional end)
14438 "Insert KDW, and the TAGS, the latter with face FACE.
14439 Also insert END."
14440 (insert (format "%-12s" (concat kwd ":"))
14441 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14442 (or end "")))
14444 (defun org-fast-tag-show-exit (flag)
14445 (save-excursion
14446 (org-goto-line 3)
14447 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14448 (replace-match ""))
14449 (when flag
14450 (end-of-line 1)
14451 (org-move-to-column (- (window-width) 19) t)
14452 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14454 (defun org-set-current-tags-overlay (current prefix)
14455 "Add an overlay to CURRENT tag with PREFIX."
14456 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14457 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14458 (org-overlay-display org-tags-overlay (concat prefix s))))
14460 (defvar org-last-tag-selection-key nil)
14461 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14462 "Fast tag selection with single keys.
14463 CURRENT is the current list of tags in the headline, INHERITED is the
14464 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14465 possibly with grouping information. TODO-TABLE is a similar table with
14466 TODO keywords, should these have keys assigned to them.
14467 If the keys are nil, a-z are automatically assigned.
14468 Returns the new tags string, or nil to not change the current settings."
14469 (let* ((fulltable (append table todo-table))
14470 (maxlen (apply 'max (mapcar
14471 (lambda (x)
14472 (if (stringp (car x)) (string-width (car x)) 0))
14473 fulltable)))
14474 (buf (current-buffer))
14475 (expert (eq org-fast-tag-selection-single-key 'expert))
14476 (buffer-tags nil)
14477 (fwidth (+ maxlen 3 1 3))
14478 (ncol (/ (- (window-width) 4) fwidth))
14479 (i-face 'org-done)
14480 (c-face 'org-todo)
14481 tg cnt e c char c1 c2 ntable tbl rtn
14482 ov-start ov-end ov-prefix
14483 (exit-after-next org-fast-tag-selection-single-key)
14484 (done-keywords org-done-keywords)
14485 groups ingroup intaggroup)
14486 (save-excursion
14487 (beginning-of-line 1)
14488 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14489 (setq ov-start (match-beginning 1)
14490 ov-end (match-end 1)
14491 ov-prefix "")
14492 (setq ov-start (1- (point-at-eol))
14493 ov-end (1+ ov-start))
14494 (skip-chars-forward "^\n\r")
14495 (setq ov-prefix
14496 (concat
14497 (buffer-substring (1- (point)) (point))
14498 (if (> (current-column) org-tags-column)
14500 (make-string (- org-tags-column (current-column)) ?\ ))))))
14501 (move-overlay org-tags-overlay ov-start ov-end)
14502 (save-window-excursion
14503 (if expert
14504 (set-buffer (get-buffer-create " *Org tags*"))
14505 (delete-other-windows)
14506 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14507 (org-switch-to-buffer-other-window " *Org tags*"))
14508 (erase-buffer)
14509 (setq-local org-done-keywords done-keywords)
14510 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14511 (org-fast-tag-insert "Current" current c-face "\n\n")
14512 (org-fast-tag-show-exit exit-after-next)
14513 (org-set-current-tags-overlay current ov-prefix)
14514 (setq tbl fulltable char ?a cnt 0)
14515 (while (setq e (pop tbl))
14516 (cond
14517 ((eq (car e) :startgroup)
14518 (push '() groups) (setq ingroup t)
14519 (unless (zerop cnt)
14520 (setq cnt 0)
14521 (insert "\n"))
14522 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14523 ((eq (car e) :endgroup)
14524 (setq ingroup nil cnt 0)
14525 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14526 ((eq (car e) :startgrouptag)
14527 (setq intaggroup t)
14528 (unless (zerop cnt)
14529 (setq cnt 0)
14530 (insert "\n"))
14531 (insert "[ "))
14532 ((eq (car e) :endgrouptag)
14533 (setq intaggroup nil cnt 0)
14534 (insert "]\n"))
14535 ((equal e '(:newline))
14536 (unless (zerop cnt)
14537 (setq cnt 0)
14538 (insert "\n")
14539 (setq e (car tbl))
14540 (while (equal (car tbl) '(:newline))
14541 (insert "\n")
14542 (setq tbl (cdr tbl)))))
14543 ((equal e '(:grouptags)) (insert " : "))
14545 (setq tg (copy-sequence (car e)) c2 nil)
14546 (if (cdr e)
14547 (setq c (cdr e))
14548 ;; automatically assign a character.
14549 (setq c1 (string-to-char
14550 (downcase (substring
14551 tg (if (= (string-to-char tg) ?@) 1 0)))))
14552 (if (or (rassoc c1 ntable) (rassoc c1 table))
14553 (while (or (rassoc char ntable) (rassoc char table))
14554 (setq char (1+ char)))
14555 (setq c2 c1))
14556 (setq c (or c2 char)))
14557 (when ingroup (push tg (car groups)))
14558 (setq tg (org-add-props tg nil 'face
14559 (cond
14560 ((not (assoc tg table))
14561 (org-get-todo-face tg))
14562 ((member tg current) c-face)
14563 ((member tg inherited) i-face))))
14564 (when (equal (caar tbl) :grouptags)
14565 (org-add-props tg nil 'face 'org-tag-group))
14566 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14567 (insert "[" c "] " tg (make-string
14568 (- fwidth 4 (length tg)) ?\ ))
14569 (push (cons tg c) ntable)
14570 (when (= (cl-incf cnt) ncol)
14571 (insert "\n")
14572 (when (or ingroup intaggroup) (insert " "))
14573 (setq cnt 0)))))
14574 (setq ntable (nreverse ntable))
14575 (insert "\n")
14576 (goto-char (point-min))
14577 (unless expert (org-fit-window-to-buffer))
14578 (setq rtn
14579 (catch 'exit
14580 (while t
14581 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14582 (if (not groups) "no " "")
14583 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14584 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14585 (setq org-last-tag-selection-key c)
14586 (cond
14587 ((= c ?\r) (throw 'exit t))
14588 ((= c ?!)
14589 (setq groups (not groups))
14590 (goto-char (point-min))
14591 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14592 ((= c ?\C-c)
14593 (if (not expert)
14594 (org-fast-tag-show-exit
14595 (setq exit-after-next (not exit-after-next)))
14596 (setq expert nil)
14597 (delete-other-windows)
14598 (set-window-buffer (split-window-vertically) " *Org tags*")
14599 (org-switch-to-buffer-other-window " *Org tags*")
14600 (org-fit-window-to-buffer)))
14601 ((or (= c ?\C-g)
14602 (and (= c ?q) (not (rassoc c ntable))))
14603 (delete-overlay org-tags-overlay)
14604 (setq quit-flag t))
14605 ((= c ?\ )
14606 (setq current nil)
14607 (when exit-after-next (setq exit-after-next 'now)))
14608 ((= c ?\t)
14609 (condition-case nil
14610 (setq tg (completing-read
14611 "Tag: "
14612 (or buffer-tags
14613 (with-current-buffer buf
14614 (setq buffer-tags
14615 (org-get-buffer-tags))))))
14616 (quit (setq tg "")))
14617 (when (string-match "\\S-" tg)
14618 (cl-pushnew (list tg) buffer-tags :test #'equal)
14619 (if (member tg current)
14620 (setq current (delete tg current))
14621 (push tg current)))
14622 (when exit-after-next (setq exit-after-next 'now)))
14623 ((setq e (rassoc c todo-table) tg (car e))
14624 (with-current-buffer buf
14625 (save-excursion (org-todo tg)))
14626 (when exit-after-next (setq exit-after-next 'now)))
14627 ((setq e (rassoc c ntable) tg (car e))
14628 (if (member tg current)
14629 (setq current (delete tg current))
14630 (cl-loop for g in groups do
14631 (when (member tg g)
14632 (dolist (x g) (setq current (delete x current)))))
14633 (push tg current))
14634 (when exit-after-next (setq exit-after-next 'now))))
14636 ;; Create a sorted list
14637 (setq current
14638 (sort current
14639 (lambda (a b)
14640 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14641 (when (eq exit-after-next 'now) (throw 'exit t))
14642 (goto-char (point-min))
14643 (beginning-of-line 2)
14644 (delete-region (point) (point-at-eol))
14645 (org-fast-tag-insert "Current" current c-face)
14646 (org-set-current-tags-overlay current ov-prefix)
14647 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14648 (setq tg (match-string 1))
14649 (add-text-properties
14650 (match-beginning 1) (match-end 1)
14651 (list 'face
14652 (cond
14653 ((member tg current) c-face)
14654 ((member tg inherited) i-face)
14655 (t (get-text-property (match-beginning 1) 'face))))))
14656 (goto-char (point-min)))))
14657 (delete-overlay org-tags-overlay)
14658 (if rtn
14659 (mapconcat 'identity current ":")
14660 nil))))
14662 (defun org-get-tags-string ()
14663 "Get the TAGS string in the current headline."
14664 (unless (org-at-heading-p t)
14665 (user-error "Not on a heading"))
14666 (save-excursion
14667 (beginning-of-line 1)
14668 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14669 (match-string-no-properties 1)
14670 "")))
14672 (defun org-get-tags ()
14673 "Get the list of tags specified in the current headline."
14674 (org-split-string (org-get-tags-string) ":"))
14676 (defun org-get-buffer-tags ()
14677 "Get a table of all tags used in the buffer, for completion."
14678 (org-with-wide-buffer
14679 (goto-char (point-min))
14680 (let ((tag-re (concat org-outline-regexp-bol
14681 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14682 tags)
14683 (while (re-search-forward tag-re nil t)
14684 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14685 (push tag tags)))
14686 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14688 ;;;; The mapping API
14690 (defvar org-agenda-skip-comment-trees)
14691 (defvar org-agenda-skip-function)
14692 (defun org-map-entries (func &optional match scope &rest skip)
14693 "Call FUNC at each headline selected by MATCH in SCOPE.
14695 FUNC is a function or a lisp form. The function will be called without
14696 arguments, with the cursor positioned at the beginning of the headline.
14697 The return values of all calls to the function will be collected and
14698 returned as a list.
14700 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14701 does not need to preserve point. After evaluation, the cursor will be
14702 moved to the end of the line (presumably of the headline of the
14703 processed entry) and search continues from there. Under some
14704 circumstances, this may not produce the wanted results. For example,
14705 if you have removed (e.g. archived) the current (sub)tree it could
14706 mean that the next entry will be skipped entirely. In such cases, you
14707 can specify the position from where search should continue by making
14708 FUNC set the variable `org-map-continue-from' to the desired buffer
14709 position.
14711 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14712 Only headlines that are matched by this query will be considered during
14713 the iteration. When MATCH is nil or t, all headlines will be
14714 visited by the iteration.
14716 SCOPE determines the scope of this command. It can be any of:
14718 nil The current buffer, respecting the restriction if any
14719 tree The subtree started with the entry at point
14720 region The entries within the active region, if any
14721 region-start-level
14722 The entries within the active region, but only those at
14723 the same level than the first one.
14724 file The current buffer, without restriction
14725 file-with-archives
14726 The current buffer, and any archives associated with it
14727 agenda All agenda files
14728 agenda-with-archives
14729 All agenda files with any archive files associated with them
14730 \(file1 file2 ...)
14731 If this is a list, all files in the list will be scanned
14733 The remaining args are treated as settings for the skipping facilities of
14734 the scanner. The following items can be given here:
14736 archive skip trees with the archive tag
14737 comment skip trees with the COMMENT keyword
14738 function or Emacs Lisp form:
14739 will be used as value for `org-agenda-skip-function', so
14740 whenever the function returns a position, FUNC will not be
14741 called for that entry and search will continue from the
14742 position returned
14744 If your function needs to retrieve the tags including inherited tags
14745 at the *current* entry, you can use the value of the variable
14746 `org-scanner-tags' which will be much faster than getting the value
14747 with `org-get-tags-at'. If your function gets properties with
14748 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14749 to t around the call to `org-entry-properties' to get the same speedup.
14750 Note that if your function moves around to retrieve tags and properties at
14751 a *different* entry, you cannot use these techniques."
14752 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14753 (not (org-region-active-p)))
14754 (let* ((org-agenda-archives-mode nil) ; just to make sure
14755 (org-agenda-skip-archived-trees (memq 'archive skip))
14756 (org-agenda-skip-comment-trees (memq 'comment skip))
14757 (org-agenda-skip-function
14758 (car (org-delete-all '(comment archive) skip)))
14759 (org-tags-match-list-sublevels t)
14760 (start-level (eq scope 'region-start-level))
14761 matcher res
14762 org-todo-keywords-for-agenda
14763 org-done-keywords-for-agenda
14764 org-todo-keyword-alist-for-agenda
14765 org-tag-alist-for-agenda
14766 org--matcher-tags-todo-only)
14768 (cond
14769 ((eq match t) (setq matcher t))
14770 ((eq match nil) (setq matcher t))
14771 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14773 (save-excursion
14774 (save-restriction
14775 (cond ((eq scope 'tree)
14776 (org-back-to-heading t)
14777 (org-narrow-to-subtree)
14778 (setq scope nil))
14779 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14780 (org-region-active-p))
14781 ;; If needed, set start-level to a string like "2"
14782 (when start-level
14783 (save-excursion
14784 (goto-char (region-beginning))
14785 (unless (org-at-heading-p) (outline-next-heading))
14786 (setq start-level (org-current-level))))
14787 (narrow-to-region (region-beginning)
14788 (save-excursion
14789 (goto-char (region-end))
14790 (unless (and (bolp) (org-at-heading-p))
14791 (outline-next-heading))
14792 (point)))
14793 (setq scope nil)))
14795 (if (not scope)
14796 (progn
14797 (org-agenda-prepare-buffers
14798 (and buffer-file-name (list buffer-file-name)))
14799 (setq res
14800 (org-scan-tags
14801 func matcher org--matcher-tags-todo-only start-level)))
14802 ;; Get the right scope
14803 (cond
14804 ((and scope (listp scope) (symbolp (car scope)))
14805 (setq scope (eval scope)))
14806 ((eq scope 'agenda)
14807 (setq scope (org-agenda-files t)))
14808 ((eq scope 'agenda-with-archives)
14809 (setq scope (org-agenda-files t))
14810 (setq scope (org-add-archive-files scope)))
14811 ((eq scope 'file)
14812 (setq scope (and buffer-file-name (list buffer-file-name))))
14813 ((eq scope 'file-with-archives)
14814 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14815 (org-agenda-prepare-buffers scope)
14816 (dolist (file scope)
14817 (with-current-buffer (org-find-base-buffer-visiting file)
14818 (org-with-wide-buffer
14819 (goto-char (point-min))
14820 (setq res
14821 (append
14823 (org-scan-tags
14824 func matcher org--matcher-tags-todo-only)))))))))
14825 res)))
14827 ;;; Properties API
14829 (defconst org-special-properties
14830 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14831 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14832 "The special properties valid in Org mode.
14833 These are properties that are not defined in the property drawer,
14834 but in some other way.")
14836 (defconst org-default-properties
14837 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14838 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14839 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14840 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14841 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14842 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14843 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14844 "Some properties that are used by Org mode for various purposes.
14845 Being in this list makes sure that they are offered for completion.")
14847 (defun org--valid-property-p (property)
14848 "Non nil when string PROPERTY is a valid property name."
14849 (not
14850 (or (equal property "")
14851 (string-match-p "\\s-" property))))
14853 (defun org--update-property-plist (key val props)
14854 "Associate KEY to VAL in alist PROPS.
14855 Modifications are made by side-effect. Return new alist."
14856 (let* ((appending (string= (substring key -1) "+"))
14857 (key (if appending (substring key 0 -1) key))
14858 (old (assoc-string key props t)))
14859 (if (not old) (cons (cons key val) props)
14860 (setcdr old (if appending (concat (cdr old) " " val) val))
14861 props)))
14863 (defun org-get-property-block (&optional beg force)
14864 "Return the (beg . end) range of the body of the property drawer.
14865 BEG is the beginning of the current subtree, or of the part
14866 before the first headline. If it is not given, it will be found.
14867 If the drawer does not exist, create it if FORCE is non-nil, or
14868 return nil."
14869 (org-with-wide-buffer
14870 (when beg (goto-char beg))
14871 (unless (org-before-first-heading-p)
14872 (let ((beg (cond (beg)
14873 ((or (not (featurep 'org-inlinetask))
14874 (org-inlinetask-in-task-p))
14875 (org-back-to-heading t))
14876 (t (org-with-limited-levels (org-back-to-heading t))))))
14877 (forward-line)
14878 (when (looking-at-p org-planning-line-re) (forward-line))
14879 (cond ((looking-at org-property-drawer-re)
14880 (forward-line)
14881 (cons (point) (progn (goto-char (match-end 0))
14882 (line-beginning-position))))
14883 (force
14884 (goto-char beg)
14885 (org-insert-property-drawer)
14886 (let ((pos (save-excursion (search-forward ":END:")
14887 (line-beginning-position))))
14888 (cons pos pos))))))))
14890 (defun org-at-property-p ()
14891 "Non-nil when point is inside a property drawer.
14892 See `org-property-re' for match data, if applicable."
14893 (save-excursion
14894 (beginning-of-line)
14895 (and (looking-at org-property-re)
14896 (let ((property-drawer (save-match-data (org-get-property-block))))
14897 (and property-drawer
14898 (>= (point) (car property-drawer))
14899 (< (point) (cdr property-drawer)))))))
14901 (defun org-property-action ()
14902 "Do an action on properties."
14903 (interactive)
14904 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14905 (let ((c (read-char-exclusive)))
14906 (cl-case c
14907 (?s (call-interactively #'org-set-property))
14908 (?d (call-interactively #'org-delete-property))
14909 (?D (call-interactively #'org-delete-property-globally))
14910 (?c (call-interactively #'org-compute-property-at-point))
14911 (otherwise (user-error "No such property action %c" c)))))
14913 (defun org-inc-effort ()
14914 "Increment the value of the effort property in the current entry."
14915 (interactive)
14916 (org-set-effort t))
14918 (defvar org-clock-effort) ; Defined in org-clock.el.
14919 (defvar org-clock-current-task) ; Defined in org-clock.el.
14920 (defun org-set-effort (&optional increment value)
14921 "Set the effort property of the current entry.
14922 If INCREMENT is non-nil, set the property to the next allowed
14923 value. Otherwise, if optional argument VALUE is provided, use
14924 it. Eventually, prompt for the new value if none of the previous
14925 variables is set."
14926 (interactive "P")
14927 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14928 (current (org-entry-get nil org-effort-property))
14929 (value
14930 (cond
14931 (increment
14932 (unless allowed (user-error "Allowed effort values are not set"))
14933 (or (cl-caadr (member (list current) allowed))
14934 (user-error "Unknown value %S among allowed values" current)))
14935 (value
14936 (if (stringp value) value
14937 (error "Invalid effort value: %S" value)))
14939 (let ((must-match
14940 (and allowed
14941 (not (get-text-property 0 'org-unrestricted
14942 (caar allowed))))))
14943 (completing-read "Effort: " allowed nil must-match))))))
14944 (unless (equal current value)
14945 (org-entry-put nil org-effort-property value))
14946 (org-refresh-property '((effort . identity)
14947 (effort-minutes . org-duration-to-minutes))
14948 value)
14949 (when (equal (org-get-heading t t t t)
14950 (bound-and-true-p org-clock-current-task))
14951 (setq org-clock-effort (org-get-at-bol 'effort))
14952 (org-clock-update-mode-line))
14953 (message "%s is now %s" org-effort-property value)))
14955 (defun org-entry-properties (&optional pom which)
14956 "Get all properties of the current entry.
14958 When POM is a buffer position, get all properties from the entry
14959 there instead.
14961 This includes the TODO keyword, the tags, time strings for
14962 deadline, scheduled, and clocking, and any additional properties
14963 defined in the entry.
14965 If WHICH is nil or `all', get all properties. If WHICH is
14966 `special' or `standard', only get that subclass. If WHICH is
14967 a string, only get that property.
14969 Return value is an alist. Keys are properties, as upcased
14970 strings."
14971 (org-with-point-at pom
14972 (when (and (derived-mode-p 'org-mode)
14973 (ignore-errors (org-back-to-heading t)))
14974 (catch 'exit
14975 (let* ((beg (point))
14976 (specific (and (stringp which) (upcase which)))
14977 (which (cond ((not specific) which)
14978 ((member specific org-special-properties) 'special)
14979 (t 'standard)))
14980 props)
14981 ;; Get the special properties, like TODO and TAGS.
14982 (when (memq which '(nil all special))
14983 (when (or (not specific) (string= specific "CLOCKSUM"))
14984 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
14985 (when clocksum
14986 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
14987 props)))
14988 (when specific (throw 'exit props)))
14989 (when (or (not specific) (string= specific "CLOCKSUM_T"))
14990 (let ((clocksumt (get-text-property (point)
14991 :org-clock-minutes-today)))
14992 (when clocksumt
14993 (push (cons "CLOCKSUM_T"
14994 (org-duration-from-minutes clocksumt))
14995 props)))
14996 (when specific (throw 'exit props)))
14997 (when (or (not specific) (string= specific "ITEM"))
14998 (let ((case-fold-search nil))
14999 (when (looking-at org-complex-heading-regexp)
15000 (push (cons "ITEM"
15001 (let ((title (match-string-no-properties 4)))
15002 (if (org-string-nw-p title)
15003 (org-remove-tabs title)
15004 "")))
15005 props)))
15006 (when specific (throw 'exit props)))
15007 (when (or (not specific) (string= specific "TODO"))
15008 (let ((case-fold-search nil))
15009 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15010 (push (cons "TODO" (match-string-no-properties 2)) props)))
15011 (when specific (throw 'exit props)))
15012 (when (or (not specific) (string= specific "PRIORITY"))
15013 (push (cons "PRIORITY"
15014 (if (looking-at org-priority-regexp)
15015 (match-string-no-properties 2)
15016 (char-to-string org-default-priority)))
15017 props)
15018 (when specific (throw 'exit props)))
15019 (when (or (not specific) (string= specific "FILE"))
15020 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15021 props)
15022 (when specific (throw 'exit props)))
15023 (when (or (not specific) (string= specific "TAGS"))
15024 (let ((value (org-string-nw-p (org-get-tags-string))))
15025 (when value (push (cons "TAGS" value) props)))
15026 (when specific (throw 'exit props)))
15027 (when (or (not specific) (string= specific "ALLTAGS"))
15028 (let ((value (org-get-tags-at)))
15029 (when value
15030 (push (cons "ALLTAGS"
15031 (format ":%s:" (mapconcat #'identity value ":")))
15032 props)))
15033 (when specific (throw 'exit props)))
15034 (when (or (not specific) (string= specific "BLOCKED"))
15035 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15036 (when specific (throw 'exit props)))
15037 (when (or (not specific)
15038 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15039 (forward-line)
15040 (when (looking-at-p org-planning-line-re)
15041 (end-of-line)
15042 (let ((bol (line-beginning-position))
15043 ;; Backward compatibility: time keywords used to
15044 ;; be configurable (before 8.3). Make sure we
15045 ;; get the correct keyword.
15046 (key-assoc `(("CLOSED" . ,org-closed-string)
15047 ("DEADLINE" . ,org-deadline-string)
15048 ("SCHEDULED" . ,org-scheduled-string))))
15049 (dolist (pair (if specific (list (assoc specific key-assoc))
15050 key-assoc))
15051 (save-excursion
15052 (when (search-backward (cdr pair) bol t)
15053 (goto-char (match-end 0))
15054 (skip-chars-forward " \t")
15055 (and (looking-at org-ts-regexp-both)
15056 (push (cons (car pair)
15057 (match-string-no-properties 0))
15058 props)))))))
15059 (when specific (throw 'exit props)))
15060 (when (or (not specific)
15061 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15062 (let ((find-ts
15063 (lambda (end ts)
15064 ;; Fix next time-stamp before END. TS is the
15065 ;; list of time-stamps found so far.
15066 (let ((ts ts)
15067 (regexp (cond
15068 ((string= specific "TIMESTAMP")
15069 org-ts-regexp)
15070 ((string= specific "TIMESTAMP_IA")
15071 org-ts-regexp-inactive)
15072 ((assoc "TIMESTAMP_IA" ts)
15073 org-ts-regexp)
15074 ((assoc "TIMESTAMP" ts)
15075 org-ts-regexp-inactive)
15076 (t org-ts-regexp-both))))
15077 (catch 'next
15078 (while (re-search-forward regexp end t)
15079 (backward-char)
15080 (let ((object (org-element-context)))
15081 ;; Accept to match timestamps in node
15082 ;; properties, too.
15083 (when (memq (org-element-type object)
15084 '(node-property timestamp))
15085 (let ((type
15086 (org-element-property :type object)))
15087 (cond
15088 ((and (memq type '(active active-range))
15089 (not (equal specific "TIMESTAMP_IA")))
15090 (unless (assoc "TIMESTAMP" ts)
15091 (push (cons "TIMESTAMP"
15092 (org-element-property
15093 :raw-value object))
15095 (when specific (throw 'exit ts))))
15096 ((and (memq type '(inactive inactive-range))
15097 (not (string= specific "TIMESTAMP")))
15098 (unless (assoc "TIMESTAMP_IA" ts)
15099 (push (cons "TIMESTAMP_IA"
15100 (org-element-property
15101 :raw-value object))
15103 (when specific (throw 'exit ts))))))
15104 ;; Both timestamp types are found,
15105 ;; move to next part.
15106 (when (= (length ts) 2) (throw 'next ts)))))
15107 ts)))))
15108 (goto-char beg)
15109 ;; First look for timestamps within headline.
15110 (let ((ts (funcall find-ts (line-end-position) nil)))
15111 (if (= (length ts) 2) (setq props (nconc ts props))
15112 ;; Then find timestamps in the section, skipping
15113 ;; planning line.
15114 (let ((end (save-excursion (outline-next-heading))))
15115 (forward-line)
15116 (when (looking-at-p org-planning-line-re) (forward-line))
15117 (setq props (nconc (funcall find-ts end ts) props))))))))
15118 ;; Get the standard properties, like :PROP:.
15119 (when (memq which '(nil all standard))
15120 ;; If we are looking after a specific property, delegate
15121 ;; to `org-entry-get', which is faster. However, make an
15122 ;; exception for "CATEGORY", since it can be also set
15123 ;; through keywords (i.e. #+CATEGORY).
15124 (if (and specific (not (equal specific "CATEGORY")))
15125 (let ((value (org-entry-get beg specific nil t)))
15126 (throw 'exit (and value (list (cons specific value)))))
15127 (let ((range (org-get-property-block beg)))
15128 (when range
15129 (let ((end (cdr range)) seen-base)
15130 (goto-char (car range))
15131 ;; Unlike to `org--update-property-plist', we
15132 ;; handle the case where base values is found
15133 ;; after its extension. We also forbid standard
15134 ;; properties to be named as special properties.
15135 (while (re-search-forward org-property-re end t)
15136 (let* ((key (upcase (match-string-no-properties 2)))
15137 (extendp (string-match-p "\\+\\'" key))
15138 (key-base (if extendp (substring key 0 -1) key))
15139 (value (match-string-no-properties 3)))
15140 (cond
15141 ((member-ignore-case key-base org-special-properties))
15142 (extendp
15143 (setq props
15144 (org--update-property-plist key value props)))
15145 ((member key seen-base))
15146 (t (push key seen-base)
15147 (let ((p (assoc-string key props t)))
15148 (if p (setcdr p (concat value " " (cdr p)))
15149 (push (cons key value) props))))))))))))
15150 (unless (assoc "CATEGORY" props)
15151 (push (cons "CATEGORY" (org-get-category beg)) props)
15152 (when (string= specific "CATEGORY") (throw 'exit props)))
15153 ;; Return value.
15154 props)))))
15156 (defun org--property-local-values (property literal-nil)
15157 "Return value for PROPERTY in current entry.
15158 Value is a list whose car is the base value for PROPERTY and cdr
15159 a list of accumulated values. Return nil if neither is found in
15160 the entry. Also return nil when PROPERTY is set to \"nil\",
15161 unless LITERAL-NIL is non-nil."
15162 (let ((range (org-get-property-block)))
15163 (when range
15164 (goto-char (car range))
15165 (let* ((case-fold-search t)
15166 (end (cdr range))
15167 (value
15168 ;; Base value.
15169 (save-excursion
15170 (let ((v (and (re-search-forward
15171 (org-re-property property nil t) end t)
15172 (match-string-no-properties 3))))
15173 (list (if literal-nil v (org-not-nil v)))))))
15174 ;; Find additional values.
15175 (let* ((property+ (org-re-property (concat property "+") nil t)))
15176 (while (re-search-forward property+ end t)
15177 (push (match-string-no-properties 3) value)))
15178 ;; Return final values.
15179 (and (not (equal value '(nil))) (nreverse value))))))
15181 (defun org--property-global-value (property literal-nil)
15182 "Return value for PROPERTY in current buffer.
15183 Return value is a string. Return nil if property is not set
15184 globally. Also return nil when PROPERTY is set to \"nil\",
15185 unless LITERAL-NIL is non-nil."
15186 (let ((global
15187 (cdr (or (assoc-string property org-file-properties t)
15188 (assoc-string property org-global-properties t)
15189 (assoc-string property org-global-properties-fixed t)))))
15190 (if literal-nil global (org-not-nil global))))
15192 (defun org-entry-get (pom property &optional inherit literal-nil)
15193 "Get value of PROPERTY for entry or content at point-or-marker POM.
15195 If INHERIT is non-nil and the entry does not have the property,
15196 then also check higher levels of the hierarchy. If INHERIT is
15197 the symbol `selective', use inheritance only if the setting in
15198 `org-use-property-inheritance' selects PROPERTY for inheritance.
15200 If the property is present but empty, the return value is the
15201 empty string. If the property is not present at all, nil is
15202 returned. In any other case, return the value as a string.
15203 Search is case-insensitive.
15205 If LITERAL-NIL is set, return the string value \"nil\" as
15206 a string, do not interpret it as the list atom nil. This is used
15207 for inheritance when a \"nil\" value can supersede a non-nil
15208 value higher up the hierarchy."
15209 (org-with-point-at pom
15210 (cond
15211 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15212 ;; We need a special property. Use `org-entry-properties' to
15213 ;; retrieve it, but specify the wanted property.
15214 (cdr (assoc-string property (org-entry-properties nil property))))
15215 ((and inherit
15216 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15217 (org-entry-get-with-inheritance property literal-nil))
15219 (let* ((local (org--property-local-values property literal-nil))
15220 (value (and local (mapconcat #'identity (delq nil local) " "))))
15221 (if literal-nil value (org-not-nil value)))))))
15223 (defun org-property-or-variable-value (var &optional inherit)
15224 "Check if there is a property fixing the value of VAR.
15225 If yes, return this value. If not, return the current value of the variable."
15226 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15227 (if (and prop (stringp prop) (string-match "\\S-" prop))
15228 (read prop)
15229 (symbol-value var))))
15231 (defun org-entry-delete (pom property)
15232 "Delete PROPERTY from entry at point-or-marker POM.
15233 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15234 non-nil when a property was removed."
15235 (org-with-point-at pom
15236 (pcase (org-get-property-block)
15237 (`(,begin . ,origin)
15238 (let* ((end (copy-marker origin))
15239 (re (org-re-property
15240 (concat (regexp-quote property) "\\+?") t t)))
15241 (goto-char begin)
15242 (while (re-search-forward re end t)
15243 (delete-region (match-beginning 0) (line-beginning-position 2)))
15244 ;; If drawer is empty, remove it altogether.
15245 (when (= begin end)
15246 (delete-region (line-beginning-position 0)
15247 (line-beginning-position 2)))
15248 ;; Return non-nil if some property was removed.
15249 (prog1 (/= end origin) (set-marker end nil))))
15250 (_ nil))))
15252 ;; Multi-values properties are properties that contain multiple values
15253 ;; These values are assumed to be single words, separated by whitespace.
15254 (defun org-entry-add-to-multivalued-property (pom property value)
15255 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15256 (let* ((old (org-entry-get pom property))
15257 (values (and old (split-string old))))
15258 (setq value (org-entry-protect-space value))
15259 (unless (member value values)
15260 (setq values (append values (list value)))
15261 (org-entry-put pom property (mapconcat #'identity values " ")))))
15263 (defun org-entry-remove-from-multivalued-property (pom property value)
15264 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15265 (let* ((old (org-entry-get pom property))
15266 (values (and old (split-string old))))
15267 (setq value (org-entry-protect-space value))
15268 (when (member value values)
15269 (setq values (delete value values))
15270 (org-entry-put pom property (mapconcat #'identity values " ")))))
15272 (defun org-entry-member-in-multivalued-property (pom property value)
15273 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15274 (let* ((old (org-entry-get pom property))
15275 (values (and old (split-string old))))
15276 (setq value (org-entry-protect-space value))
15277 (member value values)))
15279 (defun org-entry-get-multivalued-property (pom property)
15280 "Return a list of values in a multivalued property."
15281 (let* ((value (org-entry-get pom property))
15282 (values (and value (split-string value))))
15283 (mapcar #'org-entry-restore-space values)))
15285 (defun org-entry-put-multivalued-property (pom property &rest values)
15286 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15287 VALUES should be a list of strings. Spaces will be protected."
15288 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15289 (let* ((value (org-entry-get pom property))
15290 (values (and value (split-string value))))
15291 (mapcar #'org-entry-restore-space values)))
15293 (defun org-entry-protect-space (s)
15294 "Protect spaces and newline in string S."
15295 (while (string-match " " s)
15296 (setq s (replace-match "%20" t t s)))
15297 (while (string-match "\n" s)
15298 (setq s (replace-match "%0A" t t s)))
15301 (defun org-entry-restore-space (s)
15302 "Restore spaces and newline in string S."
15303 (while (string-match "%20" s)
15304 (setq s (replace-match " " t t s)))
15305 (while (string-match "%0A" s)
15306 (setq s (replace-match "\n" t t s)))
15309 (defvar org-entry-property-inherited-from (make-marker)
15310 "Marker pointing to the entry from where a property was inherited.
15311 Each call to `org-entry-get-with-inheritance' will set this marker to the
15312 location of the entry where the inheritance search matched. If there was
15313 no match, the marker will point nowhere.
15314 Note that also `org-entry-get' calls this function, if the INHERIT flag
15315 is set.")
15317 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15318 "Get PROPERTY of entry or content at point, search higher levels if needed.
15319 The search will stop at the first ancestor which has the property defined.
15320 If the value found is \"nil\", return nil to show that the property
15321 should be considered as undefined (this is the meaning of nil here).
15322 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15323 (move-marker org-entry-property-inherited-from nil)
15324 (org-with-wide-buffer
15325 (let (value)
15326 (catch 'exit
15327 (while t
15328 (let ((v (org--property-local-values property literal-nil)))
15329 (when v
15330 (setq value
15331 (concat (mapconcat #'identity (delq nil v) " ")
15332 (and value " ")
15333 value)))
15334 (cond
15335 ((car v)
15336 (org-back-to-heading t)
15337 (move-marker org-entry-property-inherited-from (point))
15338 (throw 'exit nil))
15339 ((org-up-heading-safe))
15341 (let ((global (org--property-global-value property literal-nil)))
15342 (cond ((not global))
15343 (value (setq value (concat global " " value)))
15344 (t (setq value global))))
15345 (throw 'exit nil))))))
15346 (if literal-nil value (org-not-nil value)))))
15348 (defvar org-property-changed-functions nil
15349 "Hook called when the value of a property has changed.
15350 Each hook function should accept two arguments, the name of the property
15351 and the new value.")
15353 (defun org-entry-put (pom property value)
15354 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15356 If the value is nil, it is converted to the empty string. If it
15357 is not a string, an error is raised. Also raise an error on
15358 invalid property names.
15360 PROPERTY can be any regular property (see
15361 `org-special-properties'). It can also be \"TODO\",
15362 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15364 For the last two properties, VALUE may have any of the special
15365 values \"earlier\" and \"later\". The function then increases or
15366 decreases scheduled or deadline date by one day."
15367 (cond ((null value) (setq value ""))
15368 ((not (stringp value)) (error "Properties values should be strings"))
15369 ((not (org--valid-property-p property))
15370 (user-error "Invalid property name: \"%s\"" property)))
15371 (org-with-point-at pom
15372 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15373 (org-back-to-heading t)
15374 (org-with-limited-levels (org-back-to-heading t)))
15375 (let ((beg (point)))
15376 (cond
15377 ((equal property "TODO")
15378 (cond ((not (org-string-nw-p value)) (setq value 'none))
15379 ((not (member value org-todo-keywords-1))
15380 (user-error "\"%s\" is not a valid TODO state" value)))
15381 (org-todo value)
15382 (org-set-tags nil 'align))
15383 ((equal property "PRIORITY")
15384 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15385 (org-set-tags nil 'align))
15386 ((equal property "SCHEDULED")
15387 (forward-line)
15388 (if (and (looking-at-p org-planning-line-re)
15389 (re-search-forward
15390 org-scheduled-time-regexp (line-end-position) t))
15391 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15392 ((string= value "later") (org-timestamp-change 1 'day))
15393 ((string= value "") (org-schedule '(4)))
15394 (t (org-schedule nil value)))
15395 (if (member value '("earlier" "later" ""))
15396 (call-interactively #'org-schedule)
15397 (org-schedule nil value))))
15398 ((equal property "DEADLINE")
15399 (forward-line)
15400 (if (and (looking-at-p org-planning-line-re)
15401 (re-search-forward
15402 org-deadline-time-regexp (line-end-position) t))
15403 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15404 ((string= value "later") (org-timestamp-change 1 'day))
15405 ((string= value "") (org-deadline '(4)))
15406 (t (org-deadline nil value)))
15407 (if (member value '("earlier" "later" ""))
15408 (call-interactively #'org-deadline)
15409 (org-deadline nil value))))
15410 ((member property org-special-properties)
15411 (error "The %s property cannot be set with `org-entry-put'" property))
15413 (let* ((range (org-get-property-block beg 'force))
15414 (end (cdr range))
15415 (case-fold-search t))
15416 (goto-char (car range))
15417 (if (re-search-forward (org-re-property property nil t) end t)
15418 (progn (delete-region (match-beginning 0) (match-end 0))
15419 (goto-char (match-beginning 0)))
15420 (goto-char end)
15421 (insert "\n")
15422 (backward-char))
15423 (insert ":" property ":")
15424 (when value (insert " " value))
15425 (org-indent-line)))))
15426 (run-hook-with-args 'org-property-changed-functions property value)))
15428 (defun org-buffer-property-keys (&optional specials defaults columns)
15429 "Get all property keys in the current buffer.
15431 When SPECIALS is non-nil, also list the special properties that
15432 reflect things like tags and TODO state.
15434 When DEFAULTS is non-nil, also include properties that has
15435 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15436 DESCRIPTION, LOCATION, and LOGGING and others.
15438 When COLUMNS in non-nil, also include property names given in
15439 COLUMN formats in the current buffer."
15440 (let ((case-fold-search t)
15441 (props (append
15442 (and specials org-special-properties)
15443 (and defaults (cons org-effort-property org-default-properties))
15444 nil)))
15445 (org-with-wide-buffer
15446 (goto-char (point-min))
15447 (while (re-search-forward org-property-start-re nil t)
15448 (catch :skip
15449 (let ((range (org-get-property-block)))
15450 (unless range (throw :skip nil))
15451 (goto-char (car range))
15452 (let ((begin (car range))
15453 (end (cdr range)))
15454 ;; Make sure that found property block is not located
15455 ;; before current point, as it would generate an infloop.
15456 ;; It can happen, for example, in the following
15457 ;; situation:
15459 ;; * Headline
15460 ;; :PROPERTIES:
15461 ;; ...
15462 ;; :END:
15463 ;; *************** Inlinetask
15464 ;; #+BEGIN_EXAMPLE
15465 ;; :PROPERTIES:
15466 ;; #+END_EXAMPLE
15468 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15469 (while (< (point) end)
15470 (let ((p (progn (looking-at org-property-re)
15471 (match-string-no-properties 2))))
15472 ;; Only add true property name, not extension symbol.
15473 (push (if (not (string-match-p "\\+\\'" p)) p
15474 (substring p 0 -1))
15475 props))
15476 (forward-line))))
15477 (outline-next-heading)))
15478 (when columns
15479 (goto-char (point-min))
15480 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15481 (let ((element (org-element-at-point)))
15482 (when (memq (org-element-type element) '(keyword node-property))
15483 (let ((value (org-element-property :value element))
15484 (start 0))
15485 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15486 \\(?:{[^}]+}\\)?"
15487 value start)
15488 (setq start (match-end 0))
15489 (let ((p (match-string-no-properties 1 value)))
15490 (unless (member-ignore-case p org-special-properties)
15491 (push p props))))))))))
15492 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15494 (defun org-property-values (key)
15495 "List all non-nil values of property KEY in current buffer."
15496 (org-with-wide-buffer
15497 (goto-char (point-min))
15498 (let ((case-fold-search t)
15499 (re (org-re-property key))
15500 values)
15501 (while (re-search-forward re nil t)
15502 (push (org-entry-get (point) key) values))
15503 (delete-dups values))))
15505 (defun org-insert-property-drawer ()
15506 "Insert a property drawer into the current entry."
15507 (org-with-wide-buffer
15508 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15509 (org-back-to-heading t)
15510 (org-with-limited-levels (org-back-to-heading t)))
15511 (forward-line)
15512 (when (looking-at-p org-planning-line-re) (forward-line))
15513 (unless (looking-at-p org-property-drawer-re)
15514 ;; Make sure we start editing a line from current entry, not from
15515 ;; next one. It prevents extending text properties or overlays
15516 ;; belonging to the latter.
15517 (when (bolp) (backward-char))
15518 (let ((begin (1+ (point)))
15519 (inhibit-read-only t))
15520 (insert "\n:PROPERTIES:\n:END:")
15521 (when (eobp) (insert "\n"))
15522 (org-indent-region begin (point))))))
15524 (defun org-insert-drawer (&optional arg drawer)
15525 "Insert a drawer at point.
15527 When optional argument ARG is non-nil, insert a property drawer.
15529 Optional argument DRAWER, when non-nil, is a string representing
15530 drawer's name. Otherwise, the user is prompted for a name.
15532 If a region is active, insert the drawer around that region
15533 instead.
15535 Point is left between drawer's boundaries."
15536 (interactive "P")
15537 (let* ((drawer (if arg "PROPERTIES"
15538 (or drawer (read-from-minibuffer "Drawer: ")))))
15539 (cond
15540 ;; With C-u, fall back on `org-insert-property-drawer'
15541 (arg (org-insert-property-drawer))
15542 ;; Check validity of suggested drawer's name.
15543 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15544 (user-error "Invalid drawer name"))
15545 ;; With an active region, insert a drawer at point.
15546 ((not (org-region-active-p))
15547 (progn
15548 (unless (bolp) (insert "\n"))
15549 (insert (format ":%s:\n\n:END:\n" drawer))
15550 (forward-line -2)))
15551 ;; Otherwise, insert the drawer at point
15553 (let ((rbeg (region-beginning))
15554 (rend (copy-marker (region-end))))
15555 (unwind-protect
15556 (progn
15557 (goto-char rbeg)
15558 (beginning-of-line)
15559 (when (save-excursion
15560 (re-search-forward org-outline-regexp-bol rend t))
15561 (user-error "Drawers cannot contain headlines"))
15562 ;; Position point at the beginning of the first
15563 ;; non-blank line in region. Insert drawer's opening
15564 ;; there, then indent it.
15565 (org-skip-whitespace)
15566 (beginning-of-line)
15567 (insert ":" drawer ":\n")
15568 (forward-line -1)
15569 (indent-for-tab-command)
15570 ;; Move point to the beginning of the first blank line
15571 ;; after the last non-blank line in region. Insert
15572 ;; drawer's closing, then indent it.
15573 (goto-char rend)
15574 (skip-chars-backward " \r\t\n")
15575 (insert "\n:END:")
15576 (deactivate-mark t)
15577 (indent-for-tab-command)
15578 (unless (eolp) (insert "\n")))
15579 ;; Clear marker, whatever the outcome of insertion is.
15580 (set-marker rend nil)))))))
15582 (defvar org-property-set-functions-alist nil
15583 "Property set function alist.
15584 Each entry should have the following format:
15586 (PROPERTY . READ-FUNCTION)
15588 The read function will be called with the same argument as
15589 `org-completing-read'.")
15591 (defun org-set-property-function (property)
15592 "Get the function that should be used to set PROPERTY.
15593 This is computed according to `org-property-set-functions-alist'."
15594 (or (cdr (assoc property org-property-set-functions-alist))
15595 'org-completing-read))
15597 (defun org-read-property-value (property)
15598 "Read PROPERTY value from user."
15599 (let* ((completion-ignore-case t)
15600 (allowed (org-property-get-allowed-values nil property 'table))
15601 (cur (org-entry-get nil property))
15602 (prompt (concat property " value"
15603 (if (and cur (string-match "\\S-" cur))
15604 (concat " [" cur "]") "") ": "))
15605 (set-function (org-set-property-function property))
15606 (val (if allowed
15607 (funcall set-function prompt allowed nil
15608 (not (get-text-property 0 'org-unrestricted
15609 (caar allowed))))
15610 (funcall set-function prompt
15611 (mapcar 'list (org-property-values property))
15612 nil nil "" nil cur))))
15613 (org-trim val)))
15615 (defvar org-last-set-property nil)
15616 (defvar org-last-set-property-value nil)
15617 (defun org-read-property-name ()
15618 "Read a property name."
15619 (let ((completion-ignore-case t)
15620 (default-prop (or (and (org-at-property-p)
15621 (match-string-no-properties 2))
15622 org-last-set-property)))
15623 (org-completing-read
15624 (concat "Property"
15625 (if default-prop (concat " [" default-prop "]") "")
15626 ": ")
15627 (mapcar #'list (org-buffer-property-keys nil t t))
15628 nil nil nil nil default-prop)))
15630 (defun org-set-property-and-value (use-last)
15631 "Allow to set [PROPERTY]: [value] direction from prompt.
15632 When use-default, don't even ask, just use the last
15633 \"[PROPERTY]: [value]\" string from the history."
15634 (interactive "P")
15635 (let* ((completion-ignore-case t)
15636 (pv (or (and use-last org-last-set-property-value)
15637 (org-completing-read
15638 "Enter a \"[Property]: [value]\" pair: "
15639 nil nil nil nil nil
15640 org-last-set-property-value)))
15641 prop val)
15642 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15643 (setq prop (match-string 1 pv)
15644 val (match-string 2 pv))
15645 (org-set-property prop val))))
15647 (defun org-set-property (property value)
15648 "In the current entry, set PROPERTY to VALUE.
15650 When called interactively, this will prompt for a property name, offering
15651 completion on existing and default properties. And then it will prompt
15652 for a value, offering completion either on allowed values (via an inherited
15653 xxx_ALL property) or on existing values in other instances of this property
15654 in the current file.
15656 Throw an error when trying to set a property with an invalid name."
15657 (interactive (list nil nil))
15658 (let ((property (or property (org-read-property-name))))
15659 ;; `org-entry-put' also makes the following check, but this one
15660 ;; avoids polluting `org-last-set-property' and
15661 ;; `org-last-set-property-value' needlessly.
15662 (unless (org--valid-property-p property)
15663 (user-error "Invalid property name: \"%s\"" property))
15664 (let ((value (or value (org-read-property-value property)))
15665 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15666 (setq org-last-set-property property)
15667 (setq org-last-set-property-value (concat property ": " value))
15668 ;; Possibly postprocess the inserted value:
15669 (when fn (setq value (funcall fn value)))
15670 (unless (equal (org-entry-get nil property) value)
15671 (org-entry-put nil property value)))))
15673 (defun org-find-property (property &optional value)
15674 "Find first entry in buffer that sets PROPERTY.
15676 When optional argument VALUE is non-nil, only consider an entry
15677 if it contains PROPERTY set to this value. If PROPERTY should be
15678 explicitly set to nil, use string \"nil\" for VALUE.
15680 Return position where the entry begins, or nil if there is no
15681 such entry. If narrowing is in effect, only search the visible
15682 part of the buffer."
15683 (save-excursion
15684 (goto-char (point-min))
15685 (let ((case-fold-search t)
15686 (re (org-re-property property nil (not value) value)))
15687 (catch 'exit
15688 (while (re-search-forward re nil t)
15689 (when (if value (org-at-property-p)
15690 (org-entry-get (point) property nil t))
15691 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15693 (defun org-delete-property (property)
15694 "In the current entry, delete PROPERTY."
15695 (interactive
15696 (let* ((completion-ignore-case t)
15697 (cat (org-entry-get (point) "CATEGORY"))
15698 (props0 (org-entry-properties nil 'standard))
15699 (props (if cat props0
15700 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15701 (prop (if (< 1 (length props))
15702 (completing-read "Property: " props nil t)
15703 (caar props))))
15704 (list prop)))
15705 (if (not property)
15706 (message "No property to delete in this entry")
15707 (org-entry-delete nil property)
15708 (message "Property \"%s\" deleted" property)))
15710 (defun org-delete-property-globally (property)
15711 "Remove PROPERTY globally, from all entries.
15712 This function ignores narrowing, if any."
15713 (interactive
15714 (let* ((completion-ignore-case t)
15715 (prop (completing-read
15716 "Globally remove property: "
15717 (mapcar #'list (org-buffer-property-keys)))))
15718 (list prop)))
15719 (org-with-wide-buffer
15720 (goto-char (point-min))
15721 (let ((count 0)
15722 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15723 (while (re-search-forward re nil t)
15724 (when (org-entry-delete (point) property) (cl-incf count)))
15725 (message "Property \"%s\" removed from %d entries" property count))))
15727 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15729 (defun org-compute-property-at-point ()
15730 "Compute the property at point.
15731 This looks for an enclosing column format, extracts the operator and
15732 then applies it to the property in the column format's scope."
15733 (interactive)
15734 (unless (org-at-property-p)
15735 (user-error "Not at a property"))
15736 (let ((prop (match-string-no-properties 2)))
15737 (org-columns-get-format-and-top-level)
15738 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15739 (user-error "No operator defined for property %s" prop))
15740 (org-columns-compute prop)))
15742 (defvar org-property-allowed-value-functions nil
15743 "Hook for functions supplying allowed values for a specific property.
15744 The functions must take a single argument, the name of the property, and
15745 return a flat list of allowed values. If \":ETC\" is one of
15746 the values, this means that these values are intended as defaults for
15747 completion, but that other values should be allowed too.
15748 The functions must return nil if they are not responsible for this
15749 property.")
15751 (defun org-property-get-allowed-values (pom property &optional table)
15752 "Get allowed values for the property PROPERTY.
15753 When TABLE is non-nil, return an alist that can directly be used for
15754 completion."
15755 (let (vals)
15756 (cond
15757 ((equal property "TODO")
15758 (setq vals (org-with-point-at pom
15759 (append org-todo-keywords-1 '("")))))
15760 ((equal property "PRIORITY")
15761 (let ((n org-lowest-priority))
15762 (while (>= n org-highest-priority)
15763 (push (char-to-string n) vals)
15764 (setq n (1- n)))))
15765 ((equal property "CATEGORY"))
15766 ((member property org-special-properties))
15767 ((setq vals (run-hook-with-args-until-success
15768 'org-property-allowed-value-functions property)))
15770 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15771 (when (and vals (string-match "\\S-" vals))
15772 (setq vals (car (read-from-string (concat "(" vals ")"))))
15773 (setq vals (mapcar (lambda (x)
15774 (cond ((stringp x) x)
15775 ((numberp x) (number-to-string x))
15776 ((symbolp x) (symbol-name x))
15777 (t "???")))
15778 vals)))))
15779 (when (member ":ETC" vals)
15780 (setq vals (remove ":ETC" vals))
15781 (org-add-props (car vals) '(org-unrestricted t)))
15782 (if table (mapcar 'list vals) vals)))
15784 (defun org-property-previous-allowed-value (&optional _previous)
15785 "Switch to the next allowed value for this property."
15786 (interactive)
15787 (org-property-next-allowed-value t))
15789 (defun org-property-next-allowed-value (&optional previous)
15790 "Switch to the next allowed value for this property."
15791 (interactive)
15792 (unless (org-at-property-p)
15793 (user-error "Not at a property"))
15794 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15795 (key (match-string 2))
15796 (value (match-string 3))
15797 (allowed (or (org-property-get-allowed-values (point) key)
15798 (and (member value '("[ ]" "[-]" "[X]"))
15799 '("[ ]" "[X]"))))
15800 (heading (save-match-data (nth 4 (org-heading-components))))
15801 nval)
15802 (unless allowed
15803 (user-error "Allowed values for this property have not been defined"))
15804 (when previous (setq allowed (reverse allowed)))
15805 (when (member value allowed)
15806 (setq nval (car (cdr (member value allowed)))))
15807 (setq nval (or nval (car allowed)))
15808 (when (equal nval value)
15809 (user-error "Only one allowed value for this property"))
15810 (org-at-property-p)
15811 (replace-match (concat " :" key ": " nval) t t)
15812 (org-indent-line)
15813 (beginning-of-line 1)
15814 (skip-chars-forward " \t")
15815 (when (equal prop org-effort-property)
15816 (org-refresh-property
15817 '((effort . identity)
15818 (effort-minutes . org-duration-to-minutes))
15819 nval)
15820 (when (string= org-clock-current-task heading)
15821 (setq org-clock-effort nval)
15822 (org-clock-update-mode-line)))
15823 (run-hook-with-args 'org-property-changed-functions key nval)))
15825 (defun org-find-olp (path &optional this-buffer)
15826 "Return a marker pointing to the entry at outline path OLP.
15827 If anything goes wrong, throw an error.
15828 You can wrap this call to catch the error like this:
15830 (condition-case msg
15831 (org-mobile-locate-entry (match-string 4))
15832 (error (nth 1 msg)))
15834 The return value will then be either a string with the error message,
15835 or a marker if everything is OK.
15837 If THIS-BUFFER is set, the outline path does not contain a file,
15838 only headings."
15839 (let* ((file (if this-buffer buffer-file-name (pop path)))
15840 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15841 (level 1)
15842 (lmin 1)
15843 (lmax 1)
15844 end found flevel)
15845 (unless buffer (error "File not found :%s" file))
15846 (with-current-buffer buffer
15847 (unless (derived-mode-p 'org-mode)
15848 (error "Buffer %s needs to be in Org mode" buffer))
15849 (org-with-wide-buffer
15850 (goto-char (point-min))
15851 (dolist (heading path)
15852 (let ((re (format org-complex-heading-regexp-format
15853 (regexp-quote heading)))
15854 (cnt 0))
15855 (while (re-search-forward re end t)
15856 (setq level (- (match-end 1) (match-beginning 1)))
15857 (when (and (>= level lmin) (<= level lmax))
15858 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15859 (when (= cnt 0)
15860 (error "Heading not found on level %d: %s" lmax heading))
15861 (when (> cnt 1)
15862 (error "Heading not unique on level %d: %s" lmax heading))
15863 (goto-char found)
15864 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15865 (setq end (save-excursion (org-end-of-subtree t t)))))
15866 (when (org-at-heading-p)
15867 (point-marker))))))
15869 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15870 "Find node HEADING in BUFFER.
15871 Return a marker to the heading if it was found, or nil if not.
15872 If POS-ONLY is set, return just the position instead of a marker.
15874 The heading text must match exact, but it may have a TODO keyword,
15875 a priority cookie and tags in the standard locations."
15876 (with-current-buffer (or buffer (current-buffer))
15877 (org-with-wide-buffer
15878 (goto-char (point-min))
15879 (let (case-fold-search)
15880 (when (re-search-forward
15881 (format org-complex-heading-regexp-format
15882 (regexp-quote heading)) nil t)
15883 (if pos-only
15884 (match-beginning 0)
15885 (move-marker (make-marker) (match-beginning 0))))))))
15887 (defun org-find-exact-heading-in-directory (heading &optional dir)
15888 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15889 When the target headline is found, return a marker to this location."
15890 (let ((files (directory-files (or dir default-directory)
15891 t "\\`[^.#].*\\.org\\'"))
15892 visiting m buffer)
15893 (catch 'found
15894 (dolist (file files)
15895 (message "trying %s" file)
15896 (setq visiting (org-find-base-buffer-visiting file))
15897 (setq buffer (or visiting (find-file-noselect file)))
15898 (setq m (org-find-exact-headline-in-buffer
15899 heading buffer))
15900 (when (and (not m) (not visiting)) (kill-buffer buffer))
15901 (and m (throw 'found m))))))
15903 (defun org-find-entry-with-id (ident)
15904 "Locate the entry that contains the ID property with exact value IDENT.
15905 IDENT can be a string, a symbol or a number, this function will search for
15906 the string representation of it.
15907 Return the position where this entry starts, or nil if there is no such entry."
15908 (interactive "sID: ")
15909 (let ((id (cond
15910 ((stringp ident) ident)
15911 ((symbolp ident) (symbol-name ident))
15912 ((numberp ident) (number-to-string ident))
15913 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15914 (org-with-wide-buffer (org-find-property "ID" id))))
15916 ;;;; Timestamps
15918 (defvar org-last-changed-timestamp nil)
15919 (defvar org-last-inserted-timestamp nil
15920 "The last time stamp inserted with `org-insert-time-stamp'.")
15922 (defun org-time-stamp (arg &optional inactive)
15923 "Prompt for a date/time and insert a time stamp.
15925 If the user specifies a time like HH:MM or if this command is
15926 called with at least one prefix argument, the time stamp contains
15927 the date and the time. Otherwise, only the date is included.
15929 All parts of a date not specified by the user are filled in from
15930 the timestamp at point, if any, or the current date/time
15931 otherwise.
15933 If there is already a timestamp at the cursor, it is replaced.
15935 With two universal prefix arguments, insert an active timestamp
15936 with the current time without prompting the user.
15938 When called from lisp, the timestamp is inactive if INACTIVE is
15939 non-nil."
15940 (interactive "P")
15941 (let* ((ts (cond
15942 ((org-at-date-range-p t)
15943 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15944 ((org-at-timestamp-p 'lax) (match-string 0))))
15945 ;; Default time is either the timestamp at point or today.
15946 ;; When entering a range, only the range start is considered.
15947 (default-time (if (not ts) (current-time)
15948 (apply #'encode-time (org-parse-time-string ts))))
15949 (default-input (and ts (org-get-compact-tod ts)))
15950 (repeater (and ts
15951 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15952 (match-string 0 ts)))
15953 org-time-was-given
15954 org-end-time-was-given
15955 (time
15956 (and (if (equal arg '(16)) (current-time)
15957 ;; Preserve `this-command' and `last-command'.
15958 (let ((this-command this-command)
15959 (last-command last-command))
15960 (org-read-date
15961 arg 'totime nil nil default-time default-input
15962 inactive))))))
15963 (cond
15964 ((and ts
15965 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15966 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15967 (insert "--")
15968 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15970 ;; Make sure we're on a timestamp. When in the middle of a date
15971 ;; range, move arbitrarily to range end.
15972 (unless (org-at-timestamp-p 'lax)
15973 (skip-chars-forward "-")
15974 (org-at-timestamp-p 'lax))
15975 (replace-match "")
15976 (setq org-last-changed-timestamp
15977 (org-insert-time-stamp
15978 time (or org-time-was-given arg)
15979 inactive nil nil (list org-end-time-was-given)))
15980 (when repeater
15981 (backward-char)
15982 (insert " " repeater)
15983 (setq org-last-changed-timestamp
15984 (concat (substring org-last-inserted-timestamp 0 -1)
15985 " " repeater ">")))
15986 (message "Timestamp updated"))
15987 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
15988 (t (org-insert-time-stamp
15989 time (or org-time-was-given arg) inactive nil nil
15990 (list org-end-time-was-given))))))
15992 ;; FIXME: can we use this for something else, like computing time differences?
15993 (defun org-get-compact-tod (s)
15994 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15995 (let* ((t1 (match-string 1 s))
15996 (h1 (string-to-number (match-string 2 s)))
15997 (m1 (string-to-number (match-string 3 s)))
15998 (t2 (and (match-end 4) (match-string 5 s)))
15999 (h2 (and t2 (string-to-number (match-string 6 s))))
16000 (m2 (and t2 (string-to-number (match-string 7 s))))
16001 dh dm)
16002 (if (not t2)
16004 (setq dh (- h2 h1) dm (- m2 m1))
16005 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16006 (concat t1 "+" (number-to-string dh)
16007 (and (/= 0 dm) (format ":%02d" dm)))))))
16009 (defun org-time-stamp-inactive (&optional arg)
16010 "Insert an inactive time stamp.
16011 An inactive time stamp is enclosed in square brackets instead of angle
16012 brackets. It is inactive in the sense that it does not trigger agenda entries,
16013 does not link to the calendar and cannot be changed with the S-cursor keys.
16014 So these are more for recording a certain time/date."
16015 (interactive "P")
16016 (org-time-stamp arg 'inactive))
16018 (defvar org-date-ovl (make-overlay 1 1))
16019 (overlay-put org-date-ovl 'face 'org-date-selected)
16020 (delete-overlay org-date-ovl)
16022 (defvar org-ans1) ; dynamically scoped parameter
16023 (defvar org-ans2) ; dynamically scoped parameter
16025 (defvar org-plain-time-of-day-regexp) ; defined below
16027 (defvar org-overriding-default-time nil) ; dynamically scoped
16028 (defvar org-read-date-overlay nil)
16029 (defvar org-dcst nil) ; dynamically scoped
16030 (defvar org-read-date-history nil)
16031 (defvar org-read-date-final-answer nil)
16032 (defvar org-read-date-analyze-futurep nil)
16033 (defvar org-read-date-analyze-forced-year nil)
16034 (defvar org-read-date-inactive)
16036 (defvar org-read-date-minibuffer-local-map
16037 (let* ((map (make-sparse-keymap)))
16038 (set-keymap-parent map minibuffer-local-map)
16039 (org-defkey map (kbd ".")
16040 (lambda () (interactive)
16041 ;; Are we at the beginning of the prompt?
16042 (if (looking-back "^[^:]+: "
16043 (let ((inhibit-field-text-motion t))
16044 (line-beginning-position)))
16045 (org-eval-in-calendar '(calendar-goto-today))
16046 (insert "."))))
16047 (org-defkey map (kbd "C-.")
16048 (lambda () (interactive)
16049 (org-eval-in-calendar '(calendar-goto-today))))
16050 (org-defkey map (kbd "M-S-<left>")
16051 (lambda () (interactive)
16052 (org-eval-in-calendar '(calendar-backward-month 1))))
16053 (org-defkey map (kbd "ESC S-<left>")
16054 (lambda () (interactive)
16055 (org-eval-in-calendar '(calendar-backward-month 1))))
16056 (org-defkey map (kbd "M-S-<right>")
16057 (lambda () (interactive)
16058 (org-eval-in-calendar '(calendar-forward-month 1))))
16059 (org-defkey map (kbd "ESC S-<right>")
16060 (lambda () (interactive)
16061 (org-eval-in-calendar '(calendar-forward-month 1))))
16062 (org-defkey map (kbd "M-S-<up>")
16063 (lambda () (interactive)
16064 (org-eval-in-calendar '(calendar-backward-year 1))))
16065 (org-defkey map (kbd "ESC S-<up>")
16066 (lambda () (interactive)
16067 (org-eval-in-calendar '(calendar-backward-year 1))))
16068 (org-defkey map (kbd "M-S-<down>")
16069 (lambda () (interactive)
16070 (org-eval-in-calendar '(calendar-forward-year 1))))
16071 (org-defkey map (kbd "ESC S-<down>")
16072 (lambda () (interactive)
16073 (org-eval-in-calendar '(calendar-forward-year 1))))
16074 (org-defkey map (kbd "S-<up>")
16075 (lambda () (interactive)
16076 (org-eval-in-calendar '(calendar-backward-week 1))))
16077 (org-defkey map (kbd "S-<down>")
16078 (lambda () (interactive)
16079 (org-eval-in-calendar '(calendar-forward-week 1))))
16080 (org-defkey map (kbd "S-<left>")
16081 (lambda () (interactive)
16082 (org-eval-in-calendar '(calendar-backward-day 1))))
16083 (org-defkey map (kbd "S-<right>")
16084 (lambda () (interactive)
16085 (org-eval-in-calendar '(calendar-forward-day 1))))
16086 (org-defkey map "!"
16087 (lambda () (interactive)
16088 (org-eval-in-calendar '(diary-view-entries))
16089 (message "")))
16090 (org-defkey map ">"
16091 (lambda () (interactive)
16092 (org-eval-in-calendar '(calendar-scroll-left 1))))
16093 (org-defkey map "<"
16094 (lambda () (interactive)
16095 (org-eval-in-calendar '(calendar-scroll-right 1))))
16096 (org-defkey map "\C-v"
16097 (lambda () (interactive)
16098 (org-eval-in-calendar
16099 '(calendar-scroll-left-three-months 1))))
16100 (org-defkey map "\M-v"
16101 (lambda () (interactive)
16102 (org-eval-in-calendar
16103 '(calendar-scroll-right-three-months 1))))
16104 map)
16105 "Keymap for minibuffer commands when using `org-read-date'.")
16107 (defvar org-def)
16108 (defvar org-defdecode)
16109 (defvar org-with-time)
16111 (defvar calendar-setup) ; Dynamically scoped.
16112 (defun org-read-date (&optional with-time to-time from-string prompt
16113 default-time default-input inactive)
16114 "Read a date, possibly a time, and make things smooth for the user.
16115 The prompt will suggest to enter an ISO date, but you can also enter anything
16116 which will at least partially be understood by `parse-time-string'.
16117 Unrecognized parts of the date will default to the current day, month, year,
16118 hour and minute. If this command is called to replace a timestamp at point,
16119 or to enter the second timestamp of a range, the default time is taken
16120 from the existing stamp. Furthermore, the command prefers the future,
16121 so if you are giving a date where the year is not given, and the day-month
16122 combination is already past in the current year, it will assume you
16123 mean next year. For details, see the manual. A few examples:
16125 3-2-5 --> 2003-02-05
16126 feb 15 --> currentyear-02-15
16127 2/15 --> currentyear-02-15
16128 sep 12 9 --> 2009-09-12
16129 12:45 --> today 12:45
16130 22 sept 0:34 --> currentyear-09-22 0:34
16131 12 --> currentyear-currentmonth-12
16132 Fri --> nearest Friday after today
16133 -Tue --> last Tuesday
16134 etc.
16136 Furthermore you can specify a relative date by giving, as the *first* thing
16137 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16138 change in days weeks, months, years.
16139 With a single plus or minus, the date is relative to today. With a double
16140 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16141 +4d --> four days from today
16142 +4 --> same as above
16143 +2w --> two weeks from today
16144 ++5 --> five days from default date
16146 The function understands only English month and weekday abbreviations.
16148 While prompting, a calendar is popped up - you can also select the
16149 date with the mouse (button 1). The calendar shows a period of three
16150 months. To scroll it to other months, use the keys `>' and `<'.
16151 If you don't like the calendar, turn it off with
16152 (setq org-read-date-popup-calendar nil)
16154 With optional argument TO-TIME, the date will immediately be converted
16155 to an internal time.
16156 With an optional argument WITH-TIME, the prompt will suggest to
16157 also insert a time. Note that when WITH-TIME is not set, you can
16158 still enter a time, and this function will inform the calling routine
16159 about this change. The calling routine may then choose to change the
16160 format used to insert the time stamp into the buffer to include the time.
16161 With optional argument FROM-STRING, read from this string instead from
16162 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16163 the time/date that is used for everything that is not specified by the
16164 user."
16165 (require 'parse-time)
16166 (let* ((org-with-time with-time)
16167 (org-time-stamp-rounding-minutes
16168 (if (equal org-with-time '(16))
16169 '(0 0)
16170 org-time-stamp-rounding-minutes))
16171 (org-dcst org-display-custom-times)
16172 (ct (org-current-time))
16173 (org-def (or org-overriding-default-time default-time ct))
16174 (org-defdecode (decode-time org-def))
16175 (cur-frame (selected-frame))
16176 (mouse-autoselect-window nil) ; Don't let the mouse jump
16177 (calendar-setup
16178 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16179 (calendar-move-hook nil)
16180 (calendar-view-diary-initially-flag nil)
16181 (calendar-view-holidays-initially-flag nil)
16182 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16183 ;; Rationalize `org-def' and `org-defdecode', if required.
16184 (when (< (nth 2 org-defdecode) org-extend-today-until)
16185 (setf (nth 2 org-defdecode) -1)
16186 (setf (nth 1 org-defdecode) 59)
16187 (setq org-def (apply #'encode-time org-defdecode))
16188 (setq org-defdecode (decode-time org-def)))
16189 (let* ((timestr (format-time-string
16190 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16191 org-def))
16192 (prompt (concat (if prompt (concat prompt " ") "")
16193 (format "Date+time [%s]: " timestr))))
16194 (cond
16195 (from-string (setq ans from-string))
16196 (org-read-date-popup-calendar
16197 (save-excursion
16198 (save-window-excursion
16199 (calendar)
16200 (when (eq calendar-setup 'calendar-only)
16201 (setq cal-frame
16202 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16203 (select-frame cal-frame))
16204 (org-eval-in-calendar '(setq cursor-type nil) t)
16205 (unwind-protect
16206 (progn
16207 (calendar-forward-day (- (time-to-days org-def)
16208 (calendar-absolute-from-gregorian
16209 (calendar-current-date))))
16210 (org-eval-in-calendar nil t)
16211 (let* ((old-map (current-local-map))
16212 (map (copy-keymap calendar-mode-map))
16213 (minibuffer-local-map
16214 (copy-keymap org-read-date-minibuffer-local-map)))
16215 (org-defkey map (kbd "RET") 'org-calendar-select)
16216 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16217 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16218 (unwind-protect
16219 (progn
16220 (use-local-map map)
16221 (setq org-read-date-inactive inactive)
16222 (add-hook 'post-command-hook 'org-read-date-display)
16223 (setq org-ans0
16224 (read-string prompt
16225 default-input
16226 'org-read-date-history
16227 nil))
16228 ;; org-ans0: from prompt
16229 ;; org-ans1: from mouse click
16230 ;; org-ans2: from calendar motion
16231 (setq ans
16232 (concat org-ans0 " " (or org-ans1 org-ans2))))
16233 (remove-hook 'post-command-hook 'org-read-date-display)
16234 (use-local-map old-map)
16235 (when org-read-date-overlay
16236 (delete-overlay org-read-date-overlay)
16237 (setq org-read-date-overlay nil)))))
16238 (bury-buffer "*Calendar*")
16239 (when cal-frame
16240 (delete-frame cal-frame)
16241 (select-frame-set-input-focus cur-frame))))))
16243 (t ; Naked prompt only
16244 (unwind-protect
16245 (setq ans (read-string prompt default-input
16246 'org-read-date-history timestr))
16247 (when org-read-date-overlay
16248 (delete-overlay org-read-date-overlay)
16249 (setq org-read-date-overlay nil))))))
16251 (setq final (org-read-date-analyze ans org-def org-defdecode))
16253 (when org-read-date-analyze-forced-year
16254 (message "Year was forced into %s"
16255 (if org-read-date-force-compatible-dates
16256 "compatible range (1970-2037)"
16257 "range representable on this machine"))
16258 (ding))
16260 ;; One round trip to get rid of 34th of August and stuff like that....
16261 (setq final (decode-time (apply 'encode-time final)))
16263 (setq org-read-date-final-answer ans)
16265 (if to-time
16266 (apply 'encode-time final)
16267 (if (and (boundp 'org-time-was-given) org-time-was-given)
16268 (format "%04d-%02d-%02d %02d:%02d"
16269 (nth 5 final) (nth 4 final) (nth 3 final)
16270 (nth 2 final) (nth 1 final))
16271 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16273 (defun org-read-date-display ()
16274 "Display the current date prompt interpretation in the minibuffer."
16275 (when org-read-date-display-live
16276 (when org-read-date-overlay
16277 (delete-overlay org-read-date-overlay))
16278 (when (minibufferp (current-buffer))
16279 (save-excursion
16280 (end-of-line 1)
16281 (while (not (equal (buffer-substring
16282 (max (point-min) (- (point) 4)) (point))
16283 " "))
16284 (insert " ")))
16285 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16286 " " (or org-ans1 org-ans2)))
16287 (org-end-time-was-given nil)
16288 (f (org-read-date-analyze ans org-def org-defdecode))
16289 (fmts (if org-dcst
16290 org-time-stamp-custom-formats
16291 org-time-stamp-formats))
16292 (fmt (if (or org-with-time
16293 (and (boundp 'org-time-was-given) org-time-was-given))
16294 (cdr fmts)
16295 (car fmts)))
16296 (txt (format-time-string fmt (apply 'encode-time f)))
16297 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16298 (txt (concat "=> " txt)))
16299 (when (and org-end-time-was-given
16300 (string-match org-plain-time-of-day-regexp txt))
16301 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16302 org-end-time-was-given
16303 (substring txt (match-end 0)))))
16304 (when org-read-date-analyze-futurep
16305 (setq txt (concat txt " (=>F)")))
16306 (setq org-read-date-overlay
16307 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16308 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16310 (defun org-read-date-analyze (ans def defdecode)
16311 "Analyze the combined answer of the date prompt."
16312 ;; FIXME: cleanup and comment
16313 ;; Pass `current-time' result to `decode-time' (instead of calling
16314 ;; without arguments) so that only `current-time' has to be
16315 ;; overridden in tests.
16316 (let ((org-def def)
16317 (org-defdecode defdecode)
16318 (nowdecode (decode-time (current-time)))
16319 delta deltan deltaw deltadef year month day
16320 hour minute second wday pm h2 m2 tl wday1
16321 iso-year iso-weekday iso-week iso-date futurep kill-year)
16322 (setq org-read-date-analyze-futurep nil
16323 org-read-date-analyze-forced-year nil)
16324 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16325 (setq ans "+0"))
16327 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16328 (setq ans (replace-match "" t t ans)
16329 deltan (car delta)
16330 deltaw (nth 1 delta)
16331 deltadef (nth 2 delta)))
16333 ;; Check if there is an iso week date in there. If yes, store the
16334 ;; info and postpone interpreting it until the rest of the parsing
16335 ;; is done.
16336 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16337 (setq iso-year (when (match-end 1)
16338 (org-small-year-to-year
16339 (string-to-number (match-string 1 ans))))
16340 iso-weekday (when (match-end 3)
16341 (string-to-number (match-string 3 ans)))
16342 iso-week (string-to-number (match-string 2 ans)))
16343 (setq ans (replace-match "" t t ans)))
16345 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16346 (when (string-match
16347 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16348 (setq year (if (match-end 2)
16349 (string-to-number (match-string 2 ans))
16350 (progn (setq kill-year t)
16351 (string-to-number (format-time-string "%Y"))))
16352 month (string-to-number (match-string 3 ans))
16353 day (string-to-number (match-string 4 ans)))
16354 (setq year (org-small-year-to-year year))
16355 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16356 t nil ans)))
16358 ;; Help matching dotted european dates
16359 (when (string-match
16360 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16361 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16362 (setq kill-year t)
16363 (string-to-number (format-time-string "%Y")))
16364 day (string-to-number (match-string 1 ans))
16365 month (string-to-number (match-string 2 ans))
16366 ans (replace-match (format "%04d-%02d-%02d" year month day)
16367 t nil ans)))
16369 ;; Help matching american dates, like 5/30 or 5/30/7
16370 (when (string-match
16371 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16372 (setq year (if (match-end 4)
16373 (string-to-number (match-string 4 ans))
16374 (progn (setq kill-year t)
16375 (string-to-number (format-time-string "%Y"))))
16376 month (string-to-number (match-string 1 ans))
16377 day (string-to-number (match-string 2 ans)))
16378 (setq year (org-small-year-to-year year))
16379 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16380 t nil ans)))
16381 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16382 ;; If there is a time with am/pm, and *no* time without it, we convert
16383 ;; so that matching will be successful.
16384 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16385 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16386 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16387 (setq hour (string-to-number (match-string 1 ans))
16388 minute (if (match-end 3)
16389 (string-to-number (match-string 3 ans))
16391 pm (equal ?p
16392 (string-to-char (downcase (match-string 4 ans)))))
16393 (if (and (= hour 12) (not pm))
16394 (setq hour 0)
16395 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16396 (setq ans (replace-match (format "%02d:%02d" hour minute)
16397 t t ans))))
16399 ;; Check if a time range is given as a duration
16400 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16401 (setq hour (string-to-number (match-string 1 ans))
16402 h2 (+ hour (string-to-number (match-string 3 ans)))
16403 minute (string-to-number (match-string 2 ans))
16404 m2 (+ minute (if (match-end 5) (string-to-number
16405 (match-string 5 ans))0)))
16406 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16407 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16408 t t ans)))
16410 ;; Check if there is a time range
16411 (when (boundp 'org-end-time-was-given)
16412 (setq org-time-was-given nil)
16413 (when (and (string-match org-plain-time-of-day-regexp ans)
16414 (match-end 8))
16415 (setq org-end-time-was-given (match-string 8 ans))
16416 (setq ans (concat (substring ans 0 (match-beginning 7))
16417 (substring ans (match-end 7))))))
16419 (setq tl (parse-time-string ans)
16420 day (or (nth 3 tl) (nth 3 org-defdecode))
16421 month
16422 (cond ((nth 4 tl))
16423 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16424 ;; Day was specified. Make sure DAY+MONTH
16425 ;; combination happens in the future.
16426 ((nth 3 tl)
16427 (setq futurep t)
16428 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16429 (nth 4 nowdecode)))
16430 (t (nth 4 org-defdecode)))
16431 year
16432 (cond ((and (not kill-year) (nth 5 tl)))
16433 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16434 ;; Month was guessed in the future and is at least
16435 ;; equal to NOWDECODE's. Fix year accordingly.
16436 (futurep
16437 (if (or (> month (nth 4 nowdecode))
16438 (>= day (nth 3 nowdecode)))
16439 (nth 5 nowdecode)
16440 (1+ (nth 5 nowdecode))))
16441 ;; Month was specified. Make sure MONTH+YEAR
16442 ;; combination happens in the future.
16443 ((nth 4 tl)
16444 (setq futurep t)
16445 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16446 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16447 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16448 (t (nth 5 nowdecode))))
16449 (t (nth 5 org-defdecode)))
16450 hour (or (nth 2 tl) (nth 2 org-defdecode))
16451 minute (or (nth 1 tl) (nth 1 org-defdecode))
16452 second (or (nth 0 tl) 0)
16453 wday (nth 6 tl))
16455 (when (and (eq org-read-date-prefer-future 'time)
16456 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16457 (equal day (nth 3 nowdecode))
16458 (equal month (nth 4 nowdecode))
16459 (equal year (nth 5 nowdecode))
16460 (nth 2 tl)
16461 (or (< (nth 2 tl) (nth 2 nowdecode))
16462 (and (= (nth 2 tl) (nth 2 nowdecode))
16463 (nth 1 tl)
16464 (< (nth 1 tl) (nth 1 nowdecode)))))
16465 (setq day (1+ day)
16466 futurep t))
16468 ;; Special date definitions below
16469 (cond
16470 (iso-week
16471 ;; There was an iso week
16472 (require 'cal-iso)
16473 (setq futurep nil)
16474 (setq year (or iso-year year)
16475 day (or iso-weekday wday 1)
16476 wday nil ; to make sure that the trigger below does not match
16477 iso-date (calendar-gregorian-from-absolute
16478 (calendar-iso-to-absolute
16479 (list iso-week day year))))
16480 ; FIXME: Should we also push ISO weeks into the future?
16481 ; (when (and org-read-date-prefer-future
16482 ; (not iso-year)
16483 ; (< (calendar-absolute-from-gregorian iso-date)
16484 ; (time-to-days (current-time))))
16485 ; (setq year (1+ year)
16486 ; iso-date (calendar-gregorian-from-absolute
16487 ; (calendar-iso-to-absolute
16488 ; (list iso-week day year)))))
16489 (setq month (car iso-date)
16490 year (nth 2 iso-date)
16491 day (nth 1 iso-date)))
16492 (deltan
16493 (setq futurep nil)
16494 (unless deltadef
16495 ;; Pass `current-time' result to `decode-time' (instead of
16496 ;; calling without arguments) so that only `current-time' has
16497 ;; to be overridden in tests.
16498 (let ((now (decode-time (current-time))))
16499 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16500 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16501 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16502 ((equal deltaw "m") (setq month (+ month deltan)))
16503 ((equal deltaw "y") (setq year (+ year deltan)))))
16504 ((and wday (not (nth 3 tl)))
16505 ;; Weekday was given, but no day, so pick that day in the week
16506 ;; on or after the derived date.
16507 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16508 (unless (equal wday wday1)
16509 (setq day (+ day (% (- wday wday1 -7) 7))))))
16510 (when (and (boundp 'org-time-was-given)
16511 (nth 2 tl))
16512 (setq org-time-was-given t))
16513 (when (< year 100) (setq year (+ 2000 year)))
16514 ;; Check of the date is representable
16515 (if org-read-date-force-compatible-dates
16516 (progn
16517 (when (< year 1970)
16518 (setq year 1970 org-read-date-analyze-forced-year t))
16519 (when (> year 2037)
16520 (setq year 2037 org-read-date-analyze-forced-year t)))
16521 (condition-case nil
16522 (ignore (encode-time second minute hour day month year))
16523 (error
16524 (setq year (nth 5 org-defdecode))
16525 (setq org-read-date-analyze-forced-year t))))
16526 (setq org-read-date-analyze-futurep futurep)
16527 (list second minute hour day month year)))
16529 (defvar parse-time-weekdays)
16530 (defun org-read-date-get-relative (s today default)
16531 "Check string S for special relative date string.
16532 TODAY and DEFAULT are internal times, for today and for a default.
16533 Return shift list (N what def-flag)
16534 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16535 N is the number of WHATs to shift.
16536 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16537 the DEFAULT date rather than TODAY."
16538 (require 'parse-time)
16539 (when (and
16540 (string-match
16541 (concat
16542 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16543 "\\([0-9]+\\)?"
16544 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16545 "\\([ \t]\\|$\\)") s)
16546 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16547 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16548 (string-to-char (substring (match-string 1 s) -1))
16549 ?+))
16550 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16551 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16552 (what (if (match-end 3) (match-string 3 s) "d"))
16553 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16554 (date (if rel default today))
16555 (wday (nth 6 (decode-time date)))
16556 delta)
16557 (if wday1
16558 (progn
16559 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16560 (when (= delta 0) (setq delta 7))
16561 (when (= dir ?-)
16562 (setq delta (- delta 7))
16563 (when (= delta 0) (setq delta -7)))
16564 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16565 (list delta "d" rel))
16566 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16568 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16569 "Turn a user-specified date into the internal representation.
16570 The internal representation needed by the calendar is (month day year).
16571 This is a wrapper to handle the brain-dead convention in calendar that
16572 user function argument order change dependent on argument order."
16573 (pcase calendar-date-style
16574 (`american (list arg1 arg2 arg3))
16575 (`european (list arg2 arg1 arg3))
16576 (`iso (list arg2 arg3 arg1))))
16578 (defun org-eval-in-calendar (form &optional keepdate)
16579 "Eval FORM in the calendar window and return to current window.
16580 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16581 (let ((sf (selected-frame))
16582 (sw (selected-window)))
16583 (select-window (get-buffer-window "*Calendar*" t))
16584 (eval form)
16585 (when (and (not keepdate) (calendar-cursor-to-date))
16586 (let* ((date (calendar-cursor-to-date))
16587 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16588 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16589 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16590 (select-window sw)
16591 (select-frame-set-input-focus sf)))
16593 (defun org-calendar-select ()
16594 "Return to `org-read-date' with the date currently selected.
16595 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16596 (interactive)
16597 (when (calendar-cursor-to-date)
16598 (let* ((date (calendar-cursor-to-date))
16599 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16600 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16601 (when (active-minibuffer-window) (exit-minibuffer))))
16603 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16604 "Insert a date stamp for the date given by the internal TIME.
16605 See `format-time-string' for the format of TIME.
16606 WITH-HM means use the stamp format that includes the time of the day.
16607 INACTIVE means use square brackets instead of angular ones, so that the
16608 stamp will not contribute to the agenda.
16609 PRE and POST are optional strings to be inserted before and after the
16610 stamp.
16611 The command returns the inserted time stamp."
16612 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16613 stamp)
16614 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16615 (insert-before-markers (or pre ""))
16616 (when (listp extra)
16617 (setq extra (car extra))
16618 (if (and (stringp extra)
16619 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16620 (setq extra (format "-%02d:%02d"
16621 (string-to-number (match-string 1 extra))
16622 (string-to-number (match-string 2 extra))))
16623 (setq extra nil)))
16624 (when extra
16625 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16626 (insert-before-markers (setq stamp (format-time-string fmt time)))
16627 (insert-before-markers (or post ""))
16628 (setq org-last-inserted-timestamp stamp)))
16630 (defun org-toggle-time-stamp-overlays ()
16631 "Toggle the use of custom time stamp formats."
16632 (interactive)
16633 (setq org-display-custom-times (not org-display-custom-times))
16634 (unless org-display-custom-times
16635 (let ((p (point-min)) (bmp (buffer-modified-p)))
16636 (while (setq p (next-single-property-change p 'display))
16637 (when (and (get-text-property p 'display)
16638 (eq (get-text-property p 'face) 'org-date))
16639 (remove-text-properties
16640 p (setq p (next-single-property-change p 'display))
16641 '(display t))))
16642 (set-buffer-modified-p bmp)))
16643 (org-restart-font-lock)
16644 (setq org-table-may-need-update t)
16645 (if org-display-custom-times
16646 (message "Time stamps are overlaid with custom format")
16647 (message "Time stamp overlays removed")))
16649 (defun org-display-custom-time (beg end)
16650 "Overlay modified time stamp format over timestamp between BEG and END."
16651 (let* ((ts (buffer-substring beg end))
16652 t1 with-hm tf time str (off 0))
16653 (save-match-data
16654 (setq t1 (org-parse-time-string ts t))
16655 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16656 (setq off (- (match-end 0) (match-beginning 0)))))
16657 (setq end (- end off))
16658 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16659 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16660 time (org-fix-decoded-time t1)
16661 str (org-add-props
16662 (format-time-string
16663 (substring tf 1 -1) (apply 'encode-time time))
16664 nil 'mouse-face 'highlight))
16665 (put-text-property beg end 'display str)))
16667 (defun org-fix-decoded-time (time)
16668 "Set 0 instead of nil for the first 6 elements of time.
16669 Don't touch the rest."
16670 (let ((n 0))
16671 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16673 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16674 "Difference between TIMESTAMP-STRING and now in days.
16675 If SECONDS is non-nil, return the difference in seconds."
16676 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16677 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16678 (funcall fdiff (current-time)))))
16680 (defun org-deadline-close-p (timestamp-string &optional ndays)
16681 "Is the time in TIMESTAMP-STRING close to the current date?"
16682 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16683 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16684 (not (org-entry-is-done-p))))
16686 (defun org-get-wdays (ts &optional delay zero-delay)
16687 "Get the deadline lead time appropriate for timestring TS.
16688 When DELAY is non-nil, get the delay time for scheduled items
16689 instead of the deadline lead time. When ZERO-DELAY is non-nil
16690 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16691 don't try to find the delay cookie in the scheduled timestamp."
16692 (let ((tv (if delay org-scheduled-delay-days
16693 org-deadline-warning-days)))
16694 (cond
16695 ((or (and delay (< tv 0))
16696 (and delay zero-delay (<= tv 0))
16697 (and (not delay) (<= tv 0)))
16698 ;; Enforce this value no matter what
16699 (- tv))
16700 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16701 ;; lead time is specified.
16702 (floor (* (string-to-number (match-string 1 ts))
16703 (cdr (assoc (match-string 2 ts)
16704 '(("d" . 1) ("w" . 7)
16705 ("m" . 30.4) ("y" . 365.25)
16706 ("h" . 0.041667)))))))
16707 ;; go for the default.
16708 (t tv))))
16710 (defun org-calendar-select-mouse (ev)
16711 "Return to `org-read-date' with the date currently selected.
16712 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16713 (interactive "e")
16714 (mouse-set-point ev)
16715 (when (calendar-cursor-to-date)
16716 (let* ((date (calendar-cursor-to-date))
16717 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16718 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16719 (when (active-minibuffer-window) (exit-minibuffer))))
16721 (defun org-check-deadlines (ndays)
16722 "Check if there are any deadlines due or past due.
16723 A deadline is considered due if it happens within `org-deadline-warning-days'
16724 days from today's date. If the deadline appears in an entry marked DONE,
16725 it is not shown. A numeric prefix argument NDAYS can be used to test that
16726 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16727 are shown."
16728 (interactive "P")
16729 (let* ((org-warn-days
16730 (cond
16731 ((equal ndays '(4)) 100000)
16732 (ndays (prefix-numeric-value ndays))
16733 (t (abs org-deadline-warning-days))))
16734 (case-fold-search nil)
16735 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16736 (callback
16737 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16738 (message "%d deadlines past-due or due within %d days"
16739 (org-occur regexp nil callback)
16740 org-warn-days)))
16742 (defsubst org-re-timestamp (type)
16743 "Return a regexp for timestamp TYPE.
16744 Allowed values for TYPE are:
16746 all: all timestamps
16747 active: only active timestamps (<...>)
16748 inactive: only inactive timestamps ([...])
16749 scheduled: only scheduled timestamps
16750 deadline: only deadline timestamps
16751 closed: only closed time-stamps
16753 When TYPE is nil, fall back on returning a regexp that matches
16754 both scheduled and deadline timestamps."
16755 (cl-case type
16756 (all org-ts-regexp-both)
16757 (active org-ts-regexp)
16758 (inactive org-ts-regexp-inactive)
16759 (scheduled org-scheduled-time-regexp)
16760 (deadline org-deadline-time-regexp)
16761 (closed org-closed-time-regexp)
16762 (otherwise
16763 (concat "\\<"
16764 (regexp-opt (list org-deadline-string org-scheduled-string))
16765 " *<\\([^>]+\\)>"))))
16767 (defun org-check-before-date (d)
16768 "Check if there are deadlines or scheduled entries before date D."
16769 (interactive (list (org-read-date)))
16770 (let* ((case-fold-search nil)
16771 (regexp (org-re-timestamp org-ts-type))
16772 (ts-type org-ts-type)
16773 (callback
16774 (lambda ()
16775 (let ((match (match-string 1)))
16776 (and (if (memq ts-type '(active inactive all))
16777 (eq (org-element-type (save-excursion
16778 (backward-char)
16779 (org-element-context)))
16780 'timestamp)
16781 (org-at-planning-p))
16782 (time-less-p
16783 (org-time-string-to-time match)
16784 (org-time-string-to-time d)))))))
16785 (message "%d entries before %s"
16786 (org-occur regexp nil callback)
16787 d)))
16789 (defun org-check-after-date (d)
16790 "Check if there are deadlines or scheduled entries after date D."
16791 (interactive (list (org-read-date)))
16792 (let* ((case-fold-search nil)
16793 (regexp (org-re-timestamp org-ts-type))
16794 (ts-type org-ts-type)
16795 (callback
16796 (lambda ()
16797 (let ((match (match-string 1)))
16798 (and (if (memq ts-type '(active inactive all))
16799 (eq (org-element-type (save-excursion
16800 (backward-char)
16801 (org-element-context)))
16802 'timestamp)
16803 (org-at-planning-p))
16804 (not (time-less-p
16805 (org-time-string-to-time match)
16806 (org-time-string-to-time d))))))))
16807 (message "%d entries after %s"
16808 (org-occur regexp nil callback)
16809 d)))
16811 (defun org-check-dates-range (start-date end-date)
16812 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16813 (interactive (list (org-read-date nil nil nil "Range starts")
16814 (org-read-date nil nil nil "Range end")))
16815 (let ((case-fold-search nil)
16816 (regexp (org-re-timestamp org-ts-type))
16817 (callback
16818 (let ((type org-ts-type))
16819 (lambda ()
16820 (let ((match (match-string 1)))
16821 (and
16822 (if (memq type '(active inactive all))
16823 (eq (org-element-type (save-excursion
16824 (backward-char)
16825 (org-element-context)))
16826 'timestamp)
16827 (org-at-planning-p))
16828 (not (time-less-p
16829 (org-time-string-to-time match)
16830 (org-time-string-to-time start-date)))
16831 (time-less-p
16832 (org-time-string-to-time match)
16833 (org-time-string-to-time end-date))))))))
16834 (message "%d entries between %s and %s"
16835 (org-occur regexp nil callback) start-date end-date)))
16837 (defun org-evaluate-time-range (&optional to-buffer)
16838 "Evaluate a time range by computing the difference between start and end.
16839 Normally the result is just printed in the echo area, but with prefix arg
16840 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16841 If the time range is actually in a table, the result is inserted into the
16842 next column.
16843 For time difference computation, a year is assumed to be exactly 365
16844 days in order to avoid rounding problems."
16845 (interactive "P")
16847 (org-clock-update-time-maybe)
16848 (save-excursion
16849 (unless (org-at-date-range-p t)
16850 (goto-char (point-at-bol))
16851 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16852 (unless (org-at-date-range-p t)
16853 (user-error "Not at a time-stamp range, and none found in current line")))
16854 (let* ((ts1 (match-string 1))
16855 (ts2 (match-string 2))
16856 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16857 (match-end (match-end 0))
16858 (time1 (org-time-string-to-time ts1))
16859 (time2 (org-time-string-to-time ts2))
16860 (t1 (float-time time1))
16861 (t2 (float-time time2))
16862 (diff (abs (- t2 t1)))
16863 (negative (< (- t2 t1) 0))
16864 ;; (ys (floor (* 365 24 60 60)))
16865 (ds (* 24 60 60))
16866 (hs (* 60 60))
16867 (fy "%dy %dd %02d:%02d")
16868 (fy1 "%dy %dd")
16869 (fd "%dd %02d:%02d")
16870 (fd1 "%dd")
16871 (fh "%02d:%02d")
16872 y d h m align)
16873 (if havetime
16874 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16876 d (floor (/ diff ds)) diff (mod diff ds)
16877 h (floor (/ diff hs)) diff (mod diff hs)
16878 m (floor (/ diff 60)))
16879 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16881 d (floor (+ (/ diff ds) 0.5))
16882 h 0 m 0))
16883 (if (not to-buffer)
16884 (message "%s" (org-make-tdiff-string y d h m))
16885 (if (org-at-table-p)
16886 (progn
16887 (goto-char match-end)
16888 (setq align t)
16889 (and (looking-at " *|") (goto-char (match-end 0))))
16890 (goto-char match-end))
16891 (when (looking-at
16892 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16893 (replace-match ""))
16894 (when negative (insert " -"))
16895 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16896 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16897 (insert " " (format fh h m))))
16898 (when align (org-table-align))
16899 (message "Time difference inserted")))))
16901 (defun org-make-tdiff-string (y d h m)
16902 (let ((fmt "")
16903 (l nil))
16904 (when (> y 0)
16905 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16906 (push y l))
16907 (when (> d 0)
16908 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16909 (push d l))
16910 (when (> h 0)
16911 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16912 (push h l))
16913 (when (> m 0)
16914 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16915 (push m l))
16916 (apply 'format fmt (nreverse l))))
16918 (defun org-time-string-to-time (s)
16919 "Convert timestamp string S into internal time."
16920 (apply #'encode-time (org-parse-time-string s)))
16922 (defun org-time-string-to-seconds (s)
16923 "Convert a timestamp string S into a number of seconds."
16924 (float-time (org-time-string-to-time s)))
16926 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16928 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16929 "Convert time stamp S to an absolute day number.
16931 If DAYNR in non-nil, and there is a specifier for a cyclic time
16932 stamp, get the closest date to DAYNR. If PREFER is
16933 `past' (respectively `future') return a date past (respectively
16934 after) or equal to DAYNR.
16936 POS is the location of time stamp S, as a buffer position in
16937 BUFFER.
16939 Diary sexp timestamps are matched against DAYNR, when non-nil.
16940 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16941 signaled."
16942 (cond
16943 ((string-match "\\`%%\\((.*)\\)" s)
16944 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16945 ;; only able to match individual dates. If it fails, raise an
16946 ;; error.
16947 (if (and daynr
16948 (org-diary-sexp-entry
16949 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16950 daynr
16951 (signal 'org-diary-sexp-no-match (list s))))
16952 (daynr (org-closest-date s daynr prefer))
16953 (t (time-to-days
16954 (condition-case errdata
16955 (apply #'encode-time (org-parse-time-string s))
16956 (error (error "Bad timestamp `%s'%s\nError was: %s"
16958 (if (not (and buffer pos)) ""
16959 (format-message " at %d in buffer `%s'" pos buffer))
16960 (cdr errdata))))))))
16962 (defun org-days-to-iso-week (days)
16963 "Return the iso week number."
16964 (require 'cal-iso)
16965 (car (calendar-iso-from-absolute days)))
16967 (defun org-small-year-to-year (year)
16968 "Convert 2-digit years into 4-digit years.
16969 YEAR is expanded into one of the 30 next years, if possible, or
16970 into a past one. Any year larger than 99 is returned unchanged."
16971 (if (>= year 100) year
16972 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
16973 (century (/ current 100))
16974 (offset (- year (% current 100))))
16975 (cond ((> offset 30) (+ (* (1- century) 100) year))
16976 ((> offset -70) (+ (* century 100) year))
16977 (t (+ (* (1+ century) 100) year))))))
16979 (defun org-time-from-absolute (d)
16980 "Return the time corresponding to date D.
16981 D may be an absolute day number, or a calendar-type list (month day year)."
16982 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16983 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16985 (defvar org-agenda-current-date)
16986 (defun org-calendar-holiday ()
16987 "List of holidays, for Diary display in Org mode."
16988 (require 'holidays)
16989 (let ((hl (calendar-check-holidays org-agenda-current-date)))
16990 (and hl (mapconcat #'identity hl "; "))))
16992 (defun org-diary-sexp-entry (sexp entry d)
16993 "Process a SEXP diary ENTRY for date D."
16994 (require 'diary-lib)
16995 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
16996 ;; dynamically.
16997 (let* ((sexp `(let ((entry ,entry)
16998 (date ',d))
16999 ,(car (read-from-string sexp))))
17000 (result (if calendar-debug-sexp (eval sexp)
17001 (condition-case nil
17002 (eval sexp)
17003 (error
17004 (beep)
17005 (message "Bad sexp at line %d in %s: %s"
17006 (org-current-line)
17007 (buffer-file-name) sexp)
17008 (sleep-for 2))))))
17009 (cond ((stringp result) (split-string result "; "))
17010 ((and (consp result)
17011 (not (consp (cdr result)))
17012 (stringp (cdr result))) (cdr result))
17013 ((and (consp result)
17014 (stringp (car result))) result)
17015 (result entry))))
17017 (defun org-diary-to-ical-string (frombuf)
17018 "Get iCalendar entries from diary entries in buffer FROMBUF.
17019 This uses the icalendar.el library."
17020 (let* ((tmpdir temporary-file-directory)
17021 (tmpfile (make-temp-name
17022 (expand-file-name "orgics" tmpdir)))
17023 buf rtn b e)
17024 (with-current-buffer frombuf
17025 (icalendar-export-region (point-min) (point-max) tmpfile)
17026 (setq buf (find-buffer-visiting tmpfile))
17027 (set-buffer buf)
17028 (goto-char (point-min))
17029 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17030 (setq b (match-beginning 0)))
17031 (goto-char (point-max))
17032 (when (re-search-backward "^END:VEVENT" nil t)
17033 (setq e (match-end 0)))
17034 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17035 (kill-buffer buf)
17036 (delete-file tmpfile)
17037 rtn))
17039 (defun org-closest-date (start current prefer)
17040 "Return closest date to CURRENT starting from START.
17042 CURRENT and START are both time stamps.
17044 When PREFER is `past', return a date that is either CURRENT or
17045 past. When PREFER is `future', return a date that is either
17046 CURRENT or future.
17048 Only time stamps with a repeater are modified. Any other time
17049 stamp stay unchanged. In any case, return value is an absolute
17050 day number."
17051 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17052 ;; No repeater. Do not shift time stamp.
17053 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17054 (let ((value (string-to-number (match-string 1 start)))
17055 (type (match-string 2 start)))
17056 (if (= 0 value)
17057 ;; Repeater with a 0-value is considered as void.
17058 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17059 (let* ((base (org-date-to-gregorian start))
17060 (target (org-date-to-gregorian current))
17061 (sday (calendar-absolute-from-gregorian base))
17062 (cday (calendar-absolute-from-gregorian target))
17063 n1 n2)
17064 ;; If START is already past CURRENT, just return START.
17065 (if (<= cday sday) sday
17066 ;; Compute closest date before (N1) and closest date past
17067 ;; (N2) CURRENT.
17068 (pcase type
17069 ("h"
17070 (let ((missing-hours
17071 (mod (+ (- (* 24 (- cday sday))
17072 (nth 2 (org-parse-time-string start)))
17073 org-extend-today-until)
17074 value)))
17075 (setf n1 (if (= missing-hours 0) cday
17076 (- cday (1+ (/ missing-hours 24)))))
17077 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17078 ((or "d" "w")
17079 (let ((value (if (equal type "w") (* 7 value) value)))
17080 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17081 (setf n2 (+ n1 value))))
17082 ("m"
17083 (let* ((add-months
17084 (lambda (d n)
17085 ;; Add N months to gregorian date D, i.e.,
17086 ;; a list (MONTH DAY YEAR). Return a valid
17087 ;; gregorian date.
17088 (let ((m (+ (nth 0 d) n)))
17089 (list (mod m 12)
17090 (nth 1 d)
17091 (+ (/ m 12) (nth 2 d))))))
17092 (months ; Complete months to TARGET.
17093 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17094 (- (nth 0 target) (nth 0 base))
17095 ;; If START's day is greater than
17096 ;; TARGET's, remove incomplete month.
17097 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17098 value)
17099 value))
17100 (before (funcall add-months base months)))
17101 (setf n1 (calendar-absolute-from-gregorian before))
17102 (setf n2
17103 (calendar-absolute-from-gregorian
17104 (funcall add-months before value)))))
17106 (let* ((d (nth 1 base))
17107 (m (nth 0 base))
17108 (y (nth 2 base))
17109 (years ; Complete years to TARGET.
17110 (* (/ (- (nth 2 target)
17112 ;; If START's month and day are
17113 ;; greater than TARGET's, remove
17114 ;; incomplete year.
17115 (if (or (> (nth 0 target) m)
17116 (and (= (nth 0 target) m)
17117 (> (nth 1 target) d)))
17120 value)
17121 value))
17122 (before (list m d (+ y years))))
17123 (setf n1 (calendar-absolute-from-gregorian before))
17124 (setf n2 (calendar-absolute-from-gregorian
17125 (list m d (+ (nth 2 before) value)))))))
17126 ;; Handle PREFER parameter, if any.
17127 (cond
17128 ((eq prefer 'past) (if (= cday n2) n2 n1))
17129 ((eq prefer 'future) (if (= cday n1) n1 n2))
17130 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17132 (defun org-date-to-gregorian (d)
17133 "Turn any specification of date D into a Gregorian date for the calendar."
17134 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17135 ((and (listp d) (= (length d) 3)) d)
17136 ((stringp d)
17137 (let ((d (org-parse-time-string d)))
17138 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17139 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17141 (defun org-parse-time-string (s &optional nodefault)
17142 "Parse the standard Org time string.
17144 This should be a lot faster than the normal `parse-time-string'.
17146 If time is not given, defaults to 0:00. However, with optional
17147 NODEFAULT, hour and minute fields will be nil if not given."
17148 (cond ((string-match org-ts-regexp0 s)
17149 (list 0
17150 (when (or (match-beginning 8) (not nodefault))
17151 (string-to-number (or (match-string 8 s) "0")))
17152 (when (or (match-beginning 7) (not nodefault))
17153 (string-to-number (or (match-string 7 s) "0")))
17154 (string-to-number (match-string 4 s))
17155 (string-to-number (match-string 3 s))
17156 (string-to-number (match-string 2 s))
17157 nil nil nil))
17158 ((string-match "^<[^>]+>$" s)
17159 ;; FIXME: `decode-time' needs to be called with ZONE as its
17160 ;; second argument. However, this requires at least Emacs
17161 ;; 25.1. We can do it when we switch to this version as our
17162 ;; minimal requirement.
17163 (decode-time (seconds-to-time (org-matcher-time s))))
17164 (t (error "Not a standard Org time string: %s" s))))
17166 (defun org-timestamp-up (&optional arg)
17167 "Increase the date item at the cursor by one.
17168 If the cursor is on the year, change the year. If it is on the month,
17169 the day or the time, change that.
17170 With prefix ARG, change by that many units."
17171 (interactive "p")
17172 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17174 (defun org-timestamp-down (&optional arg)
17175 "Decrease the date item at the cursor by one.
17176 If the cursor is on the year, change the year. If it is on the month,
17177 the day or the time, change that.
17178 With prefix ARG, change by that many units."
17179 (interactive "p")
17180 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17182 (defun org-timestamp-up-day (&optional arg)
17183 "Increase the date in the time stamp by one day.
17184 With prefix ARG, change that many days."
17185 (interactive "p")
17186 (if (and (not (org-at-timestamp-p 'lax))
17187 (org-at-heading-p))
17188 (org-todo 'up)
17189 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17191 (defun org-timestamp-down-day (&optional arg)
17192 "Decrease the date in the time stamp by one day.
17193 With prefix ARG, change that many days."
17194 (interactive "p")
17195 (if (and (not (org-at-timestamp-p 'lax))
17196 (org-at-heading-p))
17197 (org-todo 'down)
17198 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17200 (defun org-at-timestamp-p (&optional extended)
17201 "Non-nil if point is inside a timestamp.
17203 By default, the function only consider syntactically valid active
17204 timestamps. However, the caller may have a broader definition
17205 for timestamps. As a consequence, optional argument EXTENDED can
17206 be set to the following values
17208 `inactive'
17210 Include also syntactically valid inactive timestamps.
17212 `agenda'
17214 Include timestamps allowed in Agenda, i.e., those in
17215 properties drawers, planning lines and clock lines.
17217 `lax'
17219 Ignore context. The function matches any part of the
17220 document looking like a timestamp. This includes comments,
17221 example blocks...
17223 For backward-compatibility with Org 9.0, every other non-nil
17224 value is equivalent to `inactive'.
17226 When at a timestamp, return the position of the point as a symbol
17227 among `bracket', `after', `year', `month', `hour', `minute',
17228 `day' or a number of character from the last know part of the
17229 time stamp.
17231 When matching, the match groups are the following:
17232 group 1: year
17233 group 2: month
17234 group 3: day number
17235 group 4: day name
17236 group 5: hours, if any
17237 group 6: minutes, if any"
17238 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17239 (pos (point))
17240 (match?
17241 (let ((boundaries (org-in-regexp regexp)))
17242 (save-match-data
17243 (cond ((null boundaries) nil)
17244 ((eq extended 'lax) t)
17246 (or (and (eq extended 'agenda)
17247 (or (org-at-planning-p)
17248 (org-at-property-p)
17249 (and (bound-and-true-p
17250 org-agenda-include-inactive-timestamps)
17251 (org-at-clock-log-p))))
17252 (eq 'timestamp
17253 (save-excursion
17254 (when (= pos (cdr boundaries)) (forward-char -1))
17255 (org-element-type (org-element-context)))))))))))
17256 (cond
17257 ((not match?) nil)
17258 ((= pos (match-beginning 0)) 'bracket)
17259 ;; Distinguish location right before the closing bracket from
17260 ;; right after it.
17261 ((= pos (1- (match-end 0))) 'bracket)
17262 ((= pos (match-end 0)) 'after)
17263 ((org-pos-in-match-range pos 2) 'year)
17264 ((org-pos-in-match-range pos 3) 'month)
17265 ((org-pos-in-match-range pos 7) 'hour)
17266 ((org-pos-in-match-range pos 8) 'minute)
17267 ((or (org-pos-in-match-range pos 4)
17268 (org-pos-in-match-range pos 5)) 'day)
17269 ((and (> pos (or (match-end 8) (match-end 5)))
17270 (< pos (match-end 0)))
17271 (- pos (or (match-end 8) (match-end 5))))
17272 (t 'day))))
17274 (defun org-toggle-timestamp-type ()
17275 "Toggle the type (<active> or [inactive]) of a time stamp."
17276 (interactive)
17277 (when (org-at-timestamp-p 'lax)
17278 (let ((beg (match-beginning 0)) (end (match-end 0))
17279 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17280 (save-excursion
17281 (goto-char beg)
17282 (while (re-search-forward "[][<>]" end t)
17283 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17284 t t)))
17285 (message "Timestamp is now %sactive"
17286 (if (equal (char-after beg) ?<) "" "in")))))
17288 (defun org-at-clock-log-p ()
17289 "Non-nil if point is on a clock log line."
17290 (and (org-match-line org-clock-line-re)
17291 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17293 (defvar org-clock-history) ; defined in org-clock.el
17294 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17295 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17296 "Change the date in the time stamp at point.
17297 The date will be changed by N times WHAT. WHAT can be `day', `month',
17298 `year', `minute', `second'. If WHAT is not given, the cursor position
17299 in the timestamp determines what will be changed.
17300 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17301 (let ((origin (point))
17302 (timestamp? (org-at-timestamp-p 'lax))
17303 origin-cat
17304 with-hm inactive
17305 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17306 extra rem
17307 ts time time0 fixnext clrgx)
17308 (unless timestamp? (user-error "Not at a timestamp"))
17309 (if (and (not what) (eq timestamp? 'bracket))
17310 (org-toggle-timestamp-type)
17311 ;; Point isn't on brackets. Remember the part of the time-stamp
17312 ;; the point was in. Indeed, size of time-stamps may change,
17313 ;; but point must be kept in the same category nonetheless.
17314 (setq origin-cat timestamp?)
17315 (when (and (not what) (not (eq timestamp? 'day))
17316 org-display-custom-times
17317 (get-text-property (point) 'display)
17318 (not (get-text-property (1- (point)) 'display)))
17319 (setq timestamp? 'day))
17320 (setq timestamp? (or what timestamp?)
17321 inactive (= (char-after (match-beginning 0)) ?\[)
17322 ts (match-string 0))
17323 (replace-match "")
17324 (when (string-match
17325 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17327 (setq extra (match-string 1 ts))
17328 (when suppress-tmp-delay
17329 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17330 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17331 (setq with-hm t))
17332 (setq time0 (org-parse-time-string ts))
17333 (when (and updown
17334 (eq timestamp? 'minute)
17335 (not current-prefix-arg))
17336 ;; This looks like s-up and s-down. Change by one rounding step.
17337 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17338 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17339 (setcar (cdr time0) (+ (nth 1 time0)
17340 (if (> n 0) (- rem) (- dm rem))))))
17341 (setq time
17342 (apply #'encode-time
17343 (or (car time0) 0)
17344 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17345 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17346 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17347 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17348 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17349 (nthcdr 6 time0)))
17350 (when (and (memq timestamp? '(hour minute))
17351 extra
17352 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17353 (setq extra (org-modify-ts-extra
17354 extra
17355 (if (eq timestamp? 'hour) 2 5)
17356 n dm)))
17357 (when (integerp timestamp?)
17358 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17359 (when (eq what 'calendar)
17360 (let ((cal-date (org-get-date-from-calendar)))
17361 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17362 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17363 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17364 (setcar time0 (or (car time0) 0))
17365 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17366 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17367 (setq time (apply 'encode-time time0))))
17368 ;; Insert the new time-stamp, and ensure point stays in the same
17369 ;; category as before (i.e. not after the last position in that
17370 ;; category).
17371 (let ((pos (point)))
17372 ;; Stay before inserted string. `save-excursion' is of no use.
17373 (setq org-last-changed-timestamp
17374 (org-insert-time-stamp time with-hm inactive nil nil extra))
17375 (goto-char pos))
17376 (save-match-data
17377 (looking-at org-ts-regexp3)
17378 (goto-char
17379 (pcase origin-cat
17380 ;; `day' category ends before `hour' if any, or at the end
17381 ;; of the day name.
17382 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17383 (`hour (min (match-end 7) origin))
17384 (`minute (min (1- (match-end 8)) origin))
17385 ((pred integerp) (min (1- (match-end 0)) origin))
17386 ;; Point was right after the time-stamp. However, the
17387 ;; time-stamp length might have changed, so refer to
17388 ;; (match-end 0) instead.
17389 (`after (match-end 0))
17390 ;; `year' and `month' have both fixed size: point couldn't
17391 ;; have moved into another part.
17392 (_ origin))))
17393 ;; Update clock if on a CLOCK line.
17394 (org-clock-update-time-maybe)
17395 ;; Maybe adjust the closest clock in `org-clock-history'
17396 (when org-clock-adjust-closest
17397 (if (not (and (org-at-clock-log-p)
17398 (< 1 (length (delq nil (mapcar 'marker-position
17399 org-clock-history))))))
17400 (message "No clock to adjust")
17401 (cond ((save-excursion ; fix previous clock?
17402 (re-search-backward org-ts-regexp0 nil t)
17403 (looking-back (concat org-clock-string " \\[")
17404 (line-beginning-position)))
17405 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17406 ((save-excursion ; fix next clock?
17407 (re-search-backward org-ts-regexp0 nil t)
17408 (looking-at (concat org-ts-regexp0 "\\] =>")))
17409 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17410 (save-window-excursion
17411 ;; Find closest clock to point, adjust the previous/next one in history
17412 (let* ((p (save-excursion (org-back-to-heading t)))
17413 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17414 (clfixnth
17415 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17416 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17417 (if (not clfixpos)
17418 (message "No clock to adjust")
17419 (save-excursion
17420 (org-goto-marker-or-bmk clfixpos)
17421 (org-show-subtree)
17422 (when (re-search-forward clrgx nil t)
17423 (goto-char (match-beginning 1))
17424 (let (org-clock-adjust-closest)
17425 (org-timestamp-change n timestamp? updown))
17426 (message "Clock adjusted in %s for heading: %s"
17427 (file-name-nondirectory (buffer-file-name))
17428 (org-get-heading t t)))))))))
17429 ;; Try to recenter the calendar window, if any.
17430 (when (and org-calendar-follow-timestamp-change
17431 (get-buffer-window "*Calendar*" t)
17432 (memq timestamp? '(day month year)))
17433 (org-recenter-calendar (time-to-days time))))))
17435 (defun org-modify-ts-extra (s pos n dm)
17436 "Change the different parts of the lead-time and repeat fields in timestamp."
17437 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17438 ng h m new rem)
17439 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17440 (cond
17441 ((or (org-pos-in-match-range pos 2)
17442 (org-pos-in-match-range pos 3))
17443 (setq m (string-to-number (match-string 3 s))
17444 h (string-to-number (match-string 2 s)))
17445 (if (org-pos-in-match-range pos 2)
17446 (setq h (+ h n))
17447 (setq n (* dm (with-no-warnings (signum n))))
17448 (unless (= 0 (setq rem (% m dm)))
17449 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17450 (setq m (+ m n)))
17451 (when (< m 0) (setq m (+ m 60) h (1- h)))
17452 (when (> m 59) (setq m (- m 60) h (1+ h)))
17453 (setq h (mod h 24))
17454 (setq ng 1 new (format "-%02d:%02d" h m)))
17455 ((org-pos-in-match-range pos 6)
17456 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17457 ((org-pos-in-match-range pos 5)
17458 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17460 ((org-pos-in-match-range pos 9)
17461 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17462 ((org-pos-in-match-range pos 8)
17463 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17465 (when ng
17466 (setq s (concat
17467 (substring s 0 (match-beginning ng))
17469 (substring s (match-end ng))))))
17472 (defun org-recenter-calendar (d)
17473 "If the calendar is visible, recenter it to date D."
17474 (let ((cwin (get-buffer-window "*Calendar*" t)))
17475 (when cwin
17476 (let ((calendar-move-hook nil))
17477 (with-selected-window cwin
17478 (calendar-goto-date
17479 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17481 (defun org-goto-calendar (&optional arg)
17482 "Go to the Emacs calendar at the current date.
17483 If there is a time stamp in the current line, go to that date.
17484 A prefix ARG can be used to force the current date."
17485 (interactive "P")
17486 (let ((calendar-move-hook nil)
17487 (calendar-view-holidays-initially-flag nil)
17488 (calendar-view-diary-initially-flag nil)
17489 diff)
17490 (when (or (org-at-timestamp-p 'lax)
17491 (org-match-line (concat ".*" org-ts-regexp)))
17492 (let ((d1 (time-to-days (current-time)))
17493 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17494 (setq diff (- d2 d1))))
17495 (calendar)
17496 (calendar-goto-today)
17497 (when (and diff (not arg)) (calendar-forward-day diff))))
17499 (defun org-get-date-from-calendar ()
17500 "Return a list (month day year) of date at point in calendar."
17501 (with-current-buffer "*Calendar*"
17502 (save-match-data
17503 (calendar-cursor-to-date))))
17505 (defun org-date-from-calendar ()
17506 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17507 If there is already a time stamp at the cursor position, update it."
17508 (interactive)
17509 (if (org-at-timestamp-p 'lax)
17510 (org-timestamp-change 0 'calendar)
17511 (let ((cal-date (org-get-date-from-calendar)))
17512 (org-insert-time-stamp
17513 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17515 (defcustom org-effort-durations
17516 `(("min" . 1)
17517 ("h" . 60)
17518 ("d" . ,(* 60 8))
17519 ("w" . ,(* 60 8 5))
17520 ("m" . ,(* 60 8 5 4))
17521 ("y" . ,(* 60 8 5 40)))
17522 "Conversion factor to minutes for an effort modifier.
17524 Each entry has the form (MODIFIER . MINUTES).
17526 In an effort string, a number followed by MODIFIER is multiplied
17527 by the specified number of MINUTES to obtain an effort in
17528 minutes.
17530 For example, if the value of this variable is ((\"hours\" . 60)), then an
17531 effort string \"2hours\" is equivalent to 120 minutes."
17532 :group 'org-agenda
17533 :version "26.1"
17534 :package-version '(Org . "8.3")
17535 :type '(alist :key-type (string :tag "Modifier")
17536 :value-type (number :tag "Minutes")))
17538 (defcustom org-image-actual-width t
17539 "Should we use the actual width of images when inlining them?
17541 When set to t, always use the image width.
17543 When set to a number, use imagemagick (when available) to set
17544 the image's width to this value.
17546 When set to a number in a list, try to get the width from any
17547 #+ATTR.* keyword if it matches a width specification like
17549 #+ATTR_HTML: :width 300px
17551 and fall back on that number if none is found.
17553 When set to nil, try to get the width from an #+ATTR.* keyword
17554 and fall back on the original width if none is found.
17556 This requires Emacs >= 24.1, build with imagemagick support."
17557 :group 'org-appearance
17558 :version "24.4"
17559 :package-version '(Org . "8.0")
17560 :type '(choice
17561 (const :tag "Use the image width" t)
17562 (integer :tag "Use a number of pixels")
17563 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17564 (const :tag "Use #+ATTR* or don't resize" nil)))
17566 (defcustom org-agenda-inhibit-startup nil
17567 "Inhibit startup when preparing agenda buffers.
17568 When this variable is t, the initialization of the Org agenda
17569 buffers is inhibited: e.g. the visibility state is not set, the
17570 tables are not re-aligned, etc."
17571 :type 'boolean
17572 :version "24.3"
17573 :group 'org-agenda)
17575 (defcustom org-agenda-ignore-properties nil
17576 "Avoid updating text properties when building the agenda.
17577 Properties are used to prepare buffers for effort estimates,
17578 appointments, statistics and subtree-local categories.
17579 If you don't use these in the agenda, you can add them to this
17580 list and agenda building will be a bit faster.
17581 The value is a list, with zero or more of the symbols `effort', `appt',
17582 `stats' or `category'."
17583 :type '(set :greedy t
17584 (const effort)
17585 (const appt)
17586 (const stats)
17587 (const category))
17588 :version "26.1"
17589 :package-version '(Org . "8.3")
17590 :group 'org-agenda)
17592 ;;;; Files
17594 (defun org-save-all-org-buffers ()
17595 "Save all Org buffers without user confirmation."
17596 (interactive)
17597 (message "Saving all Org buffers...")
17598 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17599 (when (featurep 'org-id) (org-id-locations-save))
17600 (message "Saving all Org buffers... done"))
17602 (defun org-revert-all-org-buffers ()
17603 "Revert all Org buffers.
17604 Prompt for confirmation when there are unsaved changes.
17605 Be sure you know what you are doing before letting this function
17606 overwrite your changes.
17608 This function is useful in a setup where one tracks Org files
17609 with a version control system, to revert on one machine after pulling
17610 changes from another. I believe the procedure must be like this:
17612 1. M-x org-save-all-org-buffers
17613 2. Pull changes from the other machine, resolve conflicts
17614 3. M-x org-revert-all-org-buffers"
17615 (interactive)
17616 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17617 (user-error "Abort"))
17618 (save-excursion
17619 (save-window-excursion
17620 (dolist (b (buffer-list))
17621 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17622 (with-current-buffer b buffer-file-name))
17623 (pop-to-buffer-same-window b)
17624 (revert-buffer t 'no-confirm)))
17625 (when (and (featurep 'org-id) org-id-track-globally)
17626 (org-id-locations-load)))))
17628 ;;;; Agenda files
17630 ;;;###autoload
17631 (defun org-switchb (&optional arg)
17632 "Switch between Org buffers.
17634 With `\\[universal-argument]' prefix, restrict available buffers to files.
17636 With `\\[universal-argument] \\[universal-argument]' \
17637 prefix, restrict available buffers to agenda files."
17638 (interactive "P")
17639 (let ((blist (org-buffer-list
17640 (cond ((equal arg '(4)) 'files)
17641 ((equal arg '(16)) 'agenda)))))
17642 (pop-to-buffer-same-window
17643 (completing-read "Org buffer: "
17644 (mapcar #'list (mapcar #'buffer-name blist))
17645 nil t))))
17647 (defun org-buffer-list (&optional predicate exclude-tmp)
17648 "Return a list of Org buffers.
17649 PREDICATE can be `export', `files' or `agenda'.
17651 export restrict the list to Export buffers.
17652 files restrict the list to buffers visiting Org files.
17653 agenda restrict the list to buffers visiting agenda files.
17655 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17656 (let* ((bfn nil)
17657 (agenda-files (and (eq predicate 'agenda)
17658 (mapcar 'file-truename (org-agenda-files t))))
17659 (filter
17660 (cond
17661 ((eq predicate 'files)
17662 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17663 ((eq predicate 'export)
17664 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17665 ((eq predicate 'agenda)
17666 (lambda (b)
17667 (with-current-buffer b
17668 (and (derived-mode-p 'org-mode)
17669 (setq bfn (buffer-file-name b))
17670 (member (file-truename bfn) agenda-files)))))
17671 (t (lambda (b) (with-current-buffer b
17672 (or (derived-mode-p 'org-mode)
17673 (string-match "\\*Org .*Export"
17674 (buffer-name b)))))))))
17675 (delq nil
17676 (mapcar
17677 (lambda(b)
17678 (if (and (funcall filter b)
17679 (or (not exclude-tmp)
17680 (not (string-match "tmp" (buffer-name b)))))
17682 nil))
17683 (buffer-list)))))
17685 (defun org-agenda-files (&optional unrestricted archives)
17686 "Get the list of agenda files.
17687 Optional UNRESTRICTED means return the full list even if a restriction
17688 is currently in place.
17689 When ARCHIVES is t, include all archive files that are really being
17690 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17691 `org-agenda-archives-mode' is t."
17692 (let ((files
17693 (cond
17694 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17695 ((stringp org-agenda-files) (org-read-agenda-file-list))
17696 ((listp org-agenda-files) org-agenda-files)
17697 (t (error "Invalid value of `org-agenda-files'")))))
17698 (setq files (apply 'append
17699 (mapcar (lambda (f)
17700 (if (file-directory-p f)
17701 (directory-files
17702 f t org-agenda-file-regexp)
17703 (list f)))
17704 files)))
17705 (when org-agenda-skip-unavailable-files
17706 (setq files (delq nil
17707 (mapcar (function
17708 (lambda (file)
17709 (and (file-readable-p file) file)))
17710 files))))
17711 (when (or (eq archives t)
17712 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17713 (setq files (org-add-archive-files files)))
17714 files))
17716 (defun org-agenda-file-p (&optional file)
17717 "Return non-nil, if FILE is an agenda file.
17718 If FILE is omitted, use the file associated with the current
17719 buffer."
17720 (let ((fname (or file (buffer-file-name))))
17721 (and fname
17722 (member (file-truename fname)
17723 (mapcar #'file-truename (org-agenda-files t))))))
17725 (defun org-edit-agenda-file-list ()
17726 "Edit the list of agenda files.
17727 Depending on setup, this either uses customize to edit the variable
17728 `org-agenda-files', or it visits the file that is holding the list. In the
17729 latter case, the buffer is set up in a way that saving it automatically kills
17730 the buffer and restores the previous window configuration."
17731 (interactive)
17732 (if (stringp org-agenda-files)
17733 (let ((cw (current-window-configuration)))
17734 (find-file org-agenda-files)
17735 (setq-local org-window-configuration cw)
17736 (add-hook 'after-save-hook
17737 (lambda ()
17738 (set-window-configuration
17739 (prog1 org-window-configuration
17740 (kill-buffer (current-buffer))))
17741 (org-install-agenda-files-menu)
17742 (message "New agenda file list installed"))
17743 nil 'local)
17744 (message "%s" (substitute-command-keys
17745 "Edit list and finish with \\[save-buffer]")))
17746 (customize-variable 'org-agenda-files)))
17748 (defun org-store-new-agenda-file-list (list)
17749 "Set new value for the agenda file list and save it correctly."
17750 (if (stringp org-agenda-files)
17751 (let ((fe (org-read-agenda-file-list t)) b u)
17752 (while (setq b (find-buffer-visiting org-agenda-files))
17753 (kill-buffer b))
17754 (with-temp-file org-agenda-files
17755 (insert
17756 (mapconcat
17757 (lambda (f) ;; Keep un-expanded entries.
17758 (if (setq u (assoc f fe))
17759 (cdr u)
17761 list "\n")
17762 "\n")))
17763 (let ((org-mode-hook nil) (org-inhibit-startup t)
17764 (org-insert-mode-line-in-empty-file nil))
17765 (setq org-agenda-files list)
17766 (customize-save-variable 'org-agenda-files org-agenda-files))))
17768 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17769 "Read the list of agenda files from a file.
17770 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17771 filenames, used by `org-store-new-agenda-file-list' to write back
17772 un-expanded file names."
17773 (when (file-directory-p org-agenda-files)
17774 (error "`org-agenda-files' cannot be a single directory"))
17775 (when (stringp org-agenda-files)
17776 (with-temp-buffer
17777 (insert-file-contents org-agenda-files)
17778 (mapcar
17779 (lambda (f)
17780 (let ((e (expand-file-name (substitute-in-file-name f)
17781 org-directory)))
17782 (if pair-with-expansion
17783 (cons e f)
17784 e)))
17785 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17787 ;;;###autoload
17788 (defun org-cycle-agenda-files ()
17789 "Cycle through the files in `org-agenda-files'.
17790 If the current buffer visits an agenda file, find the next one in the list.
17791 If the current buffer does not, find the first agenda file."
17792 (interactive)
17793 (let* ((fs (or (org-agenda-files t)
17794 (user-error "No agenda files")))
17795 (files (copy-sequence fs))
17796 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17797 file)
17798 (when tcf
17799 (while (and (setq file (pop files))
17800 (not (equal (file-truename file) tcf)))))
17801 (find-file (car (or files fs)))
17802 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17804 (defun org-agenda-file-to-front (&optional to-end)
17805 "Move/add the current file to the top of the agenda file list.
17806 If the file is not present in the list, it is added to the front. If it is
17807 present, it is moved there. With optional argument TO-END, add/move to the
17808 end of the list."
17809 (interactive "P")
17810 (let ((org-agenda-skip-unavailable-files nil)
17811 (file-alist (mapcar (lambda (x)
17812 (cons (file-truename x) x))
17813 (org-agenda-files t)))
17814 (ctf (file-truename
17815 (or buffer-file-name
17816 (user-error "Please save the current buffer to a file"))))
17817 x had)
17818 (setq x (assoc ctf file-alist) had x)
17820 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17821 (if to-end
17822 (setq file-alist (append (delq x file-alist) (list x)))
17823 (setq file-alist (cons x (delq x file-alist))))
17824 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17825 (org-install-agenda-files-menu)
17826 (message "File %s to %s of agenda file list"
17827 (if had "moved" "added") (if to-end "end" "front"))))
17829 (defun org-remove-file (&optional file)
17830 "Remove current file from the list of files in variable `org-agenda-files'.
17831 These are the files which are being checked for agenda entries.
17832 Optional argument FILE means use this file instead of the current."
17833 (interactive)
17834 (let* ((org-agenda-skip-unavailable-files nil)
17835 (file (or file buffer-file-name
17836 (user-error "Current buffer does not visit a file")))
17837 (true-file (file-truename file))
17838 (afile (abbreviate-file-name file))
17839 (files (delq nil (mapcar
17840 (lambda (x)
17841 (unless (equal true-file
17842 (file-truename x))
17844 (org-agenda-files t)))))
17845 (if (not (= (length files) (length (org-agenda-files t))))
17846 (progn
17847 (org-store-new-agenda-file-list files)
17848 (org-install-agenda-files-menu)
17849 (message "Removed from Org Agenda list: %s" afile))
17850 (message "File was not in list: %s (not removed)" afile))))
17852 (defun org-file-menu-entry (file)
17853 (vector file (list 'find-file file) t))
17855 (defun org-check-agenda-file (file)
17856 "Make sure FILE exists. If not, ask user what to do."
17857 (unless (file-exists-p file)
17858 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17859 (abbreviate-file-name file))
17860 (let ((r (downcase (read-char-exclusive))))
17861 (cond
17862 ((equal r ?r)
17863 (org-remove-file file)
17864 (throw 'nextfile t))
17865 (t (user-error "Abort"))))))
17867 (defun org-get-agenda-file-buffer (file)
17868 "Get an agenda buffer visiting FILE.
17869 If the buffer needs to be created, add it to the list of buffers
17870 which might be released later."
17871 (let ((buf (org-find-base-buffer-visiting file)))
17872 (if buf
17873 buf ; just return it
17874 ;; Make a new buffer and remember it
17875 (setq buf (find-file-noselect file))
17876 (when buf (push buf org-agenda-new-buffers))
17877 buf)))
17879 (defun org-release-buffers (blist)
17880 "Release all buffers in list, asking the user for confirmation when needed.
17881 When a buffer is unmodified, it is just killed. When modified, it is saved
17882 \(if the user agrees) and then killed."
17883 (let (file)
17884 (dolist (buf blist)
17885 (setq file (buffer-file-name buf))
17886 (when (and (buffer-modified-p buf)
17887 file
17888 (y-or-n-p (format "Save file %s? " file)))
17889 (with-current-buffer buf (save-buffer)))
17890 (kill-buffer buf))))
17892 (defun org-agenda-prepare-buffers (files)
17893 "Create buffers for all agenda files, protect archived trees and comments."
17894 (interactive)
17895 (let ((pa '(:org-archived t))
17896 (pc '(:org-comment t))
17897 (pall '(:org-archived t :org-comment t))
17898 (inhibit-read-only t)
17899 (org-inhibit-startup org-agenda-inhibit-startup)
17900 (rea (concat ":" org-archive-tag ":"))
17901 re pos)
17902 (setq org-tag-alist-for-agenda nil
17903 org-tag-groups-alist-for-agenda nil)
17904 (save-excursion
17905 (save-restriction
17906 (dolist (file files)
17907 (catch 'nextfile
17908 (if (bufferp file)
17909 (set-buffer file)
17910 (org-check-agenda-file file)
17911 (set-buffer (org-get-agenda-file-buffer file)))
17912 (widen)
17913 (org-set-regexps-and-options 'tags-only)
17914 (setq pos (point))
17915 (or (memq 'category org-agenda-ignore-properties)
17916 (org-refresh-category-properties))
17917 (or (memq 'stats org-agenda-ignore-properties)
17918 (org-refresh-stats-properties))
17919 (or (memq 'effort org-agenda-ignore-properties)
17920 (org-refresh-effort-properties))
17921 (or (memq 'appt org-agenda-ignore-properties)
17922 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17923 (setq org-todo-keywords-for-agenda
17924 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17925 (setq org-done-keywords-for-agenda
17926 (append org-done-keywords-for-agenda org-done-keywords))
17927 (setq org-todo-keyword-alist-for-agenda
17928 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17929 (setq org-tag-alist-for-agenda
17930 (org-uniquify
17931 (append org-tag-alist-for-agenda
17932 org-current-tag-alist)))
17933 ;; Merge current file's tag groups into global
17934 ;; `org-tag-groups-alist-for-agenda'.
17935 (when org-group-tags
17936 (dolist (alist org-tag-groups-alist)
17937 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17938 (if old
17939 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17940 (push alist org-tag-groups-alist-for-agenda)))))
17941 (org-with-silent-modifications
17942 (save-excursion
17943 (remove-text-properties (point-min) (point-max) pall)
17944 (when org-agenda-skip-archived-trees
17945 (goto-char (point-min))
17946 (while (re-search-forward rea nil t)
17947 (when (org-at-heading-p t)
17948 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17949 (goto-char (point-min))
17950 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17951 (while (re-search-forward re nil t)
17952 (when (save-match-data (org-in-commented-heading-p t))
17953 (add-text-properties
17954 (match-beginning 0) (org-end-of-subtree t) pc)))))
17955 (goto-char pos)))))
17956 (setq org-todo-keywords-for-agenda
17957 (org-uniquify org-todo-keywords-for-agenda))
17958 (setq org-todo-keyword-alist-for-agenda
17959 (org-uniquify org-todo-keyword-alist-for-agenda))))
17962 ;;;; CDLaTeX minor mode
17964 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17965 "Keymap for the minor `org-cdlatex-mode'.")
17967 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17968 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17969 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17970 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17971 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
17973 (defvar org-cdlatex-texmathp-advice-is-done nil
17974 "Flag remembering if we have applied the advice to texmathp already.")
17976 (define-minor-mode org-cdlatex-mode
17977 "Toggle the minor `org-cdlatex-mode'.
17978 This mode supports entering LaTeX environment and math in LaTeX fragments
17979 in Org mode.
17980 \\{org-cdlatex-mode-map}"
17981 nil " OCDL" nil
17982 (when org-cdlatex-mode
17983 (require 'cdlatex)
17984 (run-hooks 'cdlatex-mode-hook)
17985 (cdlatex-compute-tables))
17986 (unless org-cdlatex-texmathp-advice-is-done
17987 (setq org-cdlatex-texmathp-advice-is-done t)
17988 (defadvice texmathp (around org-math-always-on activate)
17989 "Always return t in Org buffers.
17990 This is because we want to insert math symbols without dollars even outside
17991 the LaTeX math segments. If Org mode thinks that point is actually inside
17992 an embedded LaTeX fragment, let `texmathp' do its job.
17993 `\\[org-cdlatex-mode-map]'"
17994 (interactive)
17995 (let (p)
17996 (cond
17997 ((not (derived-mode-p 'org-mode)) ad-do-it)
17998 ((eq this-command 'cdlatex-math-symbol)
17999 (setq ad-return-value t
18000 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18002 (let ((p (org-inside-LaTeX-fragment-p)))
18003 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18004 (setq ad-return-value t
18005 texmathp-why '("Org mode embedded math" . 0))
18006 (when p ad-do-it)))))))))
18008 (defun turn-on-org-cdlatex ()
18009 "Unconditionally turn on `org-cdlatex-mode'."
18010 (org-cdlatex-mode 1))
18012 (defun org-try-cdlatex-tab ()
18013 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18014 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18015 - inside a LaTeX fragment, or
18016 - after the first word in a line, where an abbreviation expansion could
18017 insert a LaTeX environment."
18018 (when org-cdlatex-mode
18019 (cond
18020 ;; Before any word on the line: No expansion possible.
18021 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18022 ;; Just after first word on the line: Expand it. Make sure it
18023 ;; cannot happen on headlines, though.
18024 ((save-excursion
18025 (skip-chars-backward "a-zA-Z0-9*")
18026 (skip-chars-backward " \t")
18027 (and (bolp) (not (org-at-heading-p))))
18028 (cdlatex-tab) t)
18029 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18031 (defun org-cdlatex-underscore-caret (&optional _arg)
18032 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18033 Revert to the normal definition outside of these fragments."
18034 (interactive "P")
18035 (if (org-inside-LaTeX-fragment-p)
18036 (call-interactively 'cdlatex-sub-superscript)
18037 (let (org-cdlatex-mode)
18038 (call-interactively (key-binding (vector last-input-event))))))
18040 (defun org-cdlatex-math-modify (&optional _arg)
18041 "Execute `cdlatex-math-modify' in LaTeX fragments.
18042 Revert to the normal definition outside of these fragments."
18043 (interactive "P")
18044 (if (org-inside-LaTeX-fragment-p)
18045 (call-interactively 'cdlatex-math-modify)
18046 (let (org-cdlatex-mode)
18047 (call-interactively (key-binding (vector last-input-event))))))
18049 (defun org-cdlatex-environment-indent (&optional environment item)
18050 "Execute `cdlatex-environment' and indent the inserted environment.
18052 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18054 The inserted environment is indented to current indentation
18055 unless point is at the beginning of the line, in which the
18056 environment remains unintended."
18057 (interactive)
18058 ;; cdlatex-environment always return nil. Therefore, capture output
18059 ;; first and determine if an environment was selected.
18060 (let* ((beg (point-marker))
18061 (end (copy-marker (point) t))
18062 (inserted (progn
18063 (ignore-errors (cdlatex-environment environment item))
18064 (< beg end)))
18065 ;; Figure out how many lines to move forward after the
18066 ;; environment has been inserted.
18067 (lines (when inserted
18068 (save-excursion
18069 (- (cl-loop while (< beg (point))
18070 with x = 0
18071 do (forward-line -1)
18072 (cl-incf x)
18073 finally return x)
18074 (if (progn (goto-char beg)
18075 (and (progn (skip-chars-forward " \t") (eolp))
18076 (progn (skip-chars-backward " \t") (bolp))))
18077 1 0)))))
18078 (env (org-trim (delete-and-extract-region beg end))))
18079 (when inserted
18080 ;; Get indentation of next line unless at column 0.
18081 (let ((ind (if (bolp) 0
18082 (save-excursion
18083 (org-return-indent)
18084 (prog1 (org-get-indentation)
18085 (when (progn (skip-chars-forward " \t") (eolp))
18086 (delete-region beg (point)))))))
18087 (bol (progn (skip-chars-backward " \t") (bolp))))
18088 ;; Insert a newline before environment unless at column zero
18089 ;; to "escape" the current line. Insert a newline if
18090 ;; something is one the same line as \end{ENVIRONMENT}.
18091 (insert
18092 (concat (unless bol "\n") env
18093 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18094 (unless (zerop ind)
18095 (save-excursion
18096 (goto-char beg)
18097 (while (< (point) end)
18098 (unless (eolp) (indent-line-to ind))
18099 (forward-line))))
18100 (goto-char beg)
18101 (forward-line lines)
18102 (indent-line-to ind)))
18103 (set-marker beg nil)
18104 (set-marker end nil)))
18107 ;;;; LaTeX fragments
18109 (defun org-inside-LaTeX-fragment-p ()
18110 "Test if point is inside a LaTeX fragment.
18111 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18112 sequence appearing also before point.
18113 Even though the matchers for math are configurable, this function assumes
18114 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18115 delimiters are skipped when they have been removed by customization.
18116 The return value is nil, or a cons cell with the delimiter and the
18117 position of this delimiter.
18119 This function does a reasonably good job, but can locally be fooled by
18120 for example currency specifications. For example it will assume being in
18121 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18122 fragments that are properly closed, but during editing, we have to live
18123 with the uncertainty caused by missing closing delimiters. This function
18124 looks only before point, not after."
18125 (catch 'exit
18126 (let ((pos (point))
18127 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18128 (lim (save-excursion (org-backward-paragraph) (point)))
18129 dd-on str (start 0) m re)
18130 (goto-char pos)
18131 (when dodollar
18132 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18133 re (nth 1 (assoc "$" org-latex-regexps)))
18134 (while (string-match re str start)
18135 (cond
18136 ((= (match-end 0) (length str))
18137 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18138 ((= (match-end 0) (- (length str) 5))
18139 (throw 'exit nil))
18140 (t (setq start (match-end 0))))))
18141 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18142 (goto-char pos)
18143 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18144 (and (match-beginning 2) (throw 'exit nil))
18145 ;; count $$
18146 (while (re-search-backward "\\$\\$" lim t)
18147 (setq dd-on (not dd-on)))
18148 (goto-char pos)
18149 (when dd-on (cons "$$" m))))))
18151 (defun org-inside-latex-macro-p ()
18152 "Is point inside a LaTeX macro or its arguments?"
18153 (save-match-data
18154 (org-in-regexp
18155 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18157 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18158 "Build an overlay between BEG and END using IMAGE file.
18159 Argument IMAGETYPE is the extension of the displayed image,
18160 as a string. It defaults to \"png\"."
18161 (let ((ov (make-overlay beg end))
18162 (imagetype (or (intern imagetype) 'png)))
18163 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18164 (overlay-put ov 'evaporate t)
18165 (overlay-put ov
18166 'modification-hooks
18167 (list (lambda (o _flag _beg _end &optional _l)
18168 (delete-overlay o))))
18169 (overlay-put ov
18170 'display
18171 (list 'image :type imagetype :file image :ascent 'center))))
18173 (defun org--list-latex-overlays (&optional beg end)
18174 "List all Org LaTeX overlays in current buffer.
18175 Limit to overlays between BEG and END when those are provided."
18176 (cl-remove-if-not
18177 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18178 (overlays-in (or beg (point-min)) (or end (point-max)))))
18180 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18181 "Remove all overlays with LaTeX fragment images in current buffer.
18182 When optional arguments BEG and END are non-nil, remove all
18183 overlays between them instead. Return a non-nil value when some
18184 overlays were removed, nil otherwise."
18185 (let ((overlays (org--list-latex-overlays beg end)))
18186 (mapc #'delete-overlay overlays)
18187 overlays))
18189 (defun org-toggle-latex-fragment (&optional arg)
18190 "Preview the LaTeX fragment at point, or all locally or globally.
18192 If the cursor is on a LaTeX fragment, create the image and overlay
18193 it over the source code, if there is none. Remove it otherwise.
18194 If there is no fragment at point, display all fragments in the
18195 current section.
18197 With prefix ARG, preview or clear image for all fragments in the
18198 current subtree or in the whole buffer when used before the first
18199 headline. With a prefix ARG `\\[universal-argument] \
18200 \\[universal-argument]' preview or clear images
18201 for all fragments in the buffer."
18202 (interactive "P")
18203 (when (display-graphic-p)
18204 (catch 'exit
18205 (save-excursion
18206 (let (beg end msg)
18207 (cond
18208 ((or (equal arg '(16))
18209 (and (equal arg '(4))
18210 (org-with-limited-levels (org-before-first-heading-p))))
18211 (if (org-remove-latex-fragment-image-overlays)
18212 (progn (message "LaTeX fragments images removed from buffer")
18213 (throw 'exit nil))
18214 (setq msg "Creating images for buffer...")))
18215 ((equal arg '(4))
18216 (org-with-limited-levels (org-back-to-heading t))
18217 (setq beg (point))
18218 (setq end (progn (org-end-of-subtree t) (point)))
18219 (if (org-remove-latex-fragment-image-overlays beg end)
18220 (progn
18221 (message "LaTeX fragment images removed from subtree")
18222 (throw 'exit nil))
18223 (setq msg "Creating images for subtree...")))
18224 ((let ((datum (org-element-context)))
18225 (when (memq (org-element-type datum)
18226 '(latex-environment latex-fragment))
18227 (setq beg (org-element-property :begin datum))
18228 (setq end (org-element-property :end datum))
18229 (if (org-remove-latex-fragment-image-overlays beg end)
18230 (progn (message "LaTeX fragment image removed")
18231 (throw 'exit nil))
18232 (setq msg "Creating image...")))))
18234 (org-with-limited-levels
18235 (setq beg (if (org-at-heading-p) (line-beginning-position)
18236 (outline-previous-heading)
18237 (point)))
18238 (setq end (progn (outline-next-heading) (point)))
18239 (if (org-remove-latex-fragment-image-overlays beg end)
18240 (progn
18241 (message "LaTeX fragment images removed from section")
18242 (throw 'exit nil))
18243 (setq msg "Creating images for section...")))))
18244 (let ((file (buffer-file-name (buffer-base-buffer))))
18245 (org-format-latex
18246 (concat org-preview-latex-image-directory "org-ltximg")
18247 beg end
18248 ;; Emacs cannot overlay images from remote hosts. Create
18249 ;; it in `temporary-file-directory' instead.
18250 (if (or (not file) (file-remote-p file))
18251 temporary-file-directory
18252 default-directory)
18253 'overlays msg 'forbuffer org-preview-latex-default-process))
18254 (message (concat msg "done")))))))
18256 (defun org-format-latex
18257 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18258 "Replace LaTeX fragments with links to an image.
18260 The function takes care of creating the replacement image.
18262 Only consider fragments between BEG and END when those are
18263 provided.
18265 When optional argument OVERLAYS is non-nil, display the image on
18266 top of the fragment instead of replacing it.
18268 PROCESSING-TYPE is the conversion method to use, as a symbol.
18270 Some of the options can be changed using the variable
18271 `org-format-latex-options', which see."
18272 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18273 (unless (eq processing-type 'verbatim)
18274 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18275 (cnt 0)
18276 checkdir-flag)
18277 (goto-char (or beg (point-min)))
18278 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18279 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18280 (overlay-recenter (or end (point-max))))
18281 (while (re-search-forward math-regexp end t)
18282 (unless (and overlays
18283 (eq (get-char-property (point) 'org-overlay-type)
18284 'org-latex-overlay))
18285 (let* ((context (org-element-context))
18286 (type (org-element-type context)))
18287 (when (memq type '(latex-environment latex-fragment))
18288 (let ((block-type (eq type 'latex-environment))
18289 (value (org-element-property :value context))
18290 (beg (org-element-property :begin context))
18291 (end (save-excursion
18292 (goto-char (org-element-property :end context))
18293 (skip-chars-backward " \r\t\n")
18294 (point))))
18295 (cond
18296 ((eq processing-type 'mathjax)
18297 ;; Prepare for MathJax processing.
18298 (if (not (string-match "\\`\\$\\$?" value))
18299 (goto-char end)
18300 (delete-region beg end)
18301 (if (string= (match-string 0 value) "$$")
18302 (insert "\\[" (substring value 2 -2) "\\]")
18303 (insert "\\(" (substring value 1 -1) "\\)"))))
18304 ((assq processing-type org-preview-latex-process-alist)
18305 ;; Process to an image.
18306 (cl-incf cnt)
18307 (goto-char beg)
18308 (let* ((processing-info
18309 (cdr (assq processing-type org-preview-latex-process-alist)))
18310 (face (face-at-point))
18311 ;; Get the colors from the face at point.
18313 (let ((color (plist-get org-format-latex-options
18314 :foreground)))
18315 (if (and forbuffer (eq color 'auto))
18316 (face-attribute face :foreground nil 'default)
18317 color)))
18319 (let ((color (plist-get org-format-latex-options
18320 :background)))
18321 (if (and forbuffer (eq color 'auto))
18322 (face-attribute face :background nil 'default)
18323 color)))
18324 (hash (sha1 (prin1-to-string
18325 (list org-format-latex-header
18326 org-latex-default-packages-alist
18327 org-latex-packages-alist
18328 org-format-latex-options
18329 forbuffer value fg bg))))
18330 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18331 (absprefix (expand-file-name prefix dir))
18332 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18333 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18334 (sep (and block-type "\n\n"))
18335 (link (concat sep "[[file:" linkfile "]]" sep))
18336 (options
18337 (org-combine-plists
18338 org-format-latex-options
18339 `(:foreground ,fg :background ,bg))))
18340 (when msg (message msg cnt))
18341 (unless checkdir-flag ; Ensure the directory exists.
18342 (setq checkdir-flag t)
18343 (let ((todir (file-name-directory absprefix)))
18344 (unless (file-directory-p todir)
18345 (make-directory todir t))))
18346 (unless (file-exists-p movefile)
18347 (org-create-formula-image
18348 value movefile options forbuffer processing-type))
18349 (if overlays
18350 (progn
18351 (dolist (o (overlays-in beg end))
18352 (when (eq (overlay-get o 'org-overlay-type)
18353 'org-latex-overlay)
18354 (delete-overlay o)))
18355 (org--format-latex-make-overlay beg end movefile imagetype)
18356 (goto-char end))
18357 (delete-region beg end)
18358 (insert
18359 (org-add-props link
18360 (list 'org-latex-src
18361 (replace-regexp-in-string "\"" "" value)
18362 'org-latex-src-embed-type
18363 (if block-type 'paragraph 'character)))))))
18364 ((eq processing-type 'mathml)
18365 ;; Process to MathML.
18366 (unless (org-format-latex-mathml-available-p)
18367 (user-error "LaTeX to MathML converter not configured"))
18368 (cl-incf cnt)
18369 (when msg (message msg cnt))
18370 (goto-char beg)
18371 (delete-region beg end)
18372 (insert (org-format-latex-as-mathml
18373 value block-type prefix dir)))
18375 (error "Unknown conversion process %s for LaTeX fragments"
18376 processing-type)))))))))))
18378 (defun org-create-math-formula (latex-frag &optional mathml-file)
18379 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18380 Use `org-latex-to-mathml-convert-command'. If the conversion is
18381 sucessful, return the portion between \"<math...> </math>\"
18382 elements otherwise return nil. When MATHML-FILE is specified,
18383 write the results in to that file. When invoked as an
18384 interactive command, prompt for LATEX-FRAG, with initial value
18385 set to the current active region and echo the results for user
18386 inspection."
18387 (interactive (list (let ((frag (when (org-region-active-p)
18388 (buffer-substring-no-properties
18389 (region-beginning) (region-end)))))
18390 (read-string "LaTeX Fragment: " frag nil frag))))
18391 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18392 (let* ((tmp-in-file
18393 (let ((file (file-relative-name
18394 (make-temp-name (expand-file-name "ltxmathml-in")))))
18395 (write-region latex-frag nil file)
18396 file))
18397 (tmp-out-file (file-relative-name
18398 (make-temp-name (expand-file-name "ltxmathml-out"))))
18399 (cmd (format-spec
18400 org-latex-to-mathml-convert-command
18401 `((?j . ,(and org-latex-to-mathml-jar-file
18402 (shell-quote-argument
18403 (expand-file-name
18404 org-latex-to-mathml-jar-file))))
18405 (?I . ,(shell-quote-argument tmp-in-file))
18406 (?i . ,latex-frag)
18407 (?o . ,(shell-quote-argument tmp-out-file)))))
18408 mathml shell-command-output)
18409 (when (called-interactively-p 'any)
18410 (unless (org-format-latex-mathml-available-p)
18411 (user-error "LaTeX to MathML converter not configured")))
18412 (message "Running %s" cmd)
18413 (setq shell-command-output (shell-command-to-string cmd))
18414 (setq mathml
18415 (when (file-readable-p tmp-out-file)
18416 (with-current-buffer (find-file-noselect tmp-out-file t)
18417 (goto-char (point-min))
18418 (when (re-search-forward
18419 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18420 (regexp-quote
18421 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18422 nil t)
18423 (prog1 (match-string 0) (kill-buffer))))))
18424 (cond
18425 (mathml
18426 (setq mathml
18427 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18428 (when mathml-file
18429 (write-region mathml nil mathml-file))
18430 (when (called-interactively-p 'any)
18431 (message mathml)))
18432 ((message "LaTeX to MathML conversion failed")
18433 (message shell-command-output)))
18434 (delete-file tmp-in-file)
18435 (when (file-exists-p tmp-out-file)
18436 (delete-file tmp-out-file))
18437 mathml))
18439 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18440 prefix &optional dir)
18441 "Use `org-create-math-formula' but check local cache first."
18442 (let* ((absprefix (expand-file-name prefix dir))
18443 (print-length nil) (print-level nil)
18444 (formula-id (concat
18445 "formula-"
18446 (sha1
18447 (prin1-to-string
18448 (list latex-frag
18449 org-latex-to-mathml-convert-command)))))
18450 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18451 (formula-cache-dir (file-name-directory formula-cache)))
18453 (unless (file-directory-p formula-cache-dir)
18454 (make-directory formula-cache-dir t))
18456 (unless (file-exists-p formula-cache)
18457 (org-create-math-formula latex-frag formula-cache))
18459 (if (file-exists-p formula-cache)
18460 ;; Successful conversion. Return the link to MathML file.
18461 (org-add-props
18462 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18463 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18464 'org-latex-src-embed-type (if latex-frag-type
18465 'paragraph 'character)))
18466 ;; Failed conversion. Return the LaTeX fragment verbatim
18467 latex-frag)))
18469 (defun org--get-display-dpi ()
18470 "Get the DPI of the display.
18471 The function assumes that the display has the same pixel width in
18472 the horizontal and vertical directions."
18473 (if (display-graphic-p)
18474 (round (/ (display-pixel-height)
18475 (/ (display-mm-height) 25.4)))
18476 (error "Attempt to calculate the dpi of a non-graphic display")))
18478 (defun org-create-formula-image
18479 (string tofile options buffer &optional processing-type)
18480 "Create an image from LaTeX source using external processes.
18482 The LaTeX STRING is saved to a temporary LaTeX file, then
18483 converted to an image file by process PROCESSING-TYPE defined in
18484 `org-preview-latex-process-alist'. A nil value defaults to
18485 `org-preview-latex-default-process'.
18487 The generated image file is eventually moved to TOFILE.
18489 The OPTIONS argument controls the size, foreground color and
18490 background color of the generated image.
18492 When BUFFER non-nil, this function is used for LaTeX previewing.
18493 Otherwise, it is used to deal with LaTeX snippets showed in
18494 a HTML file."
18495 (let* ((processing-type (or processing-type
18496 org-preview-latex-default-process))
18497 (processing-info
18498 (cdr (assq processing-type org-preview-latex-process-alist)))
18499 (programs (plist-get processing-info :programs))
18500 (error-message (or (plist-get processing-info :message) ""))
18501 (use-xcolor (plist-get processing-info :use-xcolor))
18502 (image-input-type (plist-get processing-info :image-input-type))
18503 (image-output-type (plist-get processing-info :image-output-type))
18504 (post-clean (or (plist-get processing-info :post-clean)
18505 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18506 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18507 (latex-header
18508 (or (plist-get processing-info :latex-header)
18509 (org-latex-make-preamble
18510 (org-export-get-environment (org-export-get-backend 'latex))
18511 org-format-latex-header
18512 'snippet)))
18513 (latex-compiler (plist-get processing-info :latex-compiler))
18514 (image-converter (plist-get processing-info :image-converter))
18515 (tmpdir temporary-file-directory)
18516 (texfilebase (make-temp-name
18517 (expand-file-name "orgtex" tmpdir)))
18518 (texfile (concat texfilebase ".tex"))
18519 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18520 '(1.0 . 1.0)))
18521 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18522 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18523 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18524 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18525 "Black"))
18526 (bg (or (plist-get options (if buffer :background :html-background))
18527 "Transparent"))
18528 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18529 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18530 (dolist (program programs)
18531 (org-check-external-command program error-message))
18532 (if use-xcolor
18533 (progn (if (eq fg 'default)
18534 (setq fg (org-latex-color :foreground))
18535 (setq fg (org-latex-color-format fg)))
18536 (if (eq bg 'default)
18537 (setq bg (org-latex-color :background))
18538 (setq bg (org-latex-color-format
18539 (if (string= bg "Transparent") "white" bg))))
18540 (with-temp-file texfile
18541 (insert latex-header)
18542 (insert "\n\\begin{document}\n"
18543 "\\definecolor{fg}{rgb}{" fg "}\n"
18544 "\\definecolor{bg}{rgb}{" bg "}\n"
18545 "\n\\pagecolor{bg}\n"
18546 "\n{\\color{fg}\n"
18547 string
18548 "\n}\n"
18549 "\n\\end{document}\n")))
18550 (if (eq fg 'default)
18551 (setq fg (org-dvipng-color :foreground))
18552 (unless (string= fg "Transparent")
18553 (setq fg (org-dvipng-color-format fg))))
18554 (if (eq bg 'default)
18555 (setq bg (org-dvipng-color :background))
18556 (unless (string= bg "Transparent")
18557 (setq bg (org-dvipng-color-format bg))))
18558 (with-temp-file texfile
18559 (insert latex-header)
18560 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18562 (let* ((err-msg (format "Please adjust `%s' part of \
18563 `org-preview-latex-process-alist'."
18564 processing-type))
18565 (image-input-file
18566 (org-compile-file
18567 texfile latex-compiler image-input-type err-msg log-buf))
18568 (image-output-file
18569 (org-compile-file
18570 image-input-file image-converter image-output-type err-msg log-buf
18571 `((?F . ,(shell-quote-argument fg))
18572 (?B . ,(shell-quote-argument bg))
18573 (?D . ,(shell-quote-argument (format "%s" dpi)))
18574 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18575 (copy-file image-output-file tofile 'replace)
18576 (dolist (e post-clean)
18577 (when (file-exists-p (concat texfilebase e))
18578 (delete-file (concat texfilebase e))))
18579 image-output-file)))
18581 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18582 "Fill a LaTeX header template TPL.
18583 In the template, the following place holders will be recognized:
18585 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18586 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18587 [PACKAGES] \\usepackage statements for PKG
18588 [NO-PACKAGES] do not include PKG
18589 [EXTRA] the string EXTRA
18590 [NO-EXTRA] do not include EXTRA
18592 For backward compatibility, if both the positive and the negative place
18593 holder is missing, the positive one (without the \"NO-\") will be
18594 assumed to be present at the end of the template.
18595 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18596 EXTRA is a string.
18597 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18598 (let (rpl (end ""))
18599 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18600 (setq rpl (if (or (match-end 1) (not def-pkg))
18601 "" (org-latex-packages-to-string def-pkg snippets-p t))
18602 tpl (replace-match rpl t t tpl))
18603 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18605 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18606 (setq rpl (if (or (match-end 1) (not pkg))
18607 "" (org-latex-packages-to-string pkg snippets-p t))
18608 tpl (replace-match rpl t t tpl))
18609 (when pkg (setq end
18610 (concat end "\n"
18611 (org-latex-packages-to-string pkg snippets-p)))))
18613 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18614 (setq rpl (if (or (match-end 1) (not extra))
18615 "" (concat extra "\n"))
18616 tpl (replace-match rpl t t tpl))
18617 (when (and extra (string-match "\\S-" extra))
18618 (setq end (concat end "\n" extra))))
18620 (if (string-match "\\S-" end)
18621 (concat tpl "\n" end)
18622 tpl)))
18624 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18625 "Turn an alist of packages into a string with the \\usepackage macros."
18626 (setq pkg (mapconcat (lambda(p)
18627 (cond
18628 ((stringp p) p)
18629 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18630 (format "%% Package %s omitted" (cadr p)))
18631 ((equal "" (car p))
18632 (format "\\usepackage{%s}" (cadr p)))
18634 (format "\\usepackage[%s]{%s}"
18635 (car p) (cadr p)))))
18637 "\n"))
18638 (if newline (concat pkg "\n") pkg))
18640 (defun org-dvipng-color (attr)
18641 "Return a RGB color specification for dvipng."
18642 (org-dvipng-color-format (face-attribute 'default attr nil)))
18644 (defun org-dvipng-color-format (color-name)
18645 "Convert COLOR-NAME to a RGB color value for dvipng."
18646 (apply #'format "rgb %s %s %s"
18647 (mapcar 'org-normalize-color
18648 (color-values color-name))))
18650 (defun org-latex-color (attr)
18651 "Return a RGB color for the LaTeX color package."
18652 (org-latex-color-format (face-attribute 'default attr nil)))
18654 (defun org-latex-color-format (color-name)
18655 "Convert COLOR-NAME to a RGB color value."
18656 (apply #'format "%s,%s,%s"
18657 (mapcar 'org-normalize-color
18658 (color-values color-name))))
18660 (defun org-normalize-color (value)
18661 "Return string to be used as color value for an RGB component."
18662 (format "%g" (/ value 65535.0)))
18666 ;; Image display
18668 (defvar-local org-inline-image-overlays nil)
18670 (defun org-toggle-inline-images (&optional include-linked)
18671 "Toggle the display of inline images.
18672 INCLUDE-LINKED is passed to `org-display-inline-images'."
18673 (interactive "P")
18674 (if org-inline-image-overlays
18675 (progn
18676 (org-remove-inline-images)
18677 (when (called-interactively-p 'interactive)
18678 (message "Inline image display turned off")))
18679 (org-display-inline-images include-linked)
18680 (when (called-interactively-p 'interactive)
18681 (message (if org-inline-image-overlays
18682 (format "%d images displayed inline"
18683 (length org-inline-image-overlays))
18684 "No images to display inline")))))
18686 (defun org-redisplay-inline-images ()
18687 "Refresh the display of inline images."
18688 (interactive)
18689 (if (not org-inline-image-overlays)
18690 (org-toggle-inline-images)
18691 (org-toggle-inline-images)
18692 (org-toggle-inline-images)))
18694 (defun org-display-inline-images (&optional include-linked refresh beg end)
18695 "Display inline images.
18697 An inline image is a link which follows either of these
18698 conventions:
18700 1. Its path is a file with an extension matching return value
18701 from `image-file-name-regexp' and it has no contents.
18703 2. Its description consists in a single link of the previous
18704 type.
18706 When optional argument INCLUDE-LINKED is non-nil, also links with
18707 a text description part will be inlined. This can be nice for
18708 a quick look at those images, but it does not reflect what
18709 exported files will look like.
18711 When optional argument REFRESH is non-nil, refresh existing
18712 images between BEG and END. This will create new image displays
18713 only if necessary. BEG and END default to the buffer
18714 boundaries."
18715 (interactive "P")
18716 (when (display-graphic-p)
18717 (unless refresh
18718 (org-remove-inline-images)
18719 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18720 (org-with-wide-buffer
18721 (goto-char (or beg (point-min)))
18722 (let* ((case-fold-search t)
18723 (file-extension-re (image-file-name-regexp))
18724 (link-abbrevs (mapcar #'car
18725 (append org-link-abbrev-alist-local
18726 org-link-abbrev-alist)))
18727 ;; Check absolute, relative file names and explicit
18728 ;; "file:" links. Also check link abbreviations since
18729 ;; some might expand to "file" links.
18730 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18731 (if (not link-abbrevs) ""
18732 (format "\\|\\(?:%s:\\)"
18733 (regexp-opt link-abbrevs))))))
18734 (while (re-search-forward file-types-re end t)
18735 (let ((link (save-match-data (org-element-context))))
18736 ;; Check if we're at an inline image, i.e., an image file
18737 ;; link without a description (unless INCLUDE-LINKED is
18738 ;; non-nil).
18739 (when (and (equal "file" (org-element-property :type link))
18740 (or include-linked
18741 (null (org-element-contents link)))
18742 (string-match-p file-extension-re
18743 (org-element-property :path link)))
18744 (let ((file (expand-file-name
18745 (org-link-unescape
18746 (org-element-property :path link)))))
18747 (when (file-exists-p file)
18748 (let ((width
18749 ;; Apply `org-image-actual-width' specifications.
18750 (cond
18751 ((not (image-type-available-p 'imagemagick)) nil)
18752 ((eq org-image-actual-width t) nil)
18753 ((listp org-image-actual-width)
18755 ;; First try to find a width among
18756 ;; attributes associated to the paragraph
18757 ;; containing link.
18758 (let ((paragraph
18759 (let ((e link))
18760 (while (and (setq e (org-element-property
18761 :parent e))
18762 (not (eq (org-element-type e)
18763 'paragraph))))
18764 e)))
18765 (when paragraph
18766 (save-excursion
18767 (goto-char (org-element-property :begin paragraph))
18768 (when
18769 (re-search-forward
18770 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18771 (org-element-property
18772 :post-affiliated paragraph)
18774 (string-to-number (match-string 1))))))
18775 ;; Otherwise, fall-back to provided number.
18776 (car org-image-actual-width)))
18777 ((numberp org-image-actual-width)
18778 org-image-actual-width)))
18779 (old (get-char-property-and-overlay
18780 (org-element-property :begin link)
18781 'org-image-overlay)))
18782 (if (and (car-safe old) refresh)
18783 (image-refresh (overlay-get (cdr old) 'display))
18784 (let ((image (create-image file
18785 (and width 'imagemagick)
18787 :width width)))
18788 (when image
18789 (let ((ov (make-overlay
18790 (org-element-property :begin link)
18791 (progn
18792 (goto-char
18793 (org-element-property :end link))
18794 (skip-chars-backward " \t")
18795 (point)))))
18796 (overlay-put ov 'display image)
18797 (overlay-put ov 'face 'default)
18798 (overlay-put ov 'org-image-overlay t)
18799 (overlay-put
18800 ov 'modification-hooks
18801 (list 'org-display-inline-remove-overlay))
18802 (push ov org-inline-image-overlays)))))))))))))))
18804 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18805 "Remove inline-display overlay if a corresponding region is modified."
18806 (let ((inhibit-modification-hooks t))
18807 (when (and ov after)
18808 (delete ov org-inline-image-overlays)
18809 (delete-overlay ov))))
18811 (defun org-remove-inline-images ()
18812 "Remove inline display of images."
18813 (interactive)
18814 (mapc #'delete-overlay org-inline-image-overlays)
18815 (setq org-inline-image-overlays nil))
18818 ;;; Key bindings
18820 (defun org-remap (map &rest commands)
18821 "In MAP, remap the functions given in COMMANDS.
18822 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18823 (let (new old)
18824 (while commands
18825 (setq old (pop commands) new (pop commands))
18826 (org-defkey map (vector 'remap old) new))))
18828 ;;;; Outline functions that can be remapped in Org
18829 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18830 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18831 (define-key org-mode-map [remap outline-forward-same-level]
18832 #'org-forward-heading-same-level)
18833 (define-key org-mode-map [remap outline-backward-same-level]
18834 #'org-backward-heading-same-level)
18835 (define-key org-mode-map [remap outline-show-branches]
18836 #'org-kill-note-or-show-branches)
18837 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18838 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18839 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18840 (define-key org-mode-map [remap outline-next-visible-heading]
18841 #'org-next-visible-heading)
18842 (define-key org-mode-map [remap outline-previous-visible-heading]
18843 #'org-previous-visible-heading)
18844 (define-key org-mode-map [remap show-children] #'org-show-children)
18846 ;;;; Make `C-c C-x' a prefix key
18847 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18849 ;;;; TAB key with modifiers
18850 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18851 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18852 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18853 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18854 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18856 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18857 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18858 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18860 ;;;; RET key with modifiers
18861 (org-defkey org-mode-map (kbd "S-RET") #'org-table-copy-down)
18862 (org-defkey org-mode-map (kbd "M-S-RET") #'org-insert-todo-heading)
18863 (org-defkey org-mode-map (kbd "ESC S-RET") #'org-insert-todo-heading)
18864 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18865 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18867 ;;;; Cursor keys with modifiers
18868 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18869 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18870 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18871 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18872 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18873 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18874 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18876 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18877 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18878 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18879 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18880 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18881 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18882 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18883 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18884 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18885 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18887 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18888 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18889 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18890 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18892 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18893 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18894 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18895 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18897 ;;;; Babel keys
18898 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18899 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18900 (define-key org-babel-map key def))
18902 ;;;; Extra keys for TTY access.
18904 ;; We only set them when really needed because otherwise the
18905 ;; menus don't show the simple keys
18907 (when (or org-use-extra-keys (not window-system))
18908 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18909 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18910 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18911 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18912 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18913 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18914 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18915 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18916 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18917 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18918 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18919 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18920 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18921 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18922 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18923 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18924 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18925 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18926 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18927 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18929 ;;;; Narrow map
18930 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18931 (org-defkey narrow-map "b" #'org-narrow-to-block)
18932 (org-defkey narrow-map "e" #'org-narrow-to-element)
18934 ;;;; Remap usual Emacs bindings
18935 (org-remap org-mode-map
18936 'self-insert-command 'org-self-insert-command
18937 'delete-char 'org-delete-char
18938 'delete-backward-char 'org-delete-backward-char
18939 'open-line 'org-open-line
18940 'comment-dwim 'org-comment-dwim
18941 'forward-paragraph 'org-forward-paragraph
18942 'backward-paragraph 'org-backward-paragraph
18943 'delete-indentation 'org-delete-indentation)
18945 ;;;; All the other keys
18946 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18947 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18948 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18949 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18950 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18951 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18952 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18953 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18954 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18955 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18956 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18957 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18958 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18959 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18960 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18961 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18962 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18963 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18964 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
18965 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
18966 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
18967 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
18968 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
18969 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
18970 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
18971 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
18972 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
18973 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
18974 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
18975 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
18976 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
18977 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
18978 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
18979 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
18980 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
18981 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
18982 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
18983 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
18984 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
18985 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
18986 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
18987 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
18988 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
18989 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
18990 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
18991 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
18992 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
18993 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
18994 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
18995 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
18996 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
18997 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
18998 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
18999 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19000 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19001 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19002 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19003 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19004 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19005 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19006 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19007 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19008 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19009 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19010 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19011 (org-defkey org-mode-map (kbd "RET") #'org-return)
19012 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19013 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19014 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19015 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19016 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19017 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19018 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19019 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19020 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19021 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19022 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19023 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19024 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19025 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19026 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19027 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19028 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19029 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19030 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19031 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19032 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19033 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19034 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19036 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19037 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19038 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19040 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19041 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19042 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19043 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19044 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19045 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19046 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19047 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19048 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19049 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19050 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19051 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19052 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19053 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19054 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19055 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19056 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19057 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19058 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19059 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19060 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19061 (org-defkey org-mode-map (kbd "C-c C-x w") #'org-insert-structure-template)
19063 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19064 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19065 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19066 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19067 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19068 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19070 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19072 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19074 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19075 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19077 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19080 ;;; Speed commands
19082 (defconst org-speed-commands-default
19084 ("Outline Navigation")
19085 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19086 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19087 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19088 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19089 ("F" . org-next-block)
19090 ("B" . org-previous-block)
19091 ("u" . (org-speed-move-safe 'outline-up-heading))
19092 ("j" . org-goto)
19093 ("g" . (org-refile t))
19094 ("Outline Visibility")
19095 ("c" . org-cycle)
19096 ("C" . org-shifttab)
19097 (" " . org-display-outline-path)
19098 ("s" . org-narrow-to-subtree)
19099 ("=" . org-columns)
19100 ("Outline Structure Editing")
19101 ("U" . org-metaup)
19102 ("D" . org-metadown)
19103 ("r" . org-metaright)
19104 ("l" . org-metaleft)
19105 ("R" . org-shiftmetaright)
19106 ("L" . org-shiftmetaleft)
19107 ("i" . (progn (forward-char 1) (call-interactively
19108 'org-insert-heading-respect-content)))
19109 ("^" . org-sort)
19110 ("w" . org-refile)
19111 ("a" . org-archive-subtree-default-with-confirmation)
19112 ("@" . org-mark-subtree)
19113 ("#" . org-toggle-comment)
19114 ("Clock Commands")
19115 ("I" . org-clock-in)
19116 ("O" . org-clock-out)
19117 ("Meta Data Editing")
19118 ("t" . org-todo)
19119 ("," . (org-priority))
19120 ("0" . (org-priority ?\ ))
19121 ("1" . (org-priority ?A))
19122 ("2" . (org-priority ?B))
19123 ("3" . (org-priority ?C))
19124 (":" . org-set-tags-command)
19125 ("e" . org-set-effort)
19126 ("E" . org-inc-effort)
19127 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19128 (org-entry-put (point) "APPT_WARNTIME" m)))
19129 ("Agenda Views etc")
19130 ("v" . org-agenda)
19131 ("/" . org-sparse-tree)
19132 ("Misc")
19133 ("o" . org-open-at-point)
19134 ("?" . org-speed-command-help)
19135 ("<" . (org-agenda-set-restriction-lock 'subtree))
19136 (">" . (org-agenda-remove-restriction-lock))
19138 "The default speed commands.")
19140 (defun org-print-speed-command (e)
19141 (if (> (length (car e)) 1)
19142 (progn
19143 (princ "\n")
19144 (princ (car e))
19145 (princ "\n")
19146 (princ (make-string (length (car e)) ?-))
19147 (princ "\n"))
19148 (princ (car e))
19149 (princ " ")
19150 (if (symbolp (cdr e))
19151 (princ (symbol-name (cdr e)))
19152 (prin1 (cdr e)))
19153 (princ "\n")))
19155 (defun org-speed-command-help ()
19156 "Show the available speed commands."
19157 (interactive)
19158 (if (not org-use-speed-commands)
19159 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19160 (with-output-to-temp-buffer "*Help*"
19161 (princ "User-defined Speed commands\n===========================\n")
19162 (mapc #'org-print-speed-command org-speed-commands-user)
19163 (princ "\n")
19164 (princ "Built-in Speed commands\n=======================\n")
19165 (mapc #'org-print-speed-command org-speed-commands-default))
19166 (with-current-buffer "*Help*"
19167 (setq truncate-lines t))))
19169 (defun org-speed-move-safe (cmd)
19170 "Execute CMD, but make sure that the cursor always ends up in a headline.
19171 If not, return to the original position and throw an error."
19172 (interactive)
19173 (let ((pos (point)))
19174 (call-interactively cmd)
19175 (unless (and (bolp) (org-at-heading-p))
19176 (goto-char pos)
19177 (error "Boundary reached while executing %s" cmd))))
19179 (defvar org-self-insert-command-undo-counter 0)
19181 (defvar org-table-auto-blank-field) ; defined in org-table.el
19182 (defvar org-speed-command nil)
19184 (defun org-speed-command-activate (keys)
19185 "Hook for activating single-letter speed commands.
19186 `org-speed-commands-default' specifies a minimal command set.
19187 Use `org-speed-commands-user' for further customization."
19188 (when (or (and (bolp) (looking-at org-outline-regexp))
19189 (and (functionp org-use-speed-commands)
19190 (funcall org-use-speed-commands)))
19191 (cdr (assoc keys (append org-speed-commands-user
19192 org-speed-commands-default)))))
19194 (defun org-babel-speed-command-activate (keys)
19195 "Hook for activating single-letter code block commands."
19196 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19197 (cdr (assoc keys org-babel-key-bindings))))
19199 (defcustom org-speed-command-hook
19200 '(org-speed-command-activate org-babel-speed-command-activate)
19201 "Hook for activating speed commands at strategic locations.
19202 Hook functions are called in sequence until a valid handler is
19203 found.
19205 Each hook takes a single argument, a user-pressed command key
19206 which is also a `self-insert-command' from the global map.
19208 Within the hook, examine the cursor position and the command key
19209 and return nil or a valid handler as appropriate. Handler could
19210 be one of an interactive command, a function, or a form.
19212 Set `org-use-speed-commands' to non-nil value to enable this
19213 hook. The default setting is `org-speed-command-activate'."
19214 :group 'org-structure
19215 :version "24.1"
19216 :type 'hook)
19218 (defun org-self-insert-command (N)
19219 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19220 If the cursor is in a table looking at whitespace, the whitespace is
19221 overwritten, and the table is not marked as requiring realignment."
19222 (interactive "p")
19223 (org-check-before-invisible-edit 'insert)
19224 (cond
19225 ((and org-use-speed-commands
19226 (let ((kv (this-command-keys-vector)))
19227 (setq org-speed-command
19228 (run-hook-with-args-until-success
19229 'org-speed-command-hook
19230 (make-string 1 (aref kv (1- (length kv))))))))
19231 (cond
19232 ((commandp org-speed-command)
19233 (setq this-command org-speed-command)
19234 (call-interactively org-speed-command))
19235 ((functionp org-speed-command)
19236 (funcall org-speed-command))
19237 ((and org-speed-command (listp org-speed-command))
19238 (eval org-speed-command))
19239 (t (let (org-use-speed-commands)
19240 (call-interactively 'org-self-insert-command)))))
19241 ((and
19242 (= N 1)
19243 (not (org-region-active-p))
19244 (org-at-table-p)
19245 (progn
19246 ;; Check if we blank the field, and if that triggers align.
19247 (and (featurep 'org-table)
19248 org-table-auto-blank-field
19249 (memq last-command
19250 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19251 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19252 ;; Got extra space, this field does not determine
19253 ;; column width.
19254 (let (org-table-may-need-update) (org-table-blank-field))
19255 ;; No extra space, this field may determine column
19256 ;; width.
19257 (org-table-blank-field)))
19259 (looking-at "[^|\n]* |"))
19260 ;; There is room for insertion without re-aligning the table.
19261 (self-insert-command N)
19262 (org-table-with-shrunk-field
19263 (save-excursion
19264 (skip-chars-forward "^|")
19265 ;; Do not delete last space, which is
19266 ;; `org-table-separator-space', but the regular space before
19267 ;; it.
19268 (delete-region (- (point) 2) (1- (point))))))
19270 (setq org-table-may-need-update t)
19271 (self-insert-command N)
19272 (org-fix-tags-on-the-fly)
19273 (when org-self-insert-cluster-for-undo
19274 (if (not (eq last-command 'org-self-insert-command))
19275 (setq org-self-insert-command-undo-counter 1)
19276 (if (>= org-self-insert-command-undo-counter 20)
19277 (setq org-self-insert-command-undo-counter 1)
19278 (and (> org-self-insert-command-undo-counter 0)
19279 buffer-undo-list (listp buffer-undo-list)
19280 (not (cadr buffer-undo-list)) ; remove nil entry
19281 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19282 (setq org-self-insert-command-undo-counter
19283 (1+ org-self-insert-command-undo-counter))))))))
19285 (defun org-check-before-invisible-edit (kind)
19286 "Check is editing if kind KIND would be dangerous with invisible text around.
19287 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19288 ;; First, try to get out of here as quickly as possible, to reduce overhead
19289 (when (and org-catch-invisible-edits
19290 (or (not (boundp 'visible-mode)) (not visible-mode))
19291 (or (get-char-property (point) 'invisible)
19292 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19293 ;; OK, we need to take a closer look. Do not consider
19294 ;; invisibility obtained through text properties (e.g., link
19295 ;; fontification), as it cannot be toggled.
19296 (let* ((invisible-at-point
19297 (pcase (get-char-property-and-overlay (point) 'invisible)
19298 (`(,_ . ,(and (pred overlayp) o)) o)))
19299 ;; Assume that point cannot land in the middle of an
19300 ;; overlay, or between two overlays.
19301 (invisible-before-point
19302 (and (not invisible-at-point)
19303 (not (bobp))
19304 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19305 (`(,_ . ,(and (pred overlayp) o)) o))))
19306 (border-and-ok-direction
19308 ;; Check if we are acting predictably before invisible
19309 ;; text.
19310 (and invisible-at-point
19311 (memq kind '(insert delete-backward)))
19312 ;; Check if we are acting predictably after invisible text
19313 ;; This works not well, and I have turned it off. It seems
19314 ;; better to always show and stop after invisible text.
19315 ;; (and (not invisible-at-point) invisible-before-point
19316 ;; (memq kind '(insert delete)))
19318 (when (or invisible-at-point invisible-before-point)
19319 (when (eq org-catch-invisible-edits 'error)
19320 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19321 (if (and org-custom-properties-overlays
19322 (y-or-n-p "Display invisible properties in this buffer? "))
19323 (org-toggle-custom-properties-visibility)
19324 ;; Make the area visible
19325 (save-excursion
19326 (when invisible-before-point
19327 (goto-char
19328 (previous-single-char-property-change (point) 'invisible)))
19329 ;; Remove whatever overlay is currently making yet-to-be
19330 ;; edited text invisible. Also remove nested invisibility
19331 ;; related overlays.
19332 (delete-overlay (or invisible-at-point invisible-before-point))
19333 (let ((origin (if invisible-at-point (point) (1- (point)))))
19334 (while (pcase (get-char-property-and-overlay origin 'invisible)
19335 (`(,_ . ,(and (pred overlayp) o))
19336 (delete-overlay o)
19337 t)))))
19338 (cond
19339 ((eq org-catch-invisible-edits 'show)
19340 ;; That's it, we do the edit after showing
19341 (message
19342 "Unfolding invisible region around point before editing")
19343 (sit-for 1))
19344 ((and (eq org-catch-invisible-edits 'smart)
19345 border-and-ok-direction)
19346 (message "Unfolding invisible region around point before editing"))
19348 ;; Don't do the edit, make the user repeat it in full visibility
19349 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19351 (defun org-fix-tags-on-the-fly ()
19352 "Align tags in headline at point.
19353 Unlike to `org-set-tags', it ignores region and sorting."
19354 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19355 (org-at-heading-p))
19356 (let ((org-ignore-region t)
19357 (org-tags-sort-function nil))
19358 (org-set-tags nil t))))
19360 (defun org-delete-backward-char (N)
19361 "Like `delete-backward-char', insert whitespace at field end in tables.
19362 When deleting backwards, in tables this function will insert whitespace in
19363 front of the next \"|\" separator, to keep the table aligned. The table will
19364 still be marked for re-alignment if the field did fill the entire column,
19365 because, in this case the deletion might narrow the column."
19366 (interactive "p")
19367 (save-match-data
19368 (org-check-before-invisible-edit 'delete-backward)
19369 (if (and (= N 1)
19370 (not overwrite-mode)
19371 (not (org-region-active-p))
19372 (not (eq (char-before) ?|))
19373 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19374 (looking-at-p ".*?|")
19375 (org-at-table-p))
19376 (progn (forward-char -1) (org-delete-char 1))
19377 (backward-delete-char N)
19378 (org-fix-tags-on-the-fly))))
19380 (defun org-delete-char (N)
19381 "Like `delete-char', but insert whitespace at field end in tables.
19382 When deleting characters, in tables this function will insert whitespace in
19383 front of the next \"|\" separator, to keep the table aligned. The table will
19384 still be marked for re-alignment if the field did fill the entire column,
19385 because, in this case the deletion might narrow the column."
19386 (interactive "p")
19387 (save-match-data
19388 (org-check-before-invisible-edit 'delete)
19389 (cond
19390 ((or (/= N 1)
19391 (eq (char-after) ?|)
19392 (save-excursion (skip-chars-backward " \t") (bolp))
19393 (not (org-at-table-p)))
19394 (delete-char N)
19395 (org-fix-tags-on-the-fly))
19396 ((looking-at ".\\(.*?\\)|")
19397 (let* ((update? org-table-may-need-update)
19398 (noalign (looking-at-p ".*? |")))
19399 (delete-char 1)
19400 (org-table-with-shrunk-field
19401 (save-excursion
19402 ;; Last space is `org-table-separator-space', so insert
19403 ;; a regular one before it instead.
19404 (goto-char (- (match-end 0) 2))
19405 (insert " ")))
19406 ;; If there were two spaces at the end, this field does not
19407 ;; determine the width of the column.
19408 (when noalign (setq org-table-may-need-update update?))))
19410 (delete-char N)))))
19412 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19413 (put 'org-self-insert-command 'delete-selection
19414 (lambda ()
19415 (not (run-hook-with-args-until-success
19416 'self-insert-uses-region-functions))))
19417 (put 'orgtbl-self-insert-command 'delete-selection
19418 (lambda ()
19419 (not (run-hook-with-args-until-success
19420 'self-insert-uses-region-functions))))
19421 (put 'org-delete-char 'delete-selection 'supersede)
19422 (put 'org-delete-backward-char 'delete-selection 'supersede)
19423 (put 'org-yank 'delete-selection 'yank)
19425 ;; Make `flyspell-mode' delay after some commands
19426 (put 'org-self-insert-command 'flyspell-delayed t)
19427 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19428 (put 'org-delete-char 'flyspell-delayed t)
19429 (put 'org-delete-backward-char 'flyspell-delayed t)
19431 ;; Make pabbrev-mode expand after Org mode commands
19432 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19433 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19435 (defun org-transpose-words ()
19436 "Transpose words for Org.
19437 This uses the `org-mode-transpose-word-syntax-table' syntax
19438 table, which interprets characters in `org-emphasis-alist' as
19439 word constituents."
19440 (interactive)
19441 (with-syntax-table org-mode-transpose-word-syntax-table
19442 (call-interactively 'transpose-words)))
19443 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19445 (defvar org-ctrl-c-ctrl-c-hook nil
19446 "Hook for functions attaching themselves to `C-c C-c'.
19448 This can be used to add additional functionality to the C-c C-c
19449 key which executes context-dependent commands. This hook is run
19450 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19451 run after the last test.
19453 Each function will be called with no arguments. The function
19454 must check if the context is appropriate for it to act. If yes,
19455 it should do its thing and then return a non-nil value. If the
19456 context is wrong, just do nothing and return nil.")
19458 (defvar org-ctrl-c-ctrl-c-final-hook nil
19459 "Hook for functions attaching themselves to `C-c C-c'.
19461 This can be used to add additional functionality to the C-c C-c
19462 key which executes context-dependent commands. This hook is run
19463 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19464 before the first test.
19466 Each function will be called with no arguments. The function
19467 must check if the context is appropriate for it to act. If yes,
19468 it should do its thing and then return a non-nil value. If the
19469 context is wrong, just do nothing and return nil.")
19471 (defvar org-tab-first-hook nil
19472 "Hook for functions to attach themselves to TAB.
19473 See `org-ctrl-c-ctrl-c-hook' for more information.
19474 This hook runs as the first action when TAB is pressed, even before
19475 `org-cycle' messes around with the `outline-regexp' to cater for
19476 inline tasks and plain list item folding.
19477 If any function in this hook returns t, any other actions that
19478 would have been caused by TAB (such as table field motion or visibility
19479 cycling) will not occur.")
19481 (defvar org-tab-after-check-for-table-hook nil
19482 "Hook for functions to attach themselves to TAB.
19483 See `org-ctrl-c-ctrl-c-hook' for more information.
19484 This hook runs after it has been established that the cursor is not in a
19485 table, but before checking if the cursor is in a headline or if global cycling
19486 should be done.
19487 If any function in this hook returns t, not other actions like visibility
19488 cycling will be done.")
19490 (defvar org-tab-after-check-for-cycling-hook nil
19491 "Hook for functions to attach themselves to TAB.
19492 See `org-ctrl-c-ctrl-c-hook' for more information.
19493 This hook runs after it has been established that not table field motion and
19494 not visibility should be done because of current context. This is probably
19495 the place where a package like yasnippets can hook in.")
19497 (defvar org-tab-before-tab-emulation-hook nil
19498 "Hook for functions to attach themselves to TAB.
19499 See `org-ctrl-c-ctrl-c-hook' for more information.
19500 This hook runs after every other options for TAB have been exhausted, but
19501 before indentation and \t insertion takes place.")
19503 (defvar org-metaleft-hook nil
19504 "Hook for functions attaching themselves to `M-left'.
19505 See `org-ctrl-c-ctrl-c-hook' for more information.")
19506 (defvar org-metaright-hook nil
19507 "Hook for functions attaching themselves to `M-right'.
19508 See `org-ctrl-c-ctrl-c-hook' for more information.")
19509 (defvar org-metaup-hook nil
19510 "Hook for functions attaching themselves to `M-up'.
19511 See `org-ctrl-c-ctrl-c-hook' for more information.")
19512 (defvar org-metadown-hook nil
19513 "Hook for functions attaching themselves to `M-down'.
19514 See `org-ctrl-c-ctrl-c-hook' for more information.")
19515 (defvar org-shiftmetaleft-hook nil
19516 "Hook for functions attaching themselves to `M-S-left'.
19517 See `org-ctrl-c-ctrl-c-hook' for more information.")
19518 (defvar org-shiftmetaright-hook nil
19519 "Hook for functions attaching themselves to `M-S-right'.
19520 See `org-ctrl-c-ctrl-c-hook' for more information.")
19521 (defvar org-shiftmetaup-hook nil
19522 "Hook for functions attaching themselves to `M-S-up'.
19523 See `org-ctrl-c-ctrl-c-hook' for more information.")
19524 (defvar org-shiftmetadown-hook nil
19525 "Hook for functions attaching themselves to `M-S-down'.
19526 See `org-ctrl-c-ctrl-c-hook' for more information.")
19527 (defvar org-metareturn-hook nil
19528 "Hook for functions attaching themselves to `M-RET'.
19529 See `org-ctrl-c-ctrl-c-hook' for more information.")
19530 (defvar org-shiftup-hook nil
19531 "Hook for functions attaching themselves to `S-up'.
19532 See `org-ctrl-c-ctrl-c-hook' for more information.")
19533 (defvar org-shiftup-final-hook nil
19534 "Hook for functions attaching themselves to `S-up'.
19535 This one runs after all other options except shift-select have been excluded.
19536 See `org-ctrl-c-ctrl-c-hook' for more information.")
19537 (defvar org-shiftdown-hook nil
19538 "Hook for functions attaching themselves to `S-down'.
19539 See `org-ctrl-c-ctrl-c-hook' for more information.")
19540 (defvar org-shiftdown-final-hook nil
19541 "Hook for functions attaching themselves to `S-down'.
19542 This one runs after all other options except shift-select have been excluded.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.")
19544 (defvar org-shiftleft-hook nil
19545 "Hook for functions attaching themselves to `S-left'.
19546 See `org-ctrl-c-ctrl-c-hook' for more information.")
19547 (defvar org-shiftleft-final-hook nil
19548 "Hook for functions attaching themselves to `S-left'.
19549 This one runs after all other options except shift-select have been excluded.
19550 See `org-ctrl-c-ctrl-c-hook' for more information.")
19551 (defvar org-shiftright-hook nil
19552 "Hook for functions attaching themselves to `S-right'.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.")
19554 (defvar org-shiftright-final-hook nil
19555 "Hook for functions attaching themselves to `S-right'.
19556 This one runs after all other options except shift-select have been excluded.
19557 See `org-ctrl-c-ctrl-c-hook' for more information.")
19559 (defun org-modifier-cursor-error ()
19560 "Throw an error, a modified cursor command was applied in wrong context."
19561 (user-error "This command is active in special context like tables, headlines or items"))
19563 (defun org-shiftselect-error ()
19564 "Throw an error because Shift-Cursor command was applied in wrong context."
19565 (if (and (boundp 'shift-select-mode) shift-select-mode)
19566 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19567 (user-error "This command works only in special context like headlines or timestamps")))
19569 (defun org-call-for-shift-select (cmd)
19570 (let ((this-command-keys-shift-translated t))
19571 (call-interactively cmd)))
19573 (defun org-shifttab (&optional arg)
19574 "Global visibility cycling or move to previous table field.
19575 Call `org-table-previous-field' within a table.
19576 When ARG is nil, cycle globally through visibility states.
19577 When ARG is a numeric prefix, show contents of this level."
19578 (interactive "P")
19579 (cond
19580 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19581 ((integerp arg)
19582 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19583 (message "Content view to level: %d" arg)
19584 (org-content (prefix-numeric-value arg2))
19585 (org-cycle-show-empty-lines t)
19586 (setq org-cycle-global-status 'overview)))
19587 (t (call-interactively 'org-global-cycle))))
19589 (defun org-shiftmetaleft ()
19590 "Promote subtree or delete table column.
19591 Calls `org-promote-subtree', `org-outdent-item-tree', or
19592 `org-table-delete-column', depending on context. See the
19593 individual commands for more information."
19594 (interactive)
19595 (cond
19596 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19597 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19598 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19599 ((if (not (org-region-active-p)) (org-at-item-p)
19600 (save-excursion (goto-char (region-beginning))
19601 (org-at-item-p)))
19602 (call-interactively 'org-outdent-item-tree))
19603 (t (org-modifier-cursor-error))))
19605 (defun org-shiftmetaright ()
19606 "Demote subtree or insert table column.
19607 Calls `org-demote-subtree', `org-indent-item-tree', or
19608 `org-table-insert-column', depending on context. See the
19609 individual commands for more information."
19610 (interactive)
19611 (cond
19612 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19613 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19614 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19615 ((if (not (org-region-active-p)) (org-at-item-p)
19616 (save-excursion (goto-char (region-beginning))
19617 (org-at-item-p)))
19618 (call-interactively 'org-indent-item-tree))
19619 (t (org-modifier-cursor-error))))
19621 (defun org-shiftmetaup (&optional _arg)
19622 "Drag the line at point up.
19623 In a table, kill the current row.
19624 On a clock timestamp, update the value of the timestamp like `S-<up>'
19625 but also adjust the previous clocked item in the clock history.
19626 Everywhere else, drag the line at point up."
19627 (interactive "P")
19628 (cond
19629 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19630 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19631 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19632 (call-interactively 'org-timestamp-up)))
19633 (t (call-interactively 'org-drag-line-backward))))
19635 (defun org-shiftmetadown (&optional _arg)
19636 "Drag the line at point down.
19637 In a table, insert an empty row at the current line.
19638 On a clock timestamp, update the value of the timestamp like `S-<down>'
19639 but also adjust the previous clocked item in the clock history.
19640 Everywhere else, drag the line at point down."
19641 (interactive "P")
19642 (cond
19643 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19644 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19645 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19646 (call-interactively 'org-timestamp-down)))
19647 (t (call-interactively 'org-drag-line-forward))))
19649 (defsubst org-hidden-tree-error ()
19650 (user-error
19651 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19653 (defun org-metaleft (&optional _arg)
19654 "Promote heading, list item at point or move table column left.
19656 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19657 depending on context. With no specific context, calls the Emacs
19658 default `backward-word'. See the individual commands for more
19659 information.
19661 This function runs the hook `org-metaleft-hook' as a first step,
19662 and returns at first non-nil value."
19663 (interactive "P")
19664 (cond
19665 ((run-hook-with-args-until-success 'org-metaleft-hook))
19666 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19667 ((org-with-limited-levels
19668 (or (org-at-heading-p)
19669 (and (org-region-active-p)
19670 (save-excursion
19671 (goto-char (region-beginning))
19672 (org-at-heading-p)))))
19673 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19674 (call-interactively 'org-do-promote))
19675 ;; At an inline task.
19676 ((org-at-heading-p)
19677 (call-interactively 'org-inlinetask-promote))
19678 ((or (org-at-item-p)
19679 (and (org-region-active-p)
19680 (save-excursion
19681 (goto-char (region-beginning))
19682 (org-at-item-p))))
19683 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19684 (call-interactively 'org-outdent-item))
19685 (t (call-interactively 'backward-word))))
19687 (defun org-metaright (&optional _arg)
19688 "Demote heading, list item at point or move table column right.
19690 In front of a drawer or a block keyword, indent it correctly.
19692 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19693 `org-indent-drawer' or `org-indent-block' depending on context.
19694 With no specific context, calls the Emacs default `forward-word'.
19695 See the individual commands for more information.
19697 This function runs the hook `org-metaright-hook' as a first step,
19698 and returns at first non-nil value."
19699 (interactive "P")
19700 (cond
19701 ((run-hook-with-args-until-success 'org-metaright-hook))
19702 ((org-at-table-p) (call-interactively 'org-table-move-column))
19703 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19704 ((org-at-block-p) (call-interactively 'org-indent-block))
19705 ((org-with-limited-levels
19706 (or (org-at-heading-p)
19707 (and (org-region-active-p)
19708 (save-excursion
19709 (goto-char (region-beginning))
19710 (org-at-heading-p)))))
19711 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19712 (call-interactively 'org-do-demote))
19713 ;; At an inline task.
19714 ((org-at-heading-p)
19715 (call-interactively 'org-inlinetask-demote))
19716 ((or (org-at-item-p)
19717 (and (org-region-active-p)
19718 (save-excursion
19719 (goto-char (region-beginning))
19720 (org-at-item-p))))
19721 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19722 (call-interactively 'org-indent-item))
19723 (t (call-interactively 'forward-word))))
19725 (defun org-check-for-hidden (what)
19726 "Check if there are hidden headlines/items in the current visual line.
19727 WHAT can be either `headlines' or `items'. If the current line is
19728 an outline or item heading and it has a folded subtree below it,
19729 this function returns t, nil otherwise."
19730 (let ((re (cond
19731 ((eq what 'headlines) org-outline-regexp-bol)
19732 ((eq what 'items) (org-item-beginning-re))
19733 (t (error "This should not happen"))))
19734 beg end)
19735 (save-excursion
19736 (catch 'exit
19737 (unless (org-region-active-p)
19738 (setq beg (point-at-bol))
19739 (beginning-of-line 2)
19740 (while (and (not (eobp)) ;; this is like `next-line'
19741 (get-char-property (1- (point)) 'invisible))
19742 (beginning-of-line 2))
19743 (setq end (point))
19744 (goto-char beg)
19745 (goto-char (point-at-eol))
19746 (setq end (max end (point)))
19747 (while (re-search-forward re end t)
19748 (when (get-char-property (match-beginning 0) 'invisible)
19749 (throw 'exit t))))
19750 nil))))
19752 (defun org-metaup (&optional _arg)
19753 "Move subtree up or move table row up.
19754 Calls `org-move-subtree-up' or `org-table-move-row' or
19755 `org-move-item-up', depending on context. See the individual commands
19756 for more information."
19757 (interactive "P")
19758 (cond
19759 ((run-hook-with-args-until-success 'org-metaup-hook))
19760 ((org-region-active-p)
19761 (let* ((a (min (region-beginning) (region-end)))
19762 (b (1- (max (region-beginning) (region-end))))
19763 (c (save-excursion (goto-char a)
19764 (move-beginning-of-line 0)))
19765 (d (save-excursion (goto-char a)
19766 (move-end-of-line 0) (point))))
19767 (transpose-regions a b c d)
19768 (goto-char c)))
19769 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19770 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19771 ((org-at-item-p) (call-interactively 'org-move-item-up))
19772 (t (org-drag-element-backward))))
19774 (defun org-metadown (&optional _arg)
19775 "Move subtree down or move table row down.
19776 Calls `org-move-subtree-down' or `org-table-move-row' or
19777 `org-move-item-down', depending on context. See the individual
19778 commands for more information."
19779 (interactive "P")
19780 (cond
19781 ((run-hook-with-args-until-success 'org-metadown-hook))
19782 ((org-region-active-p)
19783 (let* ((a (min (region-beginning) (region-end)))
19784 (b (max (region-beginning) (region-end)))
19785 (c (save-excursion (goto-char b)
19786 (move-beginning-of-line 1)))
19787 (d (save-excursion (goto-char b)
19788 (move-end-of-line 1) (1+ (point)))))
19789 (transpose-regions a b c d)
19790 (goto-char d)))
19791 ((org-at-table-p) (call-interactively 'org-table-move-row))
19792 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19793 ((org-at-item-p) (call-interactively 'org-move-item-down))
19794 (t (org-drag-element-forward))))
19796 (defun org-shiftup (&optional arg)
19797 "Increase item in timestamp or increase priority of current headline.
19798 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19799 depending on context. See the individual commands for more information."
19800 (interactive "P")
19801 (cond
19802 ((run-hook-with-args-until-success 'org-shiftup-hook))
19803 ((and org-support-shift-select (org-region-active-p))
19804 (org-call-for-shift-select 'previous-line))
19805 ((org-at-timestamp-p 'lax)
19806 (call-interactively (if org-edit-timestamp-down-means-later
19807 'org-timestamp-down 'org-timestamp-up)))
19808 ((and (not (eq org-support-shift-select 'always))
19809 org-enable-priority-commands
19810 (org-at-heading-p))
19811 (call-interactively 'org-priority-up))
19812 ((and (not org-support-shift-select) (org-at-item-p))
19813 (call-interactively 'org-previous-item))
19814 ((org-clocktable-try-shift 'up arg))
19815 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19816 (org-support-shift-select
19817 (org-call-for-shift-select 'previous-line))
19818 (t (org-shiftselect-error))))
19820 (defun org-shiftdown (&optional arg)
19821 "Decrease item in timestamp or decrease priority of current headline.
19822 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19823 depending on context. See the individual commands for more information."
19824 (interactive "P")
19825 (cond
19826 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19827 ((and org-support-shift-select (org-region-active-p))
19828 (org-call-for-shift-select 'next-line))
19829 ((org-at-timestamp-p 'lax)
19830 (call-interactively (if org-edit-timestamp-down-means-later
19831 'org-timestamp-up 'org-timestamp-down)))
19832 ((and (not (eq org-support-shift-select 'always))
19833 org-enable-priority-commands
19834 (org-at-heading-p))
19835 (call-interactively 'org-priority-down))
19836 ((and (not org-support-shift-select) (org-at-item-p))
19837 (call-interactively 'org-next-item))
19838 ((org-clocktable-try-shift 'down arg))
19839 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19840 (org-support-shift-select
19841 (org-call-for-shift-select 'next-line))
19842 (t (org-shiftselect-error))))
19844 (defun org-shiftright (&optional arg)
19845 "Cycle the thing at point or in the current line, depending on context.
19846 Depending on context, this does one of the following:
19848 - switch a timestamp at point one day into the future
19849 - on a headline, switch to the next TODO keyword.
19850 - on an item, switch entire list to the next bullet type
19851 - on a property line, switch to the next allowed value
19852 - on a clocktable definition line, move time block into the future"
19853 (interactive "P")
19854 (cond
19855 ((run-hook-with-args-until-success 'org-shiftright-hook))
19856 ((and org-support-shift-select (org-region-active-p))
19857 (org-call-for-shift-select 'forward-char))
19858 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19859 ((and (not (eq org-support-shift-select 'always))
19860 (org-at-heading-p))
19861 (let ((org-inhibit-logging
19862 (not org-treat-S-cursor-todo-selection-as-state-change))
19863 (org-inhibit-blocking
19864 (not org-treat-S-cursor-todo-selection-as-state-change)))
19865 (org-call-with-arg 'org-todo 'right)))
19866 ((or (and org-support-shift-select
19867 (not (eq org-support-shift-select 'always))
19868 (org-at-item-bullet-p))
19869 (and (not org-support-shift-select) (org-at-item-p)))
19870 (org-call-with-arg 'org-cycle-list-bullet nil))
19871 ((and (not (eq org-support-shift-select 'always))
19872 (org-at-property-p))
19873 (call-interactively 'org-property-next-allowed-value))
19874 ((org-clocktable-try-shift 'right arg))
19875 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19876 (org-support-shift-select
19877 (org-call-for-shift-select 'forward-char))
19878 (t (org-shiftselect-error))))
19880 (defun org-shiftleft (&optional arg)
19881 "Cycle the thing at point or in the current line, depending on context.
19882 Depending on context, this does one of the following:
19884 - switch a timestamp at point one day into the past
19885 - on a headline, switch to the previous TODO keyword.
19886 - on an item, switch entire list to the previous bullet type
19887 - on a property line, switch to the previous allowed value
19888 - on a clocktable definition line, move time block into the past"
19889 (interactive "P")
19890 (cond
19891 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19892 ((and org-support-shift-select (org-region-active-p))
19893 (org-call-for-shift-select 'backward-char))
19894 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19895 ((and (not (eq org-support-shift-select 'always))
19896 (org-at-heading-p))
19897 (let ((org-inhibit-logging
19898 (not org-treat-S-cursor-todo-selection-as-state-change))
19899 (org-inhibit-blocking
19900 (not org-treat-S-cursor-todo-selection-as-state-change)))
19901 (org-call-with-arg 'org-todo 'left)))
19902 ((or (and org-support-shift-select
19903 (not (eq org-support-shift-select 'always))
19904 (org-at-item-bullet-p))
19905 (and (not org-support-shift-select) (org-at-item-p)))
19906 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19907 ((and (not (eq org-support-shift-select 'always))
19908 (org-at-property-p))
19909 (call-interactively 'org-property-previous-allowed-value))
19910 ((org-clocktable-try-shift 'left arg))
19911 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19912 (org-support-shift-select
19913 (org-call-for-shift-select 'backward-char))
19914 (t (org-shiftselect-error))))
19916 (defun org-shiftcontrolright ()
19917 "Switch to next TODO set."
19918 (interactive)
19919 (cond
19920 ((and org-support-shift-select (org-region-active-p))
19921 (org-call-for-shift-select 'forward-word))
19922 ((and (not (eq org-support-shift-select 'always))
19923 (org-at-heading-p))
19924 (org-call-with-arg 'org-todo 'nextset))
19925 (org-support-shift-select
19926 (org-call-for-shift-select 'forward-word))
19927 (t (org-shiftselect-error))))
19929 (defun org-shiftcontrolleft ()
19930 "Switch to previous TODO set."
19931 (interactive)
19932 (cond
19933 ((and org-support-shift-select (org-region-active-p))
19934 (org-call-for-shift-select 'backward-word))
19935 ((and (not (eq org-support-shift-select 'always))
19936 (org-at-heading-p))
19937 (org-call-with-arg 'org-todo 'previousset))
19938 (org-support-shift-select
19939 (org-call-for-shift-select 'backward-word))
19940 (t (org-shiftselect-error))))
19942 (defun org-shiftcontrolup (&optional n)
19943 "Change timestamps synchronously up in CLOCK log lines.
19944 Optional argument N tells to change by that many units."
19945 (interactive "P")
19946 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19947 (let (org-support-shift-select)
19948 (org-clock-timestamps-up n))
19949 (user-error "Not at a clock log")))
19951 (defun org-shiftcontroldown (&optional n)
19952 "Change timestamps synchronously down in CLOCK log lines.
19953 Optional argument N tells to change by that many units."
19954 (interactive "P")
19955 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19956 (let (org-support-shift-select)
19957 (org-clock-timestamps-down n))
19958 (user-error "Not at a clock log")))
19960 (defun org-increase-number-at-point (&optional inc)
19961 "Increment the number at point.
19962 With an optional prefix numeric argument INC, increment using
19963 this numeric value."
19964 (interactive "p")
19965 (if (not (number-at-point))
19966 (user-error "Not on a number")
19967 (unless inc (setq inc 1))
19968 (let ((pos (point))
19969 (beg (skip-chars-backward "-+^/*0-9eE."))
19970 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
19971 (setq nap (buffer-substring-no-properties
19972 (+ pos beg) (+ pos beg end)))
19973 (delete-region (+ pos beg) (+ pos beg end))
19974 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
19975 (when (org-at-table-p)
19976 (org-table-align)
19977 (org-table-end-of-field 1))))
19979 (defun org-decrease-number-at-point (&optional inc)
19980 "Decrement the number at point.
19981 With an optional prefix numeric argument INC, decrement using
19982 this numeric value."
19983 (interactive "p")
19984 (org-increase-number-at-point (- (or inc 1))))
19986 (defun org-ctrl-c-ret ()
19987 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19988 (interactive)
19989 (cond
19990 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19991 (t (call-interactively 'org-insert-heading))))
19993 (defun org-find-visible ()
19994 (let ((s (point)))
19995 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19996 (get-char-property s 'invisible)))
19998 (defun org-find-invisible ()
19999 (let ((s (point)))
20000 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20001 (not (get-char-property s 'invisible))))
20004 (defun org-copy-visible (beg end)
20005 "Copy the visible parts of the region."
20006 (interactive "r")
20007 (let ((result ""))
20008 (while (/= beg end)
20009 (when (get-char-property beg 'invisible)
20010 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20011 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20012 (setq result (concat result (buffer-substring beg next)))
20013 (setq beg next)))
20014 (kill-new result)))
20016 (defun org-copy-special ()
20017 "Copy region in table or copy current subtree.
20018 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20019 context. See the individual commands for more information."
20020 (interactive)
20021 (call-interactively
20022 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20024 (defun org-cut-special ()
20025 "Cut region in table or cut current subtree.
20026 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20027 context. See the individual commands for more information."
20028 (interactive)
20029 (call-interactively
20030 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20032 (defun org-paste-special (arg)
20033 "Paste rectangular region into table, or past subtree relative to level.
20034 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20035 See the individual commands for more information."
20036 (interactive "P")
20037 (if (org-at-table-p)
20038 (org-table-paste-rectangle)
20039 (org-paste-subtree arg)))
20041 (defun org-edit-special (&optional arg)
20042 "Call a special editor for the element at point.
20043 When at a table, call the formula editor with `org-table-edit-formulas'.
20044 When in a source code block, call `org-edit-src-code'.
20045 When in a fixed-width region, call `org-edit-fixed-width-region'.
20046 When in an export block, call `org-edit-export-block'.
20047 When in a LaTeX environment, call `org-edit-latex-environment'.
20048 When at an #+INCLUDE keyword, visit the included file.
20049 When at a footnote reference, call `org-edit-footnote-reference'
20050 On a link, call `ffap' to visit the link at point.
20051 Otherwise, return a user error."
20052 (interactive "P")
20053 (let ((element (org-element-at-point)))
20054 (barf-if-buffer-read-only)
20055 (pcase (org-element-type element)
20056 (`src-block
20057 (if (not arg) (org-edit-src-code)
20058 (let* ((info (org-babel-get-src-block-info))
20059 (lang (nth 0 info))
20060 (params (nth 2 info))
20061 (session (cdr (assq :session params))))
20062 (if (not session) (org-edit-src-code)
20063 ;; At a src-block with a session and function called with
20064 ;; an ARG: switch to the buffer related to the inferior
20065 ;; process.
20066 (switch-to-buffer
20067 (funcall (intern (concat "org-babel-prep-session:" lang))
20068 session params))))))
20069 (`keyword
20070 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20071 (org-open-link-from-string
20072 (format "[[%s]]"
20073 (expand-file-name
20074 (let ((value (org-element-property :value element)))
20075 (cond ((org-file-url-p value)
20076 (user-error "The file is specified as a URL, cannot be edited"))
20077 ((not (org-string-nw-p value))
20078 (user-error "No file to edit"))
20079 ((string-match "\\`\"\\(.*?\\)\"" value)
20080 (match-string 1 value))
20081 ((string-match "\\`[^ \t\"]\\S-*" value)
20082 (match-string 0 value))
20083 (t (user-error "No valid file specified")))))))
20084 (user-error "No special environment to edit here")))
20085 (`table
20086 (if (eq (org-element-property :type element) 'table.el)
20087 (org-edit-table.el)
20088 (call-interactively 'org-table-edit-formulas)))
20089 ;; Only Org tables contain `table-row' type elements.
20090 (`table-row (call-interactively 'org-table-edit-formulas))
20091 (`example-block (org-edit-src-code))
20092 (`export-block (org-edit-export-block))
20093 (`fixed-width (org-edit-fixed-width-region))
20094 (`latex-environment (org-edit-latex-environment))
20096 ;; No notable element at point. Though, we may be at a link or
20097 ;; a footnote reference, which are objects. Thus, scan deeper.
20098 (let ((context (org-element-context element)))
20099 (pcase (org-element-type context)
20100 (`footnote-reference (org-edit-footnote-reference))
20101 (`inline-src-block (org-edit-inline-src-code))
20102 (`link (call-interactively #'ffap))
20103 (_ (user-error "No special environment to edit here"))))))))
20105 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20106 (defun org-ctrl-c-ctrl-c (&optional arg)
20107 "Set tags in headline, or update according to changed information at point.
20109 This command does many different things, depending on context:
20111 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20112 this is what we do.
20114 - If the cursor is on a statistics cookie, update it.
20116 - If the cursor is in a headline, prompt for tags and insert them
20117 into the current line, aligned to `org-tags-column'. When called
20118 with prefix arg, realign all tags in the current buffer.
20120 - If the cursor is in one of the special #+KEYWORD lines, this
20121 triggers scanning the buffer for these lines and updating the
20122 information.
20124 - If the cursor is inside a table, realign the table. This command
20125 works even if the automatic table editor has been turned off.
20127 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20128 the entire table.
20130 - If the cursor is at a footnote reference or definition, jump to
20131 the corresponding definition or references, respectively.
20133 - If the cursor is a the beginning of a dynamic block, update it.
20135 - If the current buffer is a capture buffer, close note and file it.
20137 - If the cursor is on a <<<target>>>, update radio targets and
20138 corresponding links in this buffer.
20140 - If the cursor is on a numbered item in a plain list, renumber the
20141 ordered list.
20143 - If the cursor is on a checkbox, toggle it.
20145 - If the cursor is on a code block, evaluate it. The variable
20146 `org-confirm-babel-evaluate' can be used to control prompting
20147 before code block evaluation, by default every code block
20148 evaluation requires confirmation. Code block evaluation can be
20149 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20150 (interactive "P")
20151 (cond
20152 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20153 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20154 (org-remove-occur-highlights)
20155 (message "Temporary highlights/overlays removed from current buffer"))
20156 ((and (local-variable-p 'org-finish-function)
20157 (fboundp org-finish-function))
20158 (funcall org-finish-function))
20159 ((org-babel-hash-at-point))
20160 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20162 (let* ((context
20163 (org-element-lineage
20164 (org-element-context)
20165 ;; Limit to supported contexts.
20166 '(babel-call clock dynamic-block footnote-definition
20167 footnote-reference inline-babel-call inline-src-block
20168 inlinetask item keyword node-property paragraph
20169 plain-list planning property-drawer radio-target
20170 src-block statistics-cookie table table-cell table-row
20171 timestamp)
20173 (type (org-element-type context)))
20174 ;; For convenience: at the first line of a paragraph on the same
20175 ;; line as an item, apply function on that item instead.
20176 (when (eq type 'paragraph)
20177 (let ((parent (org-element-property :parent context)))
20178 (when (and (eq (org-element-type parent) 'item)
20179 (= (line-beginning-position)
20180 (org-element-property :begin parent)))
20181 (setq context parent)
20182 (setq type 'item))))
20183 ;; Act according to type of element or object at point.
20185 ;; Do nothing on a blank line, except if it is contained in
20186 ;; a src block. Hence, we first check if point is in such
20187 ;; a block and then if it is at a blank line.
20188 (pcase type
20189 ((or `inline-src-block `src-block)
20190 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20191 (org-babel-eval-wipe-error-buffer)
20192 (org-babel-execute-src-block
20193 current-prefix-arg (org-babel-get-src-block-info nil context))))
20194 ((guard (org-match-line "[ \t]*$"))
20195 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20196 (user-error
20197 (substitute-command-keys
20198 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20199 ((or `babel-call `inline-babel-call)
20200 (let ((info (org-babel-lob-get-info context)))
20201 (when info (org-babel-execute-src-block nil info))))
20202 (`clock (org-clock-update-time-maybe))
20203 (`dynamic-block
20204 (save-excursion
20205 (goto-char (org-element-property :post-affiliated context))
20206 (org-update-dblock)))
20207 (`footnote-definition
20208 (goto-char (org-element-property :post-affiliated context))
20209 (call-interactively 'org-footnote-action))
20210 (`footnote-reference (call-interactively #'org-footnote-action))
20211 ((or `headline `inlinetask)
20212 (save-excursion (goto-char (org-element-property :begin context))
20213 (call-interactively #'org-set-tags)))
20214 (`item
20215 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20216 ;; unconditionally, whereas `C-u' will toggle its presence.
20217 ;; Without a universal argument, if the item has a checkbox,
20218 ;; toggle it. Otherwise repair the list.
20219 (let* ((box (org-element-property :checkbox context))
20220 (struct (org-element-property :structure context))
20221 (old-struct (copy-tree struct))
20222 (parents (org-list-parents-alist struct))
20223 (prevs (org-list-prevs-alist struct))
20224 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20225 (org-list-set-checkbox
20226 (org-element-property :begin context) struct
20227 (cond ((equal arg '(16)) "[-]")
20228 ((and (not box) (equal arg '(4))) "[ ]")
20229 ((or (not box) (equal arg '(4))) nil)
20230 ((eq box 'on) "[ ]")
20231 (t "[X]")))
20232 ;; Mimic `org-list-write-struct' but with grabbing a return
20233 ;; value from `org-list-struct-fix-box'.
20234 (org-list-struct-fix-ind struct parents 2)
20235 (org-list-struct-fix-item-end struct)
20236 (org-list-struct-fix-bul struct prevs)
20237 (org-list-struct-fix-ind struct parents)
20238 (let ((block-item
20239 (org-list-struct-fix-box struct parents prevs orderedp)))
20240 (if (and box (equal struct old-struct))
20241 (if (equal arg '(16))
20242 (message "Checkboxes already reset")
20243 (user-error "Cannot toggle this checkbox: %s"
20244 (if (eq box 'on)
20245 "all subitems checked"
20246 "unchecked subitems")))
20247 (org-list-struct-apply-struct struct old-struct)
20248 (org-update-checkbox-count-maybe))
20249 (when block-item
20250 (message "Checkboxes were removed due to empty box at line %d"
20251 (org-current-line block-item))))))
20252 (`keyword
20253 (let ((org-inhibit-startup-visibility-stuff t)
20254 (org-startup-align-all-tables nil))
20255 (when (boundp 'org-table-coordinate-overlays)
20256 (mapc #'delete-overlay org-table-coordinate-overlays)
20257 (setq org-table-coordinate-overlays nil))
20258 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20259 (message "Local setup has been refreshed"))
20260 (`plain-list
20261 ;; At a plain list, with a double C-u argument, set
20262 ;; checkboxes of each item to "[-]", whereas a single one
20263 ;; will toggle their presence according to the state of the
20264 ;; first item in the list. Without an argument, repair the
20265 ;; list.
20266 (let* ((begin (org-element-property :contents-begin context))
20267 (struct (org-element-property :structure context))
20268 (old-struct (copy-tree struct))
20269 (first-box (save-excursion
20270 (goto-char begin)
20271 (looking-at org-list-full-item-re)
20272 (match-string-no-properties 3)))
20273 (new-box (cond ((equal arg '(16)) "[-]")
20274 ((equal arg '(4)) (unless first-box "[ ]"))
20275 ((equal first-box "[X]") "[ ]")
20276 (t "[X]"))))
20277 (cond
20278 (arg
20279 (dolist (pos
20280 (org-list-get-all-items
20281 begin struct (org-list-prevs-alist struct)))
20282 (org-list-set-checkbox pos struct new-box)))
20283 ((and first-box (eq (point) begin))
20284 ;; For convenience, when point is at bol on the first
20285 ;; item of the list and no argument is provided, simply
20286 ;; toggle checkbox of that item, if any.
20287 (org-list-set-checkbox begin struct new-box)))
20288 (org-list-write-struct
20289 struct (org-list-parents-alist struct) old-struct)
20290 (org-update-checkbox-count-maybe)))
20291 ((or `property-drawer `node-property)
20292 (call-interactively #'org-property-action))
20293 (`radio-target
20294 (call-interactively #'org-update-radio-target-regexp))
20295 (`statistics-cookie
20296 (call-interactively #'org-update-statistics-cookies))
20297 ((or `table `table-cell `table-row)
20298 ;; At a table, recalculate every field and align it. Also
20299 ;; send the table if necessary. If the table has
20300 ;; a `table.el' type, just give up. At a table row or cell,
20301 ;; maybe recalculate line but always align table.
20302 (if (eq (org-element-property :type context) 'table.el)
20303 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20304 Use `\\[org-edit-special]' to edit table.el tables"))
20305 (if (or (eq type 'table)
20306 ;; Check if point is at a TBLFM line.
20307 (and (eq type 'table-row)
20308 (= (point) (org-element-property :end context))))
20309 (save-excursion
20310 (if (org-at-TBLFM-p)
20311 (progn (require 'org-table)
20312 (org-table-calc-current-TBLFM))
20313 (goto-char (org-element-property :contents-begin context))
20314 (org-call-with-arg 'org-table-recalculate (or arg t))
20315 (orgtbl-send-table 'maybe)))
20316 (org-table-maybe-eval-formula)
20317 (cond (arg (call-interactively #'org-table-recalculate))
20318 ((org-table-maybe-recalculate-line))
20319 (t (org-table-align))))))
20320 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20321 (org-timestamp-change 0 'day))
20322 ((and `nil (guard (org-at-heading-p)))
20323 ;; When point is on an unsupported object type, we can miss
20324 ;; the fact that it also is at a heading. Handle it here.
20325 (call-interactively #'org-set-tags))
20326 ((guard
20327 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20329 (user-error
20330 (substitute-command-keys
20331 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20333 (defun org-mode-restart ()
20334 (interactive)
20335 (let ((indent-status (bound-and-true-p org-indent-mode)))
20336 (funcall major-mode)
20337 (hack-local-variables)
20338 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20339 (org-indent-mode -1))
20340 (org-reset-file-cache))
20341 (message "%s restarted" major-mode))
20343 (defun org-kill-note-or-show-branches ()
20344 "Abort storing current note, or call `outline-show-branches'."
20345 (interactive)
20346 (if (not org-finish-function)
20347 (save-excursion
20348 (save-restriction
20349 (org-narrow-to-subtree)
20350 (org-flag-subtree t)
20351 (call-interactively 'outline-show-branches)
20352 (org-hide-archived-subtrees (point-min) (point-max))))
20353 (let ((org-note-abort t))
20354 (funcall org-finish-function))))
20356 (defun org-delete-indentation (&optional arg)
20357 "Join current line to previous and fix whitespace at join.
20359 If previous line is a headline add to headline title. Otherwise
20360 the function calls `delete-indentation'.
20362 With a non-nil optional argument, join it to the following one."
20363 (interactive "*P")
20364 (if (save-excursion
20365 (beginning-of-line (if arg 1 0))
20366 (let ((case-fold-search nil))
20367 (looking-at org-complex-heading-regexp)))
20368 ;; At headline.
20369 (let ((tags-column (when (match-beginning 5)
20370 (save-excursion (goto-char (match-beginning 5))
20371 (current-column))))
20372 (string (concat " " (progn (when arg (forward-line 1))
20373 (org-trim (delete-and-extract-region
20374 (line-beginning-position)
20375 (line-end-position)))))))
20376 (unless (bobp) (delete-region (point) (1- (point))))
20377 (goto-char (or (match-end 4)
20378 (match-beginning 5)
20379 (match-end 0)))
20380 (skip-chars-backward " \t")
20381 (save-excursion (insert string))
20382 ;; Adjust alignment of tags.
20383 (cond
20384 ((not tags-column)) ;no tags
20385 (org-auto-align-tags (org-set-tags nil t))
20386 (t (org--align-tags-here tags-column)))) ;preserve tags column
20387 (delete-indentation arg)))
20389 (defun org-open-line (n)
20390 "Insert a new row in tables, call `open-line' elsewhere.
20391 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20392 As a special case, when a document starts with a table, allow to
20393 call `open-line' on the very first character."
20394 (interactive "*p")
20395 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20396 (org-table-insert-row)
20397 (open-line n)))
20399 (defun org-return (&optional indent)
20400 "Goto next table row or insert a newline.
20402 Calls `org-table-next-row' or `newline', depending on context.
20404 When optional INDENT argument is non-nil, call
20405 `newline-and-indent' instead of `newline'.
20407 When `org-return-follows-link' is non-nil and point is on
20408 a timestamp or a link, call `org-open-at-point'. However, it
20409 will not happen if point is in a table or on a \"dead\"
20410 object (e.g., within a comment). In these case, you need to use
20411 `org-open-at-point' directly."
20412 (interactive)
20413 (let ((context (if org-return-follows-link (org-element-context)
20414 (org-element-at-point))))
20415 (cond
20416 ;; In a table, call `org-table-next-row'. However, before first
20417 ;; column or after last one, split the table.
20418 ((or (and (eq (org-element-type context) 'table)
20419 (>= (point) (org-element-property :contents-begin context))
20420 (< (point) (org-element-property :contents-end context)))
20421 (org-element-lineage context '(table-row table-cell) t))
20422 (if (or (looking-at-p "[ \t]*$")
20423 (save-excursion (skip-chars-backward " \t") (bolp)))
20424 (insert "\n")
20425 (org-table-justify-field-maybe)
20426 (call-interactively #'org-table-next-row)))
20427 ;; On a link or a timestamp, call `org-open-at-point' if
20428 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20429 ;; locations, e.g., in a comment, as `org-open-at-point'.
20430 ((and org-return-follows-link
20431 (or (org-in-regexp org-ts-regexp-both nil t)
20432 (org-in-regexp org-tsr-regexp-both nil t)
20433 (org-in-regexp org-any-link-re nil t)))
20434 (call-interactively #'org-open-at-point))
20435 ;; Insert newline in heading, but preserve tags.
20436 ((and (not (bolp))
20437 (save-excursion (beginning-of-line)
20438 (let ((case-fold-search nil))
20439 (looking-at org-complex-heading-regexp))))
20440 ;; At headline. Split line. However, if point is on keyword,
20441 ;; priority cookie or tags, do not break any of them: add
20442 ;; a newline after the headline instead.
20443 (let ((tags-column (and (match-beginning 5)
20444 (save-excursion (goto-char (match-beginning 5))
20445 (current-column))))
20446 (string
20447 (when (and (match-end 4) (org-point-in-group (point) 4))
20448 (delete-and-extract-region (point) (match-end 4)))))
20449 ;; Adjust tag alignment.
20450 (cond
20451 ((not (and tags-column string)))
20452 (org-auto-align-tags (org-set-tags nil t))
20453 (t (org--align-tags-here tags-column))) ;preserve tags column
20454 (end-of-line)
20455 (org-show-entry)
20456 (if indent (newline-and-indent) (newline))
20457 (when string (save-excursion (insert (org-trim string))))))
20458 ;; In a list, make sure indenting keeps trailing text within.
20459 ((and indent
20460 (not (eolp))
20461 (org-element-lineage context '(item)))
20462 (let ((trailing-data
20463 (delete-and-extract-region (point) (line-end-position))))
20464 (newline-and-indent)
20465 (save-excursion (insert trailing-data))))
20466 (t (if indent (newline-and-indent) (newline))))))
20468 (defun org-return-indent ()
20469 "Goto next table row or insert a newline and indent.
20470 Calls `org-table-next-row' or `newline-and-indent', depending on
20471 context. See the individual commands for more information."
20472 (interactive)
20473 (org-return t))
20475 (defun org-ctrl-c-tab (&optional _arg)
20476 "Toggle columns width in a table, or show children.
20477 Call `org-table-toggle-column-width' if point is in a table.
20478 Otherwise, call `org-show-children'."
20479 (interactive "p")
20480 (call-interactively
20481 (if (org-at-table-p) #'org-table-toggle-column-width
20482 #'org-show-children)))
20484 (defun org-ctrl-c-star ()
20485 "Compute table, or change heading status of lines.
20486 Calls `org-table-recalculate' or `org-toggle-heading',
20487 depending on context."
20488 (interactive)
20489 (cond
20490 ((org-at-table-p)
20491 (call-interactively 'org-table-recalculate))
20493 ;; Convert all lines in region to list items
20494 (call-interactively 'org-toggle-heading))))
20496 (defun org-ctrl-c-minus ()
20497 "Insert separator line in table or modify bullet status of line.
20498 Also turns a plain line or a region of lines into list items.
20499 Calls `org-table-insert-hline', `org-toggle-item', or
20500 `org-cycle-list-bullet', depending on context."
20501 (interactive)
20502 (cond
20503 ((org-at-table-p)
20504 (call-interactively 'org-table-insert-hline))
20505 ((org-region-active-p)
20506 (call-interactively 'org-toggle-item))
20507 ((org-in-item-p)
20508 (call-interactively 'org-cycle-list-bullet))
20510 (call-interactively 'org-toggle-item))))
20512 (defun org-toggle-heading (&optional nstars)
20513 "Convert headings to normal text, or items or text to headings.
20514 If there is no active region, only convert the current line.
20516 With a `\\[universal-argument]' prefix, convert the whole list at
20517 point into heading.
20519 In a region:
20521 - If the first non blank line is a headline, remove the stars
20522 from all headlines in the region.
20524 - If it is a normal line, turn each and every normal line (i.e.,
20525 not an heading or an item) in the region into headings. If you
20526 want to convert only the first line of this region, use one
20527 universal prefix argument.
20529 - If it is a plain list item, turn all plain list items into headings.
20531 When converting a line into a heading, the number of stars is chosen
20532 such that the lines become children of the current entry. However,
20533 when a numeric prefix argument is given, its value determines the
20534 number of stars to add."
20535 (interactive "P")
20536 (let ((skip-blanks
20537 (function
20538 ;; Return beginning of first non-blank line, starting from
20539 ;; line at POS.
20540 (lambda (pos)
20541 (save-excursion
20542 (goto-char pos)
20543 (while (org-at-comment-p) (forward-line))
20544 (skip-chars-forward " \r\t\n")
20545 (point-at-bol)))))
20546 beg end toggled)
20547 ;; Determine boundaries of changes. If a universal prefix has
20548 ;; been given, put the list in a region. If region ends at a bol,
20549 ;; do not consider the last line to be in the region.
20551 (when (and current-prefix-arg (org-at-item-p))
20552 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20553 (org-mark-element))
20555 (if (org-region-active-p)
20556 (setq beg (funcall skip-blanks (region-beginning))
20557 end (copy-marker (save-excursion
20558 (goto-char (region-end))
20559 (if (bolp) (point) (point-at-eol)))))
20560 (setq beg (funcall skip-blanks (point-at-bol))
20561 end (copy-marker (point-at-eol))))
20562 ;; Ensure inline tasks don't count as headings.
20563 (org-with-limited-levels
20564 (save-excursion
20565 (goto-char beg)
20566 (cond
20567 ;; Case 1. Started at an heading: de-star headings.
20568 ((org-at-heading-p)
20569 (while (< (point) end)
20570 (when (org-at-heading-p t)
20571 (looking-at org-outline-regexp) (replace-match "")
20572 (setq toggled t))
20573 (forward-line)))
20574 ;; Case 2. Started at an item: change items into headlines.
20575 ;; One star will be added by `org-list-to-subtree'.
20576 ((org-at-item-p)
20577 (while (< (point) end)
20578 (when (org-at-item-p)
20579 ;; Pay attention to cases when region ends before list.
20580 (let* ((struct (org-list-struct))
20581 (list-end
20582 (min (org-list-get-bottom-point struct) (1+ end))))
20583 (save-restriction
20584 (narrow-to-region (point) list-end)
20585 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20586 (setq toggled t))
20587 (forward-line)))
20588 ;; Case 3. Started at normal text: make every line an heading,
20589 ;; skipping headlines and items.
20590 (t (let* ((stars
20591 (make-string
20592 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20593 (add-stars
20594 (cond (nstars "") ; stars from prefix only
20595 ((equal stars "") "*") ; before first heading
20596 (org-odd-levels-only "**") ; inside heading, odd
20597 (t "*"))) ; inside heading, oddeven
20598 (rpl (concat stars add-stars " "))
20599 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20600 (while (< (point) (if (equal nstars '(4)) lend end))
20601 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20602 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20603 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20604 (forward-line)))))))
20605 (unless toggled (message "Cannot toggle heading from here"))))
20607 (defun org-meta-return (&optional arg)
20608 "Insert a new heading or wrap a region in a table.
20609 Calls `org-insert-heading', `org-insert-item' or
20610 `org-table-wrap-region', depending on context. When called with
20611 an argument, unconditionally call `org-insert-heading'."
20612 (interactive "P")
20613 (org-check-before-invisible-edit 'insert)
20614 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20615 (call-interactively (cond (arg #'org-insert-heading)
20616 ((org-at-table-p) #'org-table-wrap-region)
20617 ((org-in-item-p) #'org-insert-item)
20618 (t #'org-insert-heading)))))
20620 ;;; Menu entries
20622 (defsubst org-in-subtree-not-table-p ()
20623 "Are we in a subtree and not in a table?"
20624 (and (not (org-before-first-heading-p))
20625 (not (org-at-table-p))))
20627 ;; Define the Org mode menus
20628 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20629 '("Tbl"
20630 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20631 ["Next Field" org-cycle (org-at-table-p)]
20632 ["Previous Field" org-shifttab (org-at-table-p)]
20633 ["Next Row" org-return (org-at-table-p)]
20634 "--"
20635 ["Blank Field" org-table-blank-field (org-at-table-p)]
20636 ["Edit Field" org-table-edit-field (org-at-table-p)]
20637 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20638 "--"
20639 ("Column"
20640 ["Move Column Left" org-metaleft (org-at-table-p)]
20641 ["Move Column Right" org-metaright (org-at-table-p)]
20642 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20643 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20644 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20645 ("Row"
20646 ["Move Row Up" org-metaup (org-at-table-p)]
20647 ["Move Row Down" org-metadown (org-at-table-p)]
20648 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20649 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20650 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20651 "--"
20652 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20653 ("Rectangle"
20654 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20655 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20656 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20657 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20658 "--"
20659 ("Calculate"
20660 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20661 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20662 ["Edit Formulas" org-edit-special (org-at-table-p)]
20663 "--"
20664 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20665 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20666 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20667 "--"
20668 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20669 "--"
20670 ["Sum Column/Rectangle" org-table-sum
20671 (or (org-at-table-p) (org-region-active-p))]
20672 ["Which Column?" org-table-current-column (org-at-table-p)])
20673 ["Debug Formulas"
20674 org-table-toggle-formula-debugger
20675 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20676 ["Show Col/Row Numbers"
20677 org-table-toggle-coordinate-overlays
20678 :style toggle
20679 :selected (bound-and-true-p org-table-overlay-coordinates)]
20680 "--"
20681 ["Create" org-table-create (not (org-at-table-p))]
20682 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20683 ["Import from File" org-table-import (not (org-at-table-p))]
20684 ["Export to File" org-table-export (org-at-table-p)]
20685 "--"
20686 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20687 "--"
20688 ("Plot"
20689 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20690 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20692 (easy-menu-define org-org-menu org-mode-map "Org menu"
20693 '("Org"
20694 ("Show/Hide"
20695 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20696 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20697 ["Sparse Tree..." org-sparse-tree t]
20698 ["Reveal Context" org-reveal t]
20699 ["Show All" org-show-all t]
20700 "--"
20701 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20702 "--"
20703 ["New Heading" org-insert-heading t]
20704 ("Navigate Headings"
20705 ["Up" outline-up-heading t]
20706 ["Next" outline-next-visible-heading t]
20707 ["Previous" outline-previous-visible-heading t]
20708 ["Next Same Level" outline-forward-same-level t]
20709 ["Previous Same Level" outline-backward-same-level t]
20710 "--"
20711 ["Jump" org-goto t])
20712 ("Edit Structure"
20713 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20714 "--"
20715 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20716 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20717 "--"
20718 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20719 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20720 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20721 "--"
20722 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20723 "--"
20724 ["Copy visible text" org-copy-visible t]
20725 "--"
20726 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20727 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20728 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20729 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20730 "--"
20731 ["Sort Region/Children" org-sort t]
20732 "--"
20733 ["Convert to odd levels" org-convert-to-odd-levels t]
20734 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20735 ("Editing"
20736 ["Emphasis..." org-emphasize t]
20737 ["Edit Source Example" org-edit-special t]
20738 "--"
20739 ["Footnote new/jump" org-footnote-action t]
20740 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20741 ("Archive"
20742 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20743 "--"
20744 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20745 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20746 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20748 "--"
20749 ("Hyperlinks"
20750 ["Store Link (Global)" org-store-link t]
20751 ["Find existing link to here" org-occur-link-in-agenda-files t]
20752 ["Insert Link" org-insert-link t]
20753 ["Follow Link" org-open-at-point t]
20754 "--"
20755 ["Next link" org-next-link t]
20756 ["Previous link" org-previous-link t]
20757 "--"
20758 ["Descriptive Links"
20759 org-toggle-link-display
20760 :style radio
20761 :selected org-descriptive-links
20763 ["Literal Links"
20764 org-toggle-link-display
20765 :style radio
20766 :selected (not org-descriptive-links)])
20767 "--"
20768 ("TODO Lists"
20769 ["TODO/DONE/-" org-todo t]
20770 ("Select keyword"
20771 ["Next keyword" org-shiftright (org-at-heading-p)]
20772 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20773 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20774 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20775 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20776 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20777 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20778 "--"
20779 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20780 :selected org-enforce-todo-dependencies :style toggle :active t]
20781 "Settings for tree at point"
20782 ["Do Children sequentially" org-toggle-ordered-property :style radio
20783 :selected (org-entry-get nil "ORDERED")
20784 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20785 ["Do Children parallel" org-toggle-ordered-property :style radio
20786 :selected (not (org-entry-get nil "ORDERED"))
20787 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20788 "--"
20789 ["Set Priority" org-priority t]
20790 ["Priority Up" org-shiftup t]
20791 ["Priority Down" org-shiftdown t]
20792 "--"
20793 ["Get news from all feeds" org-feed-update-all t]
20794 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20795 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20796 ("TAGS and Properties"
20797 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20798 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20799 "--"
20800 ["Set property" org-set-property (not (org-before-first-heading-p))]
20801 ["Column view of properties" org-columns t]
20802 ["Insert Column View DBlock" org-columns-insert-dblock t])
20803 ("Dates and Scheduling"
20804 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20805 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20806 ("Change Date"
20807 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20808 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20809 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20810 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20811 ["Compute Time Range" org-evaluate-time-range t]
20812 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20813 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20814 "--"
20815 ["Custom time format" org-toggle-time-stamp-overlays
20816 :style radio :selected org-display-custom-times]
20817 "--"
20818 ["Goto Calendar" org-goto-calendar t]
20819 ["Date from Calendar" org-date-from-calendar t]
20820 "--"
20821 ["Start/Restart Timer" org-timer-start t]
20822 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20823 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20824 ["Insert Timer String" org-timer t]
20825 ["Insert Timer Item" org-timer-item t])
20826 ("Logging work"
20827 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20828 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20829 ["Clock out" org-clock-out t]
20830 ["Clock cancel" org-clock-cancel t]
20831 "--"
20832 ["Mark as default task" org-clock-mark-default-task t]
20833 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20834 ["Goto running clock" org-clock-goto t]
20835 "--"
20836 ["Display times" org-clock-display t]
20837 ["Create clock table" org-clock-report t]
20838 "--"
20839 ["Record DONE time"
20840 (progn (setq org-log-done (not org-log-done))
20841 (message "Switching to %s will %s record a timestamp"
20842 (car org-done-keywords)
20843 (if org-log-done "automatically" "not")))
20844 :style toggle :selected org-log-done])
20845 "--"
20846 ["Agenda Command..." org-agenda t]
20847 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20848 ("File List for Agenda")
20849 ("Special views current file"
20850 ["TODO Tree" org-show-todo-tree t]
20851 ["Check Deadlines" org-check-deadlines t]
20852 ["Tags/Property tree" org-match-sparse-tree t])
20853 "--"
20854 ["Export/Publish..." org-export-dispatch t]
20855 ("LaTeX"
20856 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20857 :style toggle :selected org-cdlatex-mode]
20858 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20859 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20860 ["Modify math symbol" org-cdlatex-math-modify
20861 (org-inside-LaTeX-fragment-p)]
20862 ["Insert citation" org-reftex-citation t])
20863 "--"
20864 ("MobileOrg"
20865 ["Push Files and Views" org-mobile-push t]
20866 ["Get Captured and Flagged" org-mobile-pull t]
20867 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20868 "--"
20869 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20870 "--"
20871 ("Documentation"
20872 ["Show Version" org-version t]
20873 ["Info Documentation" org-info t])
20874 ("Customize"
20875 ["Browse Org Group" org-customize t]
20876 "--"
20877 ["Expand This Menu" org-create-customize-menu
20878 (fboundp 'customize-menu-create)])
20879 ["Send bug report" org-submit-bug-report t]
20880 "--"
20881 ("Refresh/Reload"
20882 ["Refresh setup current buffer" org-mode-restart t]
20883 ["Reload Org (after update)" org-reload t]
20884 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20887 (defun org-info (&optional node)
20888 "Read documentation for Org in the info system.
20889 With optional NODE, go directly to that node."
20890 (interactive)
20891 (info (format "(org)%s" (or node ""))))
20893 ;;;###autoload
20894 (defun org-submit-bug-report ()
20895 "Submit a bug report on Org via mail.
20897 Don't hesitate to report any problems or inaccurate documentation.
20899 If you don't have setup sending mail from (X)Emacs, please copy the
20900 output buffer into your mail program, as it gives us important
20901 information about your Org version and configuration."
20902 (interactive)
20903 (require 'reporter)
20904 (defvar reporter-prompt-for-summary-p)
20905 (org-load-modules-maybe)
20906 (org-require-autoloaded-modules)
20907 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20908 (reporter-submit-bug-report
20909 "emacs-orgmode@gnu.org"
20910 (org-version nil 'full)
20911 (let (list)
20912 (save-window-excursion
20913 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20914 (delete-other-windows)
20915 (erase-buffer)
20916 (insert "You are about to submit a bug report to the Org mailing list.
20918 We would like to add your full Org and Outline configuration to the
20919 bug report. This greatly simplifies the work of the maintainer and
20920 other experts on the mailing list.
20922 HOWEVER, some variables you have customized may contain private
20923 information. The names of customers, colleagues, or friends, might
20924 appear in the form of file names, tags, todo states, or search strings.
20925 If you answer yes to the prompt, you might want to check and remove
20926 such private information before sending the email.")
20927 (add-text-properties (point-min) (point-max) '(face org-warning))
20928 (when (yes-or-no-p "Include your Org configuration ")
20929 (mapatoms
20930 (lambda (v)
20931 (and (boundp v)
20932 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20933 (or (and (symbol-value v)
20934 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20935 (and
20936 (get v 'custom-type) (get v 'standard-value)
20937 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20938 (push v list)))))
20939 (kill-buffer (get-buffer "*Warn about privacy*"))
20940 list))
20941 nil nil
20942 "Remember to cover the basics, that is, what you expected to happen and
20943 what in fact did happen. You don't know how to make a good report? See
20945 https://orgmode.org/manual/Feedback.html#Feedback
20947 Your bug report will be posted to the Org mailing list.
20948 ------------------------------------------------------------------------")
20949 (save-excursion
20950 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20951 (replace-match "\\1Bug: \\3 [\\2]")))))
20954 (defun org-install-agenda-files-menu ()
20955 (let ((bl (buffer-list)))
20956 (save-excursion
20957 (while bl
20958 (set-buffer (pop bl))
20959 (when (derived-mode-p 'org-mode) (setq bl nil)))
20960 (when (derived-mode-p 'org-mode)
20961 (easy-menu-change
20962 '("Org") "File List for Agenda"
20963 (append
20964 (list
20965 ["Edit File List" (org-edit-agenda-file-list) t]
20966 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20967 ["Remove Current File from List" org-remove-file t]
20968 ["Cycle through agenda files" org-cycle-agenda-files t]
20969 ["Occur in all agenda files" org-occur-in-agenda-files t]
20970 "--")
20971 (mapcar 'org-file-menu-entry
20972 ;; Prevent initialization from failing.
20973 (ignore-errors (org-agenda-files t)))))))))
20975 ;;;; Documentation
20977 (defun org-require-autoloaded-modules ()
20978 (interactive)
20979 (mapc #'require
20980 '(org-agenda org-archive org-attach org-clock org-colview org-id
20981 org-table org-timer)))
20983 ;;;###autoload
20984 (defun org-reload (&optional uncompiled)
20985 "Reload all Org Lisp files.
20986 With prefix arg UNCOMPILED, load the uncompiled versions."
20987 (interactive "P")
20988 (require 'loadhist)
20989 (let* ((org-dir (org-find-library-dir "org"))
20990 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20991 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20992 (remove-re (format "\\`%s\\'"
20993 (regexp-opt '("org" "org-loaddefs" "org-version"))))
20994 (feats (delete-dups
20995 (mapcar 'file-name-sans-extension
20996 (mapcar 'file-name-nondirectory
20997 (delq nil
20998 (mapcar 'feature-file
20999 features))))))
21000 (lfeat (append
21001 (sort
21002 (setq feats
21003 (delq nil (mapcar
21004 (lambda (f)
21005 (if (and (string-match feature-re f)
21006 (not (string-match remove-re f)))
21007 f nil))
21008 feats)))
21009 'string-lessp)
21010 (list "org-version" "org")))
21011 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21012 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21013 load-uncore load-misses)
21014 (setq load-misses
21015 (delq 't
21016 (mapcar (lambda (f)
21017 (or (org-load-noerror-mustsuffix (concat org-dir f))
21018 (and (string= org-dir contrib-dir)
21019 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21020 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21021 (add-to-list 'load-uncore f 'append)
21024 lfeat)))
21025 (when load-uncore
21026 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21027 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21028 (if load-misses
21029 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21030 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21031 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21033 ;;;###autoload
21034 (defun org-customize ()
21035 "Call the customize function with org as argument."
21036 (interactive)
21037 (org-load-modules-maybe)
21038 (org-require-autoloaded-modules)
21039 (customize-browse 'org))
21041 (defun org-create-customize-menu ()
21042 "Create a full customization menu for Org mode, insert it into the menu."
21043 (interactive)
21044 (org-load-modules-maybe)
21045 (org-require-autoloaded-modules)
21046 (if (fboundp 'customize-menu-create)
21047 (progn
21048 (easy-menu-change
21049 '("Org") "Customize"
21050 `(["Browse Org group" org-customize t]
21051 "--"
21052 ,(customize-menu-create 'org)
21053 ["Set" Custom-set t]
21054 ["Save" Custom-save t]
21055 ["Reset to Current" Custom-reset-current t]
21056 ["Reset to Saved" Custom-reset-saved t]
21057 ["Reset to Standard Settings" Custom-reset-standard t]))
21058 (message "\"Org\"-menu now contains full customization menu"))
21059 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21061 ;;;; Miscellaneous stuff
21063 ;;; Generally useful functions
21065 (defun org-link-display-format (s)
21066 "Replace links in string S with their description.
21067 If there is no description, use the link target."
21068 (save-match-data
21069 (replace-regexp-in-string
21070 org-bracket-link-analytic-regexp
21071 (lambda (m)
21072 (if (match-end 5) (match-string 5 m)
21073 (concat (match-string 1 m) (match-string 3 m))))
21074 s nil t)))
21076 (defun org-toggle-link-display ()
21077 "Toggle the literal or descriptive display of links."
21078 (interactive)
21079 (if org-descriptive-links
21080 (progn (org-remove-from-invisibility-spec '(org-link))
21081 (org-restart-font-lock)
21082 (setq org-descriptive-links nil))
21083 (progn (add-to-invisibility-spec '(org-link))
21084 (org-restart-font-lock)
21085 (setq org-descriptive-links t))))
21087 (defun org-in-clocktable-p ()
21088 "Check if the cursor is in a clocktable."
21089 (let ((pos (point)) start)
21090 (save-excursion
21091 (end-of-line 1)
21092 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21093 (setq start (match-beginning 0))
21094 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21095 (>= (match-end 0) pos)
21096 start))))
21098 (defun org-in-verbatim-emphasis ()
21099 (save-match-data
21100 (and (org-in-regexp org-verbatim-re 2)
21101 (>= (point) (match-beginning 3))
21102 (<= (point) (match-end 4)))))
21104 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21105 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21106 (if (and marker (marker-buffer marker)
21107 (buffer-live-p (marker-buffer marker)))
21108 (progn
21109 (pop-to-buffer-same-window (marker-buffer marker))
21110 (when (or (> marker (point-max)) (< marker (point-min)))
21111 (widen))
21112 (goto-char marker)
21113 (org-show-context 'org-goto))
21114 (if bookmark
21115 (bookmark-jump bookmark)
21116 (error "Cannot find location"))))
21118 (defun org-quote-csv-field (s)
21119 "Quote field for inclusion in CSV material."
21120 (if (string-match "[\",]" s)
21121 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21124 (defun org-force-self-insert (N)
21125 "Needed to enforce self-insert under remapping."
21126 (interactive "p")
21127 (self-insert-command N))
21129 (defun org-fill-template (template alist)
21130 "Find each %key of ALIST in TEMPLATE and replace it."
21131 (let ((case-fold-search nil))
21132 (dolist (entry (sort (copy-sequence alist)
21133 (lambda (a b) (< (length (car a)) (length (car b))))))
21134 (setq template
21135 (replace-regexp-in-string
21136 (concat "%" (regexp-quote (car entry)))
21137 (or (cdr entry) "") template t t)))
21138 template))
21140 (defun org-quote-vert (s)
21141 "Replace \"|\" with \"\\vert\"."
21142 (while (string-match "|" s)
21143 (setq s (replace-match "\\vert" t t s)))
21146 (defun org-uuidgen-p (s)
21147 "Is S an ID created by UUIDGEN?"
21148 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21150 (defun org-in-src-block-p (&optional inside)
21151 "Whether point is in a code source block.
21152 When INSIDE is non-nil, don't consider we are within a src block
21153 when point is at #+BEGIN_SRC or #+END_SRC."
21154 (let ((case-fold-search t))
21155 (or (and (eq (get-char-property (point) 'src-block) t))
21156 (and (not inside)
21157 (save-match-data
21158 (save-excursion
21159 (beginning-of-line)
21160 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21162 (defun org-context ()
21163 "Return a list of contexts of the current cursor position.
21164 If several contexts apply, all are returned.
21165 Each context entry is a list with a symbol naming the context, and
21166 two positions indicating start and end of the context. Possible
21167 contexts are:
21169 :headline anywhere in a headline
21170 :headline-stars on the leading stars in a headline
21171 :todo-keyword on a TODO keyword (including DONE) in a headline
21172 :tags on the TAGS in a headline
21173 :priority on the priority cookie in a headline
21174 :item on the first line of a plain list item
21175 :item-bullet on the bullet/number of a plain list item
21176 :checkbox on the checkbox in a plain list item
21177 :table in an Org table
21178 :table-special on a special filed in a table
21179 :table-table in a table.el table
21180 :clocktable in a clocktable
21181 :src-block in a source block
21182 :link on a hyperlink
21183 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21184 :target on a <<target>>
21185 :radio-target on a <<<radio-target>>>
21186 :latex-fragment on a LaTeX fragment
21187 :latex-preview on a LaTeX fragment with overlaid preview image
21189 This function expects the position to be visible because it uses font-lock
21190 faces as a help to recognize the following contexts: :table-special, :link,
21191 and :keyword."
21192 (let* ((f (get-text-property (point) 'face))
21193 (faces (if (listp f) f (list f)))
21194 (case-fold-search t)
21195 (p (point)) clist o)
21196 ;; First the large context
21197 (cond
21198 ((org-at-heading-p t)
21199 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21200 (when (progn
21201 (beginning-of-line 1)
21202 (looking-at org-todo-line-tags-regexp))
21203 (push (org-point-in-group p 1 :headline-stars) clist)
21204 (push (org-point-in-group p 2 :todo-keyword) clist)
21205 (push (org-point-in-group p 4 :tags) clist))
21206 (goto-char p)
21207 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21208 (when (looking-at "\\[#[A-Z0-9]\\]")
21209 (push (org-point-in-group p 0 :priority) clist)))
21211 ((org-at-item-p)
21212 (push (org-point-in-group p 2 :item-bullet) clist)
21213 (push (list :item (point-at-bol)
21214 (save-excursion (org-end-of-item) (point)))
21215 clist)
21216 (and (org-at-item-checkbox-p)
21217 (push (org-point-in-group p 0 :checkbox) clist)))
21219 ((org-at-table-p)
21220 (push (list :table (org-table-begin) (org-table-end)) clist)
21221 (when (memq 'org-formula faces)
21222 (push (list :table-special
21223 (previous-single-property-change p 'face)
21224 (next-single-property-change p 'face)) clist)))
21225 ((org-at-table-p 'any)
21226 (push (list :table-table) clist)))
21227 (goto-char p)
21229 (let ((case-fold-search t))
21230 ;; New the "medium" contexts: clocktables, source blocks
21231 (cond ((org-in-clocktable-p)
21232 (push (list :clocktable
21233 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21234 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21235 (match-beginning 1))
21236 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21237 (match-end 0))) clist))
21238 ((org-in-src-block-p)
21239 (push (list :src-block
21240 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21241 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21242 (match-beginning 1))
21243 (and (search-forward "#+END_SRC" nil t)
21244 (match-beginning 0))) clist))))
21245 (goto-char p)
21247 ;; Now the small context
21248 (cond
21249 ((org-at-timestamp-p)
21250 (push (org-point-in-group p 0 :timestamp) clist))
21251 ((memq 'org-link faces)
21252 (push (list :link
21253 (previous-single-property-change p 'face)
21254 (next-single-property-change p 'face)) clist))
21255 ((memq 'org-special-keyword faces)
21256 (push (list :keyword
21257 (previous-single-property-change p 'face)
21258 (next-single-property-change p 'face)) clist))
21259 ((org-at-target-p)
21260 (push (org-point-in-group p 0 :target) clist)
21261 (goto-char (1- (match-beginning 0)))
21262 (when (looking-at org-radio-target-regexp)
21263 (push (org-point-in-group p 0 :radio-target) clist))
21264 (goto-char p))
21265 ((setq o (cl-some
21266 (lambda (o)
21267 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21269 (overlays-at (point))))
21270 (push (list :latex-fragment
21271 (overlay-start o) (overlay-end o)) clist)
21272 (push (list :latex-preview
21273 (overlay-start o) (overlay-end o)) clist))
21274 ((org-inside-LaTeX-fragment-p)
21275 ;; FIXME: positions wrong.
21276 (push (list :latex-fragment (point) (point)) clist)))
21278 (setq clist (nreverse (delq nil clist)))
21279 clist))
21281 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21282 "Non-nil when point is between matches of START-RE and END-RE.
21284 Also return a non-nil value when point is on one of the matches.
21286 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21287 buffer positions. Default values are the positions of headlines
21288 surrounding the point.
21290 The functions returns a cons cell whose car (resp. cdr) is the
21291 position before START-RE (resp. after END-RE)."
21292 (save-match-data
21293 (let ((pos (point))
21294 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21295 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21296 beg end)
21297 (save-excursion
21298 ;; Point is on a block when on START-RE or if START-RE can be
21299 ;; found before it...
21300 (and (or (org-in-regexp start-re)
21301 (re-search-backward start-re limit-up t))
21302 (setq beg (match-beginning 0))
21303 ;; ... and END-RE after it...
21304 (goto-char (match-end 0))
21305 (re-search-forward end-re limit-down t)
21306 (> (setq end (match-end 0)) pos)
21307 ;; ... without another START-RE in-between.
21308 (goto-char (match-beginning 0))
21309 (not (re-search-backward start-re (1+ beg) t))
21310 ;; Return value.
21311 (cons beg end))))))
21313 (defun org-in-block-p (names)
21314 "Non-nil when point belongs to a block whose name belongs to NAMES.
21316 NAMES is a list of strings containing names of blocks.
21318 Return first block name matched, or nil. Beware that in case of
21319 nested blocks, the returned name may not belong to the closest
21320 block from point."
21321 (save-match-data
21322 (catch 'exit
21323 (let ((case-fold-search t)
21324 (lim-up (save-excursion (outline-previous-heading)))
21325 (lim-down (save-excursion (outline-next-heading))))
21326 (dolist (name names)
21327 (let ((n (regexp-quote name)))
21328 (when (org-between-regexps-p
21329 (concat "^[ \t]*#\\+begin_" n)
21330 (concat "^[ \t]*#\\+end_" n)
21331 lim-up lim-down)
21332 (throw 'exit n)))))
21333 nil)))
21335 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21336 "Call `multi-occur' with buffers for all agenda files."
21337 (interactive "sOrg-files matching: ")
21338 (let* ((files (org-agenda-files))
21339 (tnames (mapcar #'file-truename files))
21340 (extra org-agenda-text-search-extra-files))
21341 (when (eq (car extra) 'agenda-archives)
21342 (setq extra (cdr extra))
21343 (setq files (org-add-archive-files files)))
21344 (dolist (f extra)
21345 (unless (member (file-truename f) tnames)
21346 (unless (member f files) (setq files (append files (list f))))
21347 (setq tnames (append tnames (list (file-truename f))))))
21348 (multi-occur
21349 (mapcar (lambda (x)
21350 (with-current-buffer
21351 ;; FIXME: Why not just (find-file-noselect x)?
21352 ;; Is it to avoid the "revert buffer" prompt?
21353 (or (get-file-buffer x) (find-file-noselect x))
21354 (widen)
21355 (current-buffer)))
21356 files)
21357 regexp)))
21359 (add-hook 'occur-mode-find-occurrence-hook
21360 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21362 (defun org-occur-link-in-agenda-files ()
21363 "Create a link and search for it in the agendas.
21364 The link is not stored in `org-stored-links', it is just created
21365 for the search purpose."
21366 (interactive)
21367 (let ((link (condition-case nil
21368 (org-store-link nil)
21369 (error "Unable to create a link to here"))))
21370 (org-occur-in-agenda-files (regexp-quote link))))
21372 (defun org-back-over-empty-lines ()
21373 "Move backwards over whitespace, to the beginning of the first empty line.
21374 Returns the number of empty lines passed."
21375 (let ((pos (point)))
21376 (if (cdr (assq 'heading org-blank-before-new-entry))
21377 (skip-chars-backward " \t\n\r")
21378 (unless (eobp)
21379 (forward-line -1)))
21380 (beginning-of-line 2)
21381 (goto-char (min (point) pos))
21382 (count-lines (point) pos)))
21384 (defun org-switch-to-buffer-other-window (&rest args)
21385 "Switch to buffer in a second window on the current frame.
21386 In particular, do not allow pop-up frames.
21387 Returns the newly created buffer."
21388 (org-no-popups
21389 (apply 'switch-to-buffer-other-window args)))
21391 (defun org-replace-escapes (string table)
21392 "Replace %-escapes in STRING with values in TABLE.
21393 TABLE is an association list with keys like \"%a\" and string values.
21394 The sequences in STRING may contain normal field width and padding information,
21395 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21396 so values can contain further %-escapes if they are define later in TABLE."
21397 (let ((tbl (copy-alist table))
21398 (case-fold-search nil)
21399 (pchg 0)
21400 re rpl)
21401 (dolist (e tbl)
21402 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21403 (when (and (cdr e) (string-match re (cdr e)))
21404 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21405 (safe "SREF"))
21406 (add-text-properties 0 3 (list 'sref sref) safe)
21407 (setcdr e (replace-match safe t t (cdr e)))))
21408 (while (string-match re string)
21409 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21410 (cdr e)))
21411 (setq string (replace-match rpl t t string))))
21412 (while (setq pchg (next-property-change pchg string))
21413 (let ((sref (get-text-property pchg 'sref string)))
21414 (when (and sref (string-match "SREF" string pchg))
21415 (setq string (replace-match sref t t string)))))
21416 string))
21418 ;;; TODO: Only called once, from ox-odt which should probably use
21419 ;;; org-export-inline-image-p or something.
21420 (defun org-file-image-p (file)
21421 "Return non-nil if FILE is an image."
21422 (save-match-data
21423 (string-match (image-file-name-regexp) file)))
21425 (defun org-get-cursor-date (&optional with-time)
21426 "Return the date at cursor in as a time.
21427 This works in the calendar and in the agenda, anywhere else it just
21428 returns the current time.
21429 If WITH-TIME is non-nil, returns the time of the event at point (in
21430 the agenda) or the current time of the day."
21431 (let (date day defd tp hod mod)
21432 (when with-time
21433 (setq tp (get-text-property (point) 'time))
21434 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21435 (setq hod (string-to-number (match-string 1 tp))
21436 mod (string-to-number (match-string 2 tp))))
21437 (or tp (let ((now (decode-time)))
21438 (setq hod (nth 2 now)
21439 mod (nth 1 now)))))
21440 (cond
21441 ((eq major-mode 'calendar-mode)
21442 (setq date (calendar-cursor-to-date)
21443 defd (encode-time 0 (or mod 0) (or hod 0)
21444 (nth 1 date) (nth 0 date) (nth 2 date))))
21445 ((eq major-mode 'org-agenda-mode)
21446 (setq day (get-text-property (point) 'day))
21447 (when day
21448 (setq date (calendar-gregorian-from-absolute day)
21449 defd (encode-time 0 (or mod 0) (or hod 0)
21450 (nth 1 date) (nth 0 date) (nth 2 date))))))
21451 (or defd (current-time))))
21453 (defun org-mark-subtree (&optional up)
21454 "Mark the current subtree.
21455 This puts point at the start of the current subtree, and mark at
21456 the end. If a numeric prefix UP is given, move up into the
21457 hierarchy of headlines by UP levels before marking the subtree."
21458 (interactive "P")
21459 (org-with-limited-levels
21460 (cond ((org-at-heading-p) (beginning-of-line))
21461 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21462 (t (outline-previous-visible-heading 1))))
21463 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21464 (if (called-interactively-p 'any)
21465 (call-interactively 'org-mark-element)
21466 (org-mark-element)))
21468 (defun org-file-newer-than-p (file time)
21469 "Non-nil if FILE is newer than TIME.
21470 FILE is a filename, as a string, TIME is a list of integers, as
21471 returned by, e.g., `current-time'."
21472 (and (file-exists-p file)
21473 ;; Only compare times up to whole seconds as some file-systems
21474 ;; (e.g. HFS+) do not retain any finer granularity. As
21475 ;; a consequence, make sure we return non-nil when the two
21476 ;; times are equal.
21477 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21478 (cl-subseq time 0 2)))))
21480 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21481 "Compile a SOURCE file using PROCESS.
21483 PROCESS is either a function or a list of shell commands, as
21484 strings. EXT is a file extension, without the leading dot, as
21485 a string. It is used to check if the process actually succeeded.
21487 PROCESS must create a file with the same base name and directory
21488 as SOURCE, but ending with EXT. The function then returns its
21489 filename. Otherwise, it raises an error. The error message can
21490 then be refined by providing string ERR-MSG, which is appended to
21491 the standard message.
21493 If PROCESS is a function, it is called with a single argument:
21494 the SOURCE file.
21496 If it is a list of commands, each of them is called using
21497 `shell-command'. By default, in each command, %b, %f, %F, %o and
21498 %O are replaced with, respectively, SOURCE base name, name, full
21499 name, directory and absolute output file name. It is possible,
21500 however, to use more place-holders by specifying them in optional
21501 argument SPEC, as an alist following the pattern
21503 (CHARACTER . REPLACEMENT-STRING).
21505 When PROCESS is a list of commands, optional argument LOG-BUF can
21506 be set to a buffer or a buffer name. `shell-command' then uses
21507 it for output."
21508 (let* ((base-name (file-name-base source))
21509 (full-name (file-truename source))
21510 (out-dir (or (file-name-directory source) "./"))
21511 (output (expand-file-name (concat base-name "." ext) out-dir))
21512 (time (current-time))
21513 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21514 (save-window-excursion
21515 (pcase process
21516 ((pred functionp) (funcall process (shell-quote-argument source)))
21517 ((pred consp)
21518 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21519 (spec (append spec
21520 `((?b . ,(shell-quote-argument base-name))
21521 (?f . ,(shell-quote-argument source))
21522 (?F . ,(shell-quote-argument full-name))
21523 (?o . ,(shell-quote-argument out-dir))
21524 (?O . ,(shell-quote-argument output))))))
21525 (dolist (command process)
21526 (shell-command (format-spec command spec) log-buf))
21527 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21528 (_ (error "No valid command to process %S%s" source err-msg))))
21529 ;; Check for process failure. Output file is expected to be
21530 ;; located in the same directory as SOURCE.
21531 (unless (org-file-newer-than-p output time)
21532 (error (format "File %S wasn't produced%s" output err-msg)))
21533 output))
21535 ;;; Indentation
21537 (defvar org-element-greater-elements)
21538 (defun org--get-expected-indentation (element contentsp)
21539 "Expected indentation column for current line, according to ELEMENT.
21540 ELEMENT is an element containing point. CONTENTSP is non-nil
21541 when indentation is to be computed according to contents of
21542 ELEMENT."
21543 (let ((type (org-element-type element))
21544 (start (org-element-property :begin element))
21545 (post-affiliated (org-element-property :post-affiliated element)))
21546 (org-with-wide-buffer
21547 (cond
21548 (contentsp
21549 (cl-case type
21550 ((diary-sexp footnote-definition) 0)
21551 ((headline inlinetask nil)
21552 (if (not org-adapt-indentation) 0
21553 (let ((level (org-current-level)))
21554 (if level (1+ level) 0))))
21555 ((item plain-list) (org-list-item-body-column post-affiliated))
21557 (goto-char start)
21558 (org-get-indentation))))
21559 ((memq type '(headline inlinetask nil))
21560 (if (org-match-line "[ \t]*$")
21561 (org--get-expected-indentation element t)
21563 ((memq type '(diary-sexp footnote-definition)) 0)
21564 ;; First paragraph of a footnote definition or an item.
21565 ;; Indent like parent.
21566 ((< (line-beginning-position) start)
21567 (org--get-expected-indentation
21568 (org-element-property :parent element) t))
21569 ;; At first line: indent according to previous sibling, if any,
21570 ;; ignoring footnote definitions and inline tasks, or parent's
21571 ;; contents.
21572 ((= (line-beginning-position) start)
21573 (catch 'exit
21574 (while t
21575 (if (= (point-min) start) (throw 'exit 0)
21576 (goto-char (1- start))
21577 (let* ((previous (org-element-at-point))
21578 (parent previous))
21579 (while (and parent (<= (org-element-property :end parent) start))
21580 (setq previous parent
21581 parent (org-element-property :parent parent)))
21582 (cond
21583 ((not previous) (throw 'exit 0))
21584 ((> (org-element-property :end previous) start)
21585 (throw 'exit (org--get-expected-indentation previous t)))
21586 ((memq (org-element-type previous)
21587 '(footnote-definition inlinetask))
21588 (setq start (org-element-property :begin previous)))
21589 (t (goto-char (org-element-property :begin previous))
21590 (throw 'exit
21591 (if (bolp) (org-get-indentation)
21592 ;; At first paragraph in an item or
21593 ;; a footnote definition.
21594 (org--get-expected-indentation
21595 (org-element-property :parent previous) t))))))))))
21596 ;; Otherwise, move to the first non-blank line above.
21598 (beginning-of-line)
21599 (let ((pos (point)))
21600 (skip-chars-backward " \r\t\n")
21601 (cond
21602 ;; Two blank lines end a footnote definition or a plain
21603 ;; list. When we indent an empty line after them, the
21604 ;; containing list or footnote definition is over, so it
21605 ;; qualifies as a previous sibling. Therefore, we indent
21606 ;; like its first line.
21607 ((and (memq type '(footnote-definition plain-list))
21608 (> (count-lines (point) pos) 2))
21609 (goto-char start)
21610 (org-get-indentation))
21611 ;; Line above is the first one of a paragraph at the
21612 ;; beginning of an item or a footnote definition. Indent
21613 ;; like parent.
21614 ((< (line-beginning-position) start)
21615 (org--get-expected-indentation
21616 (org-element-property :parent element) t))
21617 ;; Line above is the beginning of an element, i.e., point
21618 ;; was originally on the blank lines between element's start
21619 ;; and contents.
21620 ((= (line-beginning-position) post-affiliated)
21621 (org--get-expected-indentation element t))
21622 ;; POS is after contents in a greater element. Indent like
21623 ;; the beginning of the element.
21624 ((and (memq type org-element-greater-elements)
21625 (let ((cend (org-element-property :contents-end element)))
21626 (and cend (<= cend pos))))
21627 ;; As a special case, if point is at the end of a footnote
21628 ;; definition or an item, indent like the very last element
21629 ;; within. If that last element is an item, indent like
21630 ;; its contents.
21631 (if (memq type '(footnote-definition item plain-list))
21632 (let ((last (org-element-at-point)))
21633 (goto-char pos)
21634 (org--get-expected-indentation
21635 last (eq (org-element-type last) 'item)))
21636 (goto-char start)
21637 (org-get-indentation)))
21638 ;; In any other case, indent like the current line.
21639 (t (org-get-indentation)))))))))
21641 (defun org--align-node-property ()
21642 "Align node property at point.
21643 Alignment is done according to `org-property-format', which see."
21644 (when (save-excursion
21645 (beginning-of-line)
21646 (looking-at org-property-re))
21647 (replace-match
21648 (concat (match-string 4)
21649 (org-trim
21650 (format org-property-format (match-string 1) (match-string 3))))
21651 t t)))
21653 (defun org-indent-line ()
21654 "Indent line depending on context.
21656 Indentation is done according to the following rules:
21658 - Footnote definitions, diary sexps, headlines and inline tasks
21659 have to start at column 0.
21661 - On the very first line of an element, consider, in order, the
21662 next rules until one matches:
21664 1. If there's a sibling element before, ignoring footnote
21665 definitions and inline tasks, indent like its first line.
21667 2. If element has a parent, indent like its contents. More
21668 precisely, if parent is an item, indent after the
21669 description part, if any, or the bullet (see
21670 `org-list-description-max-indent'). Else, indent like
21671 parent's first line.
21673 3. Otherwise, indent relatively to current level, if
21674 `org-adapt-indentation' is non-nil, or to left margin.
21676 - On a blank line at the end of an element, indent according to
21677 the type of the element. More precisely
21679 1. If element is a plain list, an item, or a footnote
21680 definition, indent like the very last element within.
21682 2. If element is a paragraph, indent like its last non blank
21683 line.
21685 3. Otherwise, indent like its very first line.
21687 - In the code part of a source block, use language major mode
21688 to indent current line if `org-src-tab-acts-natively' is
21689 non-nil. If it is nil, do nothing.
21691 - Otherwise, indent like the first non-blank line above.
21693 The function doesn't indent an item as it could break the whole
21694 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21695 `\\[org-shiftmetaright]'.
21697 Also align node properties according to `org-property-format'."
21698 (interactive)
21699 (cond
21700 ((org-at-heading-p) 'noindent)
21702 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21703 (type (org-element-type element)))
21704 (cond ((and (memq type '(plain-list item))
21705 (= (line-beginning-position)
21706 (org-element-property :post-affiliated element)))
21707 'noindent)
21708 ((and (eq type 'latex-environment)
21709 (>= (point) (org-element-property :post-affiliated element))
21710 (< (point) (org-with-wide-buffer
21711 (goto-char (org-element-property :end element))
21712 (skip-chars-backward " \r\t\n")
21713 (line-beginning-position 2))))
21714 'noindent)
21715 ((and (eq type 'src-block)
21716 org-src-tab-acts-natively
21717 (> (line-beginning-position)
21718 (org-element-property :post-affiliated element))
21719 (< (line-beginning-position)
21720 (org-with-wide-buffer
21721 (goto-char (org-element-property :end element))
21722 (skip-chars-backward " \r\t\n")
21723 (line-beginning-position))))
21724 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21726 (let ((column (org--get-expected-indentation element nil)))
21727 ;; Preserve current column.
21728 (if (<= (current-column) (current-indentation))
21729 (indent-line-to column)
21730 (save-excursion (indent-line-to column))))
21731 ;; Align node property. Also preserve current column.
21732 (when (eq type 'node-property)
21733 (let ((column (current-column)))
21734 (org--align-node-property)
21735 (org-move-to-column column)))))))))
21737 (defun org-indent-region (start end)
21738 "Indent each non-blank line in the region.
21739 Called from a program, START and END specify the region to
21740 indent. The function will not indent contents of example blocks,
21741 verse blocks and export blocks as leading white spaces are
21742 assumed to be significant there."
21743 (interactive "r")
21744 (save-excursion
21745 (goto-char start)
21746 (skip-chars-forward " \r\t\n")
21747 (unless (eobp) (beginning-of-line))
21748 (let ((indent-to
21749 (lambda (ind pos)
21750 ;; Set IND as indentation for all lines between point and
21751 ;; POS. Blank lines are ignored. Leave point after POS
21752 ;; once done.
21753 (let ((limit (copy-marker pos)))
21754 (while (< (point) limit)
21755 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21756 (forward-line))
21757 (set-marker limit nil))))
21758 (end (copy-marker end)))
21759 (while (< (point) end)
21760 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21761 (let* ((element (org-element-at-point))
21762 (type (org-element-type element))
21763 (element-end (copy-marker (org-element-property :end element)))
21764 (ind (org--get-expected-indentation element nil)))
21765 (cond
21766 ;; Element indented as a single block. Example blocks
21767 ;; preserving indentation are a special case since the
21768 ;; "contents" must not be indented whereas the block
21769 ;; boundaries can.
21770 ((or (memq type '(export-block latex-environment))
21771 (and (eq type 'example-block)
21772 (not
21773 (or org-src-preserve-indentation
21774 (org-element-property :preserve-indent element)))))
21775 (let ((offset (- ind (org-get-indentation))))
21776 (unless (zerop offset)
21777 (indent-rigidly (org-element-property :begin element)
21778 (org-element-property :end element)
21779 offset)))
21780 (goto-char element-end))
21781 ;; Elements indented line wise. Be sure to exclude
21782 ;; example blocks (preserving indentation) and source
21783 ;; blocks from this category as they are treated
21784 ;; specially later.
21785 ((or (memq type '(paragraph table table-row))
21786 (not (or (org-element-property :contents-begin element)
21787 (memq type '(example-block src-block)))))
21788 (when (eq type 'node-property)
21789 (org--align-node-property)
21790 (beginning-of-line))
21791 (funcall indent-to ind (min element-end end)))
21792 ;; Elements consisting of three parts: before the
21793 ;; contents, the contents, and after the contents. The
21794 ;; contents are treated specially, according to the
21795 ;; element type, or not indented at all. Other parts are
21796 ;; indented as a single block.
21798 (let* ((post (copy-marker
21799 (org-element-property :post-affiliated element)))
21800 (cbeg
21801 (copy-marker
21802 (cond
21803 ((not (org-element-property :contents-begin element))
21804 ;; Fake contents for source blocks.
21805 (org-with-wide-buffer
21806 (goto-char post)
21807 (line-beginning-position 2)))
21808 ((memq type '(footnote-definition item plain-list))
21809 ;; Contents in these elements could start on
21810 ;; the same line as the beginning of the
21811 ;; element. Make sure we start indenting
21812 ;; from the second line.
21813 (org-with-wide-buffer
21814 (goto-char post)
21815 (end-of-line)
21816 (skip-chars-forward " \r\t\n")
21817 (if (eobp) (point) (line-beginning-position))))
21818 (t (org-element-property :contents-begin element)))))
21819 (cend (copy-marker
21820 (or (org-element-property :contents-end element)
21821 ;; Fake contents for source blocks.
21822 (org-with-wide-buffer
21823 (goto-char element-end)
21824 (skip-chars-backward " \r\t\n")
21825 (line-beginning-position)))
21826 t)))
21827 ;; Do not change items indentation individually as it
21828 ;; might break the list as a whole. On the other
21829 ;; hand, when at a plain list, indent it as a whole.
21830 (cond ((eq type 'plain-list)
21831 (let ((offset (- ind (org-get-indentation))))
21832 (unless (zerop offset)
21833 (indent-rigidly (org-element-property :begin element)
21834 (org-element-property :end element)
21835 offset))
21836 (goto-char cbeg)))
21837 ((eq type 'item) (goto-char cbeg))
21838 (t (funcall indent-to ind (min cbeg end))))
21839 (when (< (point) end)
21840 (cl-case type
21841 ((example-block verse-block))
21842 (src-block
21843 ;; In a source block, indent source code
21844 ;; according to language major mode, but only if
21845 ;; `org-src-tab-acts-natively' is non-nil.
21846 (when (and (< (point) end) org-src-tab-acts-natively)
21847 (ignore-errors
21848 (org-babel-do-in-edit-buffer
21849 (indent-region (point-min) (point-max))))))
21850 (t (org-indent-region (point) (min cend end))))
21851 (goto-char (min cend end))
21852 (when (< (point) end)
21853 (funcall indent-to ind (min element-end end))))
21854 (set-marker post nil)
21855 (set-marker cbeg nil)
21856 (set-marker cend nil))))
21857 (set-marker element-end nil))))
21858 (set-marker end nil))))
21860 (defun org-indent-drawer ()
21861 "Indent the drawer at point."
21862 (interactive)
21863 (unless (save-excursion
21864 (beginning-of-line)
21865 (looking-at-p org-drawer-regexp))
21866 (user-error "Not at a drawer"))
21867 (let ((element (org-element-at-point)))
21868 (unless (memq (org-element-type element) '(drawer property-drawer))
21869 (user-error "Not at a drawer"))
21870 (org-with-wide-buffer
21871 (org-indent-region (org-element-property :begin element)
21872 (org-element-property :end element))))
21873 (message "Drawer at point indented"))
21875 (defun org-indent-block ()
21876 "Indent the block at point."
21877 (interactive)
21878 (unless (save-excursion
21879 (beginning-of-line)
21880 (let ((case-fold-search t))
21881 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21882 (user-error "Not at a block"))
21883 (let ((element (org-element-at-point)))
21884 (unless (memq (org-element-type element)
21885 '(comment-block center-block dynamic-block example-block
21886 export-block quote-block special-block
21887 src-block verse-block))
21888 (user-error "Not at a block"))
21889 (org-with-wide-buffer
21890 (org-indent-region (org-element-property :begin element)
21891 (org-element-property :end element))))
21892 (message "Block at point indented"))
21895 ;;; Filling
21897 ;; We use our own fill-paragraph and auto-fill functions.
21899 ;; `org-fill-paragraph' relies on adaptive filling and context
21900 ;; checking. Appropriate `fill-prefix' is computed with
21901 ;; `org-adaptive-fill-function'.
21903 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21904 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21905 ;; `org-adaptive-fill-function' value. Internally,
21906 ;; `org-comment-line-break-function' breaks the line.
21908 ;; `org-setup-filling' installs filling and auto-filling related
21909 ;; variables during `org-mode' initialization.
21911 (defun org-setup-filling ()
21912 (require 'org-element)
21913 ;; Prevent auto-fill from inserting unwanted new items.
21914 (when (boundp 'fill-nobreak-predicate)
21915 (setq-local
21916 fill-nobreak-predicate
21917 (org-uniquify
21918 (append fill-nobreak-predicate
21919 '(org-fill-line-break-nobreak-p
21920 org-fill-n-macro-as-item-nobreak-p
21921 org-fill-paragraph-with-timestamp-nobreak-p)))))
21922 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21923 (setq-local paragraph-start paragraph-ending)
21924 (setq-local paragraph-separate paragraph-ending))
21925 (setq-local fill-paragraph-function 'org-fill-paragraph)
21926 (setq-local auto-fill-inhibit-regexp nil)
21927 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21928 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21929 (setq-local comment-line-break-function 'org-comment-line-break-function))
21931 (defun org-fill-line-break-nobreak-p ()
21932 "Non-nil when a new line at point would create an Org line break."
21933 (save-excursion
21934 (skip-chars-backward "[ \t]")
21935 (skip-chars-backward "\\\\")
21936 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21938 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21939 "Non-nil when a new line at point would split a timestamp."
21940 (and (org-at-timestamp-p 'lax)
21941 (not (looking-at org-ts-regexp-both))))
21943 (defun org-fill-n-macro-as-item-nobreak-p ()
21944 "Non-nil when a new line at point would create a new list."
21945 ;; During export, a "n" macro followed by a dot or a closing
21946 ;; parenthesis can end up being parsed as a new list item.
21947 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21949 (defvar orgtbl-line-start-regexp) ; From org-table.el
21950 (defun org-adaptive-fill-function ()
21951 "Compute a fill prefix for the current line.
21952 Return fill prefix, as a string, or nil if current line isn't
21953 meant to be filled. For convenience, if `adaptive-fill-regexp'
21954 matches in paragraphs or comments, use it."
21955 (org-with-wide-buffer
21956 (unless (org-at-heading-p)
21957 (let* ((p (line-beginning-position))
21958 (element (save-excursion
21959 (beginning-of-line)
21960 (org-element-at-point)))
21961 (type (org-element-type element))
21962 (post-affiliated (org-element-property :post-affiliated element)))
21963 (unless (< p post-affiliated)
21964 (cl-case type
21965 (comment
21966 (save-excursion
21967 (beginning-of-line)
21968 (looking-at "[ \t]*")
21969 (concat (match-string 0) "# ")))
21970 (footnote-definition "")
21971 ((item plain-list)
21972 (make-string (org-list-item-body-column post-affiliated) ?\s))
21973 (paragraph
21974 ;; Fill prefix is usually the same as the current line,
21975 ;; unless the paragraph is at the beginning of an item.
21976 (let ((parent (org-element-property :parent element)))
21977 (save-excursion
21978 (beginning-of-line)
21979 (cond ((eq (org-element-type parent) 'item)
21980 (make-string (org-list-item-body-column
21981 (org-element-property :begin parent))
21982 ?\s))
21983 ((and adaptive-fill-regexp
21984 ;; Locally disable
21985 ;; `adaptive-fill-function' to let
21986 ;; `fill-context-prefix' handle
21987 ;; `adaptive-fill-regexp' variable.
21988 (let (adaptive-fill-function)
21989 (fill-context-prefix
21990 post-affiliated
21991 (org-element-property :end element)))))
21992 ((looking-at "[ \t]+") (match-string 0))
21993 (t "")))))
21994 (comment-block
21995 ;; Only fill contents if P is within block boundaries.
21996 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21997 (forward-line)
21998 (point)))
21999 (cend (save-excursion
22000 (goto-char (org-element-property :end element))
22001 (skip-chars-backward " \r\t\n")
22002 (line-beginning-position))))
22003 (when (and (>= p cbeg) (< p cend))
22004 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22005 (match-string 0)
22006 ""))))))))))
22008 (defun org-fill-element (&optional justify)
22009 "Fill element at point, when applicable.
22011 This function only applies to comment blocks, comments, example
22012 blocks and paragraphs. Also, as a special case, re-align table
22013 when point is at one.
22015 If JUSTIFY is non-nil (interactively, with prefix argument),
22016 justify as well. If `sentence-end-double-space' is non-nil, then
22017 period followed by one space does not end a sentence, so don't
22018 break a line there. The variable `fill-column' controls the
22019 width for filling.
22021 For convenience, when point is at a plain list, an item or
22022 a footnote definition, try to fill the first paragraph within."
22023 (with-syntax-table org-mode-transpose-word-syntax-table
22024 ;; Move to end of line in order to get the first paragraph within
22025 ;; a plain list or a footnote definition.
22026 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22027 ;; First check if point is in a blank line at the beginning of
22028 ;; the buffer. In that case, ignore filling.
22029 (cl-case (org-element-type element)
22030 ;; Use major mode filling function is src blocks.
22031 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22032 ;; Align Org tables, leave table.el tables as-is.
22033 (table-row (org-table-align) t)
22034 (table
22035 (when (eq (org-element-property :type element) 'org)
22036 (save-excursion
22037 (goto-char (org-element-property :post-affiliated element))
22038 (org-table-align)))
22040 (paragraph
22041 ;; Paragraphs may contain `line-break' type objects.
22042 (let ((beg (max (point-min)
22043 (org-element-property :contents-begin element)))
22044 (end (min (point-max)
22045 (org-element-property :contents-end element))))
22046 ;; Do nothing if point is at an affiliated keyword.
22047 (if (< (line-end-position) beg) t
22048 ;; Fill paragraph, taking line breaks into account.
22049 (save-excursion
22050 (goto-char beg)
22051 (let ((cuts (list beg)))
22052 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22053 (when (eq 'line-break
22054 (org-element-type
22055 (save-excursion (backward-char)
22056 (org-element-context))))
22057 (push (point) cuts)))
22058 (dolist (c (delq end cuts))
22059 (fill-region-as-paragraph c end justify)
22060 (setq end c))))
22061 t)))
22062 ;; Contents of `comment-block' type elements should be
22063 ;; filled as plain text, but only if point is within block
22064 ;; markers.
22065 (comment-block
22066 (let* ((case-fold-search t)
22067 (beg (save-excursion
22068 (goto-char (org-element-property :begin element))
22069 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22070 (forward-line)
22071 (point)))
22072 (end (save-excursion
22073 (goto-char (org-element-property :end element))
22074 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22075 (line-beginning-position))))
22076 (if (or (< (point) beg) (> (point) end)) t
22077 (fill-region-as-paragraph
22078 (save-excursion (end-of-line)
22079 (re-search-backward "^[ \t]*$" beg 'move)
22080 (line-beginning-position))
22081 (save-excursion (beginning-of-line)
22082 (re-search-forward "^[ \t]*$" end 'move)
22083 (line-beginning-position))
22084 justify))))
22085 ;; Fill comments.
22086 (comment
22087 (let ((begin (org-element-property :post-affiliated element))
22088 (end (org-element-property :end element)))
22089 (when (and (>= (point) begin) (<= (point) end))
22090 (let ((begin (save-excursion
22091 (end-of-line)
22092 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22093 (progn (forward-line) (point))
22094 begin)))
22095 (end (save-excursion
22096 (end-of-line)
22097 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22098 (1- (line-beginning-position))
22099 (skip-chars-backward " \r\t\n")
22100 (line-end-position)))))
22101 ;; Do not fill comments when at a blank line.
22102 (when (> end begin)
22103 (let ((fill-prefix
22104 (save-excursion
22105 (beginning-of-line)
22106 (looking-at "[ \t]*#")
22107 (let ((comment-prefix (match-string 0)))
22108 (goto-char (match-end 0))
22109 (if (looking-at adaptive-fill-regexp)
22110 (concat comment-prefix (match-string 0))
22111 (concat comment-prefix " "))))))
22112 (save-excursion
22113 (fill-region-as-paragraph begin end justify))))))
22115 ;; Ignore every other element.
22116 (otherwise t)))))
22118 (defun org-fill-paragraph (&optional justify region)
22119 "Fill element at point, when applicable.
22121 This function only applies to comment blocks, comments, example
22122 blocks and paragraphs. Also, as a special case, re-align table
22123 when point is at one.
22125 For convenience, when point is at a plain list, an item or
22126 a footnote definition, try to fill the first paragraph within.
22128 If JUSTIFY is non-nil (interactively, with prefix argument),
22129 justify as well. If `sentence-end-double-space' is non-nil, then
22130 period followed by one space does not end a sentence, so don't
22131 break a line there. The variable `fill-column' controls the
22132 width for filling.
22134 The REGION argument is non-nil if called interactively; in that
22135 case, if Transient Mark mode is enabled and the mark is active,
22136 fill each of the elements in the active region, instead of just
22137 filling the current element."
22138 (interactive (progn
22139 (barf-if-buffer-read-only)
22140 (list (if current-prefix-arg 'full) t)))
22141 (cond
22142 ((and region transient-mark-mode mark-active
22143 (not (eq (region-beginning) (region-end))))
22144 (let ((origin (point-marker))
22145 (start (region-beginning)))
22146 (unwind-protect
22147 (progn
22148 (goto-char (region-end))
22149 (while (> (point) start)
22150 (org-backward-paragraph)
22151 (org-fill-element justify)))
22152 (goto-char origin)
22153 (set-marker origin nil))))
22154 (t (org-fill-element justify))))
22155 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22157 (defun org-auto-fill-function ()
22158 "Auto-fill function."
22159 ;; Check if auto-filling is meaningful.
22160 (let ((fc (current-fill-column)))
22161 (when (and fc (> (current-column) fc))
22162 (let* ((fill-prefix (org-adaptive-fill-function))
22163 ;; Enforce empty fill prefix, if required. Otherwise, it
22164 ;; will be computed again.
22165 (adaptive-fill-mode (not (equal fill-prefix ""))))
22166 (when fill-prefix (do-auto-fill))))))
22168 (defun org-comment-line-break-function (&optional soft)
22169 "Break line at point and indent, continuing comment if within one.
22170 The inserted newline is marked hard if variable
22171 `use-hard-newlines' is true, unless optional argument SOFT is
22172 non-nil."
22173 (if soft (insert-and-inherit ?\n) (newline 1))
22174 (save-excursion (forward-char -1) (delete-horizontal-space))
22175 (delete-horizontal-space)
22176 (indent-to-left-margin)
22177 (insert-before-markers-and-inherit fill-prefix))
22180 ;;; Fixed Width Areas
22182 (defun org-toggle-fixed-width ()
22183 "Toggle fixed-width markup.
22185 Add or remove fixed-width markup on current line, whenever it
22186 makes sense. Return an error otherwise.
22188 If a region is active and if it contains only fixed-width areas
22189 or blank lines, remove all fixed-width markup in it. If the
22190 region contains anything else, convert all non-fixed-width lines
22191 to fixed-width ones.
22193 Blank lines at the end of the region are ignored unless the
22194 region only contains such lines."
22195 (interactive)
22196 (if (not (org-region-active-p))
22197 ;; No region:
22199 ;; Remove fixed width marker only in a fixed-with element.
22201 ;; Add fixed width maker in paragraphs, in blank lines after
22202 ;; elements or at the beginning of a headline or an inlinetask,
22203 ;; and before any one-line elements (e.g., a clock).
22204 (progn
22205 (beginning-of-line)
22206 (let* ((element (org-element-at-point))
22207 (type (org-element-type element)))
22208 (cond
22209 ((and (eq type 'fixed-width)
22210 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22211 (replace-match
22212 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22213 ((and (memq type '(babel-call clock comment diary-sexp headline
22214 horizontal-rule keyword paragraph
22215 planning))
22216 (<= (org-element-property :post-affiliated element) (point)))
22217 (skip-chars-forward " \t")
22218 (insert ": "))
22219 ((and (looking-at-p "[ \t]*$")
22220 (or (eq type 'inlinetask)
22221 (save-excursion
22222 (skip-chars-forward " \r\t\n")
22223 (<= (org-element-property :end element) (point)))))
22224 (delete-region (point) (line-end-position))
22225 (org-indent-line)
22226 (insert ": "))
22227 (t (user-error "Cannot insert a fixed-width line here")))))
22228 ;; Region active.
22229 (let* ((begin (save-excursion
22230 (goto-char (region-beginning))
22231 (line-beginning-position)))
22232 (end (copy-marker
22233 (save-excursion
22234 (goto-char (region-end))
22235 (unless (eolp) (beginning-of-line))
22236 (if (save-excursion (re-search-backward "\\S-" begin t))
22237 (progn (skip-chars-backward " \r\t\n") (point))
22238 (point)))))
22239 (all-fixed-width-p
22240 (catch 'not-all-p
22241 (save-excursion
22242 (goto-char begin)
22243 (skip-chars-forward " \r\t\n")
22244 (when (eobp) (throw 'not-all-p nil))
22245 (while (< (point) end)
22246 (let ((element (org-element-at-point)))
22247 (if (eq (org-element-type element) 'fixed-width)
22248 (goto-char (org-element-property :end element))
22249 (throw 'not-all-p nil))))
22250 t))))
22251 (if all-fixed-width-p
22252 (save-excursion
22253 (goto-char begin)
22254 (while (< (point) end)
22255 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22256 (replace-match
22257 "" nil nil nil
22258 (if (= (line-end-position) (match-end 0)) 0 1)))
22259 (forward-line)))
22260 (let ((min-ind (point-max)))
22261 ;; Find minimum indentation across all lines.
22262 (save-excursion
22263 (goto-char begin)
22264 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22265 (setq min-ind 0)
22266 (catch 'zerop
22267 (while (< (point) end)
22268 (unless (looking-at-p "[ \t]*$")
22269 (let ((ind (org-get-indentation)))
22270 (setq min-ind (min min-ind ind))
22271 (when (zerop ind) (throw 'zerop t))))
22272 (forward-line)))))
22273 ;; Loop over all lines and add fixed-width markup everywhere
22274 ;; but in fixed-width lines.
22275 (save-excursion
22276 (goto-char begin)
22277 (while (< (point) end)
22278 (cond
22279 ((org-at-heading-p)
22280 (insert ": ")
22281 (forward-line)
22282 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22283 (insert ":")
22284 (forward-line)))
22285 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22286 (let* ((element (org-element-at-point))
22287 (element-end (org-element-property :end element)))
22288 (if (eq (org-element-type element) 'fixed-width)
22289 (progn (goto-char element-end)
22290 (skip-chars-backward " \r\t\n")
22291 (forward-line))
22292 (let ((limit (min end element-end)))
22293 (while (< (point) limit)
22294 (org-move-to-column min-ind t)
22295 (insert ": ")
22296 (forward-line))))))
22298 (org-move-to-column min-ind t)
22299 (insert ": ")
22300 (forward-line)))))))
22301 (set-marker end nil))))
22304 ;;; Blocks
22306 (defun org-block-map (function &optional start end)
22307 "Call FUNCTION at the head of all source blocks in the current buffer.
22308 Optional arguments START and END can be used to limit the range."
22309 (let ((start (or start (point-min)))
22310 (end (or end (point-max))))
22311 (save-excursion
22312 (goto-char start)
22313 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22314 (save-excursion
22315 (save-match-data
22316 (goto-char (match-beginning 0))
22317 (funcall function)))))))
22319 (defun org-next-block (arg &optional backward block-regexp)
22320 "Jump to the next block.
22322 With a prefix argument ARG, jump forward ARG many blocks.
22324 When BACKWARD is non-nil, jump to the previous block.
22326 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22327 Match data is set according to this regexp when the function
22328 returns.
22330 Return point at beginning of the opening line of found block.
22331 Throw an error if no block is found."
22332 (interactive "p")
22333 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22334 (case-fold-search t)
22335 (search-fn (if backward #'re-search-backward #'re-search-forward))
22336 (count (or arg 1))
22337 (origin (point))
22338 last-element)
22339 (if backward (beginning-of-line) (end-of-line))
22340 (while (and (> count 0) (funcall search-fn re nil t))
22341 (let ((element (save-excursion
22342 (goto-char (match-beginning 0))
22343 (save-match-data (org-element-at-point)))))
22344 (when (and (memq (org-element-type element)
22345 '(center-block comment-block dynamic-block
22346 example-block export-block quote-block
22347 special-block src-block verse-block))
22348 (<= (match-beginning 0)
22349 (org-element-property :post-affiliated element)))
22350 (setq last-element element)
22351 (cl-decf count))))
22352 (if (= count 0)
22353 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22354 (save-match-data (org-show-context)))
22355 (goto-char origin)
22356 (user-error "No %s code blocks" (if backward "previous" "further")))))
22358 (defun org-previous-block (arg &optional block-regexp)
22359 "Jump to the previous block.
22360 With a prefix argument ARG, jump backward ARG many source blocks.
22361 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22362 (interactive "p")
22363 (org-next-block arg t block-regexp))
22366 ;;; Comments
22368 ;; Org comments syntax is quite complex. It requires the entire line
22369 ;; to be just a comment. Also, even with the right syntax at the
22370 ;; beginning of line, some elements (e.g., verse-block or
22371 ;; example-block) don't accept comments. Usual Emacs comment commands
22372 ;; cannot cope with those requirements. Therefore, Org replaces them.
22374 ;; Org still relies on `comment-dwim', but cannot trust
22375 ;; `comment-only-p'. So, `comment-region-function' and
22376 ;; `uncomment-region-function' both point
22377 ;; to`org-comment-or-uncomment-region'. Eventually,
22378 ;; `org-insert-comment' takes care of insertion of comments at the
22379 ;; beginning of line.
22381 ;; `org-setup-comments-handling' install comments related variables
22382 ;; during `org-mode' initialization.
22384 (defun org-setup-comments-handling ()
22385 (interactive)
22386 (setq-local comment-use-syntax nil)
22387 (setq-local comment-start "# ")
22388 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22389 (setq-local comment-insert-comment-function 'org-insert-comment)
22390 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22391 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22393 (defun org-insert-comment ()
22394 "Insert an empty comment above current line.
22395 If the line is empty, insert comment at its beginning. When
22396 point is within a source block, comment according to the related
22397 major mode."
22398 (if (let ((element (org-element-at-point)))
22399 (and (eq (org-element-type element) 'src-block)
22400 (< (save-excursion
22401 (goto-char (org-element-property :post-affiliated element))
22402 (line-end-position))
22403 (point))
22404 (> (save-excursion
22405 (goto-char (org-element-property :end element))
22406 (skip-chars-backward " \r\t\n")
22407 (line-beginning-position))
22408 (point))))
22409 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22410 (beginning-of-line)
22411 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22412 (open-line 1))
22413 (org-indent-line)
22414 (insert "# ")))
22416 (defvar comment-empty-lines) ; From newcomment.el.
22417 (defun org-comment-or-uncomment-region (beg end &rest _)
22418 "Comment or uncomment each non-blank line in the region.
22419 Uncomment each non-blank line between BEG and END if it only
22420 contains commented lines. Otherwise, comment them. If region is
22421 strictly within a source block, use appropriate comment syntax."
22422 (if (let ((element (org-element-at-point)))
22423 (and (eq (org-element-type element) 'src-block)
22424 (< (save-excursion
22425 (goto-char (org-element-property :post-affiliated element))
22426 (line-end-position))
22427 beg)
22428 (>= (save-excursion
22429 (goto-char (org-element-property :end element))
22430 (skip-chars-backward " \r\t\n")
22431 (line-beginning-position))
22432 end)))
22433 ;; Translate region boundaries for the Org buffer to the source
22434 ;; buffer.
22435 (let ((offset (- end beg)))
22436 (save-excursion
22437 (goto-char beg)
22438 (org-babel-do-in-edit-buffer
22439 (comment-or-uncomment-region (point) (+ offset (point))))))
22440 (save-restriction
22441 ;; Restrict region
22442 (narrow-to-region (save-excursion (goto-char beg)
22443 (skip-chars-forward " \r\t\n" end)
22444 (line-beginning-position))
22445 (save-excursion (goto-char end)
22446 (skip-chars-backward " \r\t\n" beg)
22447 (line-end-position)))
22448 (let ((uncommentp
22449 ;; UNCOMMENTP is non-nil when every non blank line between
22450 ;; BEG and END is a comment.
22451 (save-excursion
22452 (goto-char (point-min))
22453 (while (and (not (eobp))
22454 (let ((element (org-element-at-point)))
22455 (and (eq (org-element-type element) 'comment)
22456 (goto-char (min (point-max)
22457 (org-element-property
22458 :end element)))))))
22459 (eobp))))
22460 (if uncommentp
22461 ;; Only blank lines and comments in region: uncomment it.
22462 (save-excursion
22463 (goto-char (point-min))
22464 (while (not (eobp))
22465 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22466 (replace-match "" nil nil nil 1))
22467 (forward-line)))
22468 ;; Comment each line in region.
22469 (let ((min-indent (point-max)))
22470 ;; First find the minimum indentation across all lines.
22471 (save-excursion
22472 (goto-char (point-min))
22473 (while (and (not (eobp)) (not (zerop min-indent)))
22474 (unless (looking-at "[ \t]*$")
22475 (setq min-indent (min min-indent (current-indentation))))
22476 (forward-line)))
22477 ;; Then loop over all lines.
22478 (save-excursion
22479 (goto-char (point-min))
22480 (while (not (eobp))
22481 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22482 ;; Don't get fooled by invisible text (e.g. link path)
22483 ;; when moving to column MIN-INDENT.
22484 (let ((buffer-invisibility-spec nil))
22485 (org-move-to-column min-indent t))
22486 (insert comment-start))
22487 (forward-line)))))))))
22489 (defun org-comment-dwim (_arg)
22490 "Call the comment command you mean.
22491 Call `org-toggle-comment' if on a heading, otherwise call
22492 `comment-dwim', within a source edit buffer if needed."
22493 (interactive "*P")
22494 (cond ((org-at-heading-p)
22495 (call-interactively #'org-toggle-comment))
22496 ((org-in-src-block-p)
22497 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22498 (t (call-interactively #'comment-dwim))))
22501 ;;; Timestamps API
22503 ;; This section contains tools to operate on, or create, timestamp
22504 ;; objects, as returned by, e.g. `org-element-context'.
22506 (defun org-timestamp-from-string (s)
22507 "Convert Org timestamp S, as a string, into a timestamp object.
22508 Return nil if S is not a valid timestamp string."
22509 (when (org-string-nw-p s)
22510 (with-temp-buffer
22511 (save-excursion (insert s))
22512 (org-element-timestamp-parser))))
22514 (defun org-timestamp-from-time (time &optional with-time inactive)
22515 "Convert a time value into a timestamp object.
22517 TIME is an Emacs internal time representation, as returned, e.g.,
22518 by `current-time'.
22520 When optional argument WITH-TIME is non-nil, return a timestamp
22521 object with a time part, i.e., with hours and minutes.
22523 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22524 return an active timestamp."
22525 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22526 (org-element-create 'timestamp
22527 (list :type (if inactive 'inactive 'active)
22528 :year-start year
22529 :month-start month
22530 :day-start day
22531 :hour-start (and with-time hour)
22532 :minute-start (and with-time minute)))))
22534 (defun org-timestamp-to-time (timestamp &optional end)
22535 "Convert TIMESTAMP object into an Emacs internal time value.
22536 Use end of date range or time range when END is non-nil.
22537 Otherwise, use its start."
22538 (apply #'encode-time
22539 (cons 0
22540 (mapcar
22541 (lambda (prop) (or (org-element-property prop timestamp) 0))
22542 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22543 '(:minute-start :hour-start :day-start :month-start
22544 :year-start))))))
22546 (defun org-timestamp-has-time-p (timestamp)
22547 "Non-nil when TIMESTAMP has a time specified."
22548 (org-element-property :hour-start timestamp))
22550 (defun org-timestamp-format (timestamp format &optional end utc)
22551 "Format a TIMESTAMP object into a string.
22553 FORMAT is a format specifier to be passed to
22554 `format-time-string'.
22556 When optional argument END is non-nil, use end of date-range or
22557 time-range, if possible.
22559 When optional argument UTC is non-nil, time is be expressed as
22560 Universal Time."
22561 (format-time-string format (org-timestamp-to-time timestamp end)
22562 (and utc t)))
22564 (defun org-timestamp-split-range (timestamp &optional end)
22565 "Extract a TIMESTAMP object from a date or time range.
22567 END, when non-nil, means extract the end of the range.
22568 Otherwise, extract its start.
22570 Return a new timestamp object."
22571 (let ((type (org-element-property :type timestamp)))
22572 (if (memq type '(active inactive diary)) timestamp
22573 (let ((split-ts (org-element-copy timestamp)))
22574 ;; Set new type.
22575 (org-element-put-property
22576 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22577 ;; Copy start properties over end properties if END is
22578 ;; non-nil. Otherwise, copy end properties over `start' ones.
22579 (let ((p-alist '((:minute-start . :minute-end)
22580 (:hour-start . :hour-end)
22581 (:day-start . :day-end)
22582 (:month-start . :month-end)
22583 (:year-start . :year-end))))
22584 (dolist (p-cell p-alist)
22585 (org-element-put-property
22586 split-ts
22587 (funcall (if end #'car #'cdr) p-cell)
22588 (org-element-property
22589 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22590 ;; Eventually refresh `:raw-value'.
22591 (org-element-put-property split-ts :raw-value nil)
22592 (org-element-put-property
22593 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22595 (defun org-timestamp-translate (timestamp &optional boundary)
22596 "Translate TIMESTAMP object to custom format.
22598 Format string is defined in `org-time-stamp-custom-formats',
22599 which see.
22601 When optional argument BOUNDARY is non-nil, it is either the
22602 symbol `start' or `end'. In this case, only translate the
22603 starting or ending part of TIMESTAMP if it is a date or time
22604 range. Otherwise, translate both parts.
22606 Return timestamp as-is if `org-display-custom-times' is nil or if
22607 it has a `diary' type."
22608 (let ((type (org-element-property :type timestamp)))
22609 (if (or (not org-display-custom-times) (eq type 'diary))
22610 (org-element-interpret-data timestamp)
22611 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22612 org-time-stamp-custom-formats)))
22613 (if (and (not boundary) (memq type '(active-range inactive-range)))
22614 (concat (org-timestamp-format timestamp fmt)
22615 "--"
22616 (org-timestamp-format timestamp fmt t))
22617 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22621 ;;; Other stuff.
22623 (defvar reftex-docstruct-symbol)
22624 (defvar org--rds)
22626 (defun org-reftex-citation ()
22627 "Use reftex-citation to insert a citation into the buffer.
22628 This looks for a line like
22630 #+BIBLIOGRAPHY: foo plain option:-d
22632 and derives from it that foo.bib is the bibliography file relevant
22633 for this document. It then installs the necessary environment for RefTeX
22634 to work in this buffer and calls `reftex-citation' to insert a citation
22635 into the buffer.
22637 Export of such citations to both LaTeX and HTML is handled by the contributed
22638 package ox-bibtex by Taru Karttunen."
22639 (interactive)
22640 (let ((reftex-docstruct-symbol 'org--rds)
22641 org--rds bib)
22642 (org-with-wide-buffer
22643 (let ((case-fold-search t)
22644 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22645 (if (not (save-excursion
22646 (or (re-search-forward re nil t)
22647 (re-search-backward re nil t))))
22648 (user-error "No bibliography defined in file")
22649 (setq bib (concat (match-string 1) ".bib")
22650 org--rds (list (list 'bib bib))))))
22651 (call-interactively 'reftex-citation)))
22653 ;;;; Functions extending outline functionality
22655 (defun org-beginning-of-line (&optional n)
22656 "Go to the beginning of the current visible line.
22658 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22659 tags on the first attempt, and only move to after the tags when
22660 the cursor is already beyond the end of the headline.
22662 With argument N not nil or 1, move forward N - 1 lines first."
22663 (interactive "^p")
22664 (let ((origin (point))
22665 (special (pcase org-special-ctrl-a/e
22666 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22667 deactivate-mark)
22668 ;; First move to a visible line.
22669 (if (bound-and-true-p visual-line-mode)
22670 (beginning-of-visual-line n)
22671 (move-beginning-of-line n)
22672 ;; `move-beginning-of-line' may leave point after invisible
22673 ;; characters if line starts with such of these (e.g., with
22674 ;; a link at column 0). Really move to the beginning of the
22675 ;; current visible line.
22676 (beginning-of-line))
22677 (cond
22678 ;; No special behavior. Point is already at the beginning of
22679 ;; a line, logical or visual.
22680 ((not special))
22681 ;; `beginning-of-visual-line' left point before logical beginning
22682 ;; of line: point is at the beginning of a visual line. Bail
22683 ;; out.
22684 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22685 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22686 ;; At a headline, special position is before the title, but
22687 ;; after any TODO keyword or priority cookie.
22688 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22689 (line-end-position)))
22690 (bol (point)))
22691 (if (eq special 'reversed)
22692 (when (and (= origin bol) (eq last-command this-command))
22693 (goto-char refpos))
22694 (when (or (> origin refpos) (= origin bol))
22695 (goto-char refpos)))))
22696 ((and (looking-at org-list-full-item-re)
22697 (memq (org-element-type (save-match-data (org-element-at-point)))
22698 '(item plain-list)))
22699 ;; Set special position at first white space character after
22700 ;; bullet, and check-box, if any.
22701 (let ((after-bullet
22702 (let ((box (match-end 3)))
22703 (cond ((not box) (match-end 1))
22704 ((eq (char-after box) ?\s) (1+ box))
22705 (t box)))))
22706 (if (eq special 'reversed)
22707 (when (and (= (point) origin) (eq last-command this-command))
22708 (goto-char after-bullet))
22709 (when (or (> origin after-bullet) (= (point) origin))
22710 (goto-char after-bullet)))))
22711 ;; No special context. Point is already at beginning of line.
22712 (t nil))))
22714 (defun org-end-of-line (&optional n)
22715 "Go to the end of the line, but before ellipsis, if any.
22717 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22718 tags on the first attempt, and only move to after the tags when
22719 the cursor is already beyond the end of the headline.
22721 With argument N not nil or 1, move forward N - 1 lines first."
22722 (interactive "^p")
22723 (let ((origin (point))
22724 (special (pcase org-special-ctrl-a/e
22725 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22726 deactivate-mark)
22727 ;; First move to a visible line.
22728 (if (bound-and-true-p visual-line-mode)
22729 (beginning-of-visual-line n)
22730 (move-beginning-of-line n))
22731 (cond
22732 ;; At a headline, with tags.
22733 ((and special
22734 (save-excursion
22735 (beginning-of-line)
22736 (let ((case-fold-search nil))
22737 (looking-at org-complex-heading-regexp)))
22738 (match-end 5))
22739 (let ((tags (save-excursion
22740 (goto-char (match-beginning 5))
22741 (skip-chars-backward " \t")
22742 (point)))
22743 (visual-end (and (bound-and-true-p visual-line-mode)
22744 (save-excursion
22745 (end-of-visual-line)
22746 (point)))))
22747 ;; If `end-of-visual-line' brings us before end of line or
22748 ;; even tags, i.e., the headline spans over multiple visual
22749 ;; lines, move there.
22750 (cond ((and visual-end
22751 (< visual-end tags)
22752 (<= origin visual-end))
22753 (goto-char visual-end))
22754 ((eq special 'reversed)
22755 (if (and (= origin (line-end-position))
22756 (eq this-command last-command))
22757 (goto-char tags)
22758 (end-of-line)))
22760 (if (or (< origin tags) (= origin (line-end-position)))
22761 (goto-char tags)
22762 (end-of-line))))))
22763 ((bound-and-true-p visual-line-mode)
22764 (let ((bol (line-beginning-position)))
22765 (end-of-visual-line)
22766 ;; If `end-of-visual-line' gets us past the ellipsis at the
22767 ;; end of a line, backtrack and use `end-of-line' instead.
22768 (when (/= bol (line-beginning-position))
22769 (goto-char bol)
22770 (end-of-line))))
22771 (t (end-of-line)))))
22773 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22774 (define-key org-mode-map "\C-e" 'org-end-of-line)
22776 (defun org-backward-sentence (&optional _arg)
22777 "Go to beginning of sentence, or beginning of table field.
22778 This will call `backward-sentence' or `org-table-beginning-of-field',
22779 depending on context."
22780 (interactive)
22781 (let* ((element (org-element-at-point))
22782 (contents-begin (org-element-property :contents-begin element))
22783 (table (org-element-lineage element '(table) t)))
22784 (if (and table
22785 (> (point) contents-begin)
22786 (<= (point) (org-element-property :contents-end table)))
22787 (call-interactively #'org-table-beginning-of-field)
22788 (save-restriction
22789 (when (and contents-begin
22790 (< (point-min) contents-begin)
22791 (> (point) contents-begin))
22792 (narrow-to-region contents-begin
22793 (org-element-property :contents-end element)))
22794 (call-interactively #'backward-sentence)))))
22796 (defun org-forward-sentence (&optional _arg)
22797 "Go to end of sentence, or end of table field.
22798 This will call `forward-sentence' or `org-table-end-of-field',
22799 depending on context."
22800 (interactive)
22801 (if (and (org-at-heading-p)
22802 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22803 (save-restriction
22804 (narrow-to-region (line-beginning-position) (line-end-position))
22805 (call-interactively #'forward-sentence))
22806 (let* ((element (org-element-at-point))
22807 (contents-end (org-element-property :contents-end element))
22808 (table (org-element-lineage element '(table) t)))
22809 (if (and table
22810 (>= (point) (org-element-property :contents-begin table))
22811 (< (point) contents-end))
22812 (call-interactively #'org-table-end-of-field)
22813 (save-restriction
22814 (when (and contents-end
22815 (> (point-max) contents-end)
22816 ;; Skip blank lines between elements.
22817 (< (org-element-property :end element)
22818 (save-excursion (goto-char contents-end)
22819 (skip-chars-forward " \r\t\n"))))
22820 (narrow-to-region (org-element-property :contents-begin element)
22821 contents-end))
22822 ;; End of heading is considered as the end of a sentence.
22823 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22824 (call-interactively #'forward-sentence)))))))
22826 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22827 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22829 (defun org-kill-line (&optional _arg)
22830 "Kill line, to tags or end of line."
22831 (interactive)
22832 (cond
22833 ((or (not org-special-ctrl-k)
22834 (bolp)
22835 (not (org-at-heading-p)))
22836 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22837 org-ctrl-k-protect-subtree
22838 (or (eq org-ctrl-k-protect-subtree 'error)
22839 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22840 (user-error "C-k aborted as it would kill a hidden subtree"))
22841 (call-interactively
22842 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22843 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
22844 (kill-region (point) (match-beginning 1))
22845 (org-set-tags nil t))
22846 (t (kill-region (point) (point-at-eol)))))
22848 (define-key org-mode-map "\C-k" 'org-kill-line)
22850 (defun org-yank (&optional arg)
22851 "Yank. If the kill is a subtree, treat it specially.
22852 This command will look at the current kill and check if is a single
22853 subtree, or a series of subtrees[1]. If it passes the test, and if the
22854 cursor is at the beginning of a line or after the stars of a currently
22855 empty headline, then the yank is handled specially. How exactly depends
22856 on the value of the following variables.
22858 `org-yank-folded-subtrees'
22859 By default, this variable is non-nil, which results in
22860 subtree(s) being folded after insertion, except if doing so
22861 would swallow text after the yanked text.
22863 `org-yank-adjusted-subtrees'
22864 When non-nil (the default value is nil), the subtree will be
22865 promoted or demoted in order to fit into the local outline tree
22866 structure, which means that the level will be adjusted so that it
22867 becomes the smaller one of the two *visible* surrounding headings.
22869 Any prefix to this command will cause `yank' to be called directly with
22870 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22871 will just
22872 plainly yank the text as it is.
22874 \[1] The test checks if the first non-white line is a heading
22875 and if there are no other headings with fewer stars."
22876 (interactive "P")
22877 (org-yank-generic 'yank arg))
22879 (defun org-yank-generic (command arg)
22880 "Perform some yank-like command.
22882 This function implements the behavior described in the `org-yank'
22883 documentation. However, it has been generalized to work for any
22884 interactive command with similar behavior."
22886 ;; pretend to be command COMMAND
22887 (setq this-command command)
22889 (if arg
22890 (call-interactively command)
22892 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22893 (and (org-kill-is-subtree-p)
22894 (or (bolp)
22895 (and (looking-at "[ \t]*$")
22896 (string-match
22897 "\\`\\*+\\'"
22898 (buffer-substring (point-at-bol) (point)))))))
22899 swallowp)
22900 (cond
22901 ((and subtreep org-yank-folded-subtrees)
22902 (let ((beg (point))
22903 end)
22904 (if (and subtreep org-yank-adjusted-subtrees)
22905 (org-paste-subtree nil nil 'for-yank)
22906 (call-interactively command))
22908 (setq end (point))
22909 (goto-char beg)
22910 (when (and (bolp) subtreep
22911 (not (setq swallowp
22912 (org-yank-folding-would-swallow-text beg end))))
22913 (org-with-limited-levels
22914 (or (looking-at org-outline-regexp)
22915 (re-search-forward org-outline-regexp-bol end t))
22916 (while (and (< (point) end) (looking-at org-outline-regexp))
22917 (outline-hide-subtree)
22918 (org-cycle-show-empty-lines 'folded)
22919 (condition-case nil
22920 (outline-forward-same-level 1)
22921 (error (goto-char end))))))
22922 (when swallowp
22923 (message
22924 "Inserted text not folded because that would swallow text"))
22926 (goto-char end)
22927 (skip-chars-forward " \t\n\r")
22928 (beginning-of-line 1)
22929 (push-mark beg 'nomsg)))
22930 ((and subtreep org-yank-adjusted-subtrees)
22931 (let ((beg (point-at-bol)))
22932 (org-paste-subtree nil nil 'for-yank)
22933 (push-mark beg 'nomsg)))
22935 (call-interactively command))))))
22937 (defun org-yank-folding-would-swallow-text (beg end)
22938 "Would hide-subtree at BEG swallow any text after END?"
22939 (let (level)
22940 (org-with-limited-levels
22941 (save-excursion
22942 (goto-char beg)
22943 (when (or (looking-at org-outline-regexp)
22944 (re-search-forward org-outline-regexp-bol end t))
22945 (setq level (org-outline-level)))
22946 (goto-char end)
22947 (skip-chars-forward " \t\r\n\v\f")
22948 (not (or (eobp)
22949 (and (bolp) (looking-at-p org-outline-regexp)
22950 (<= (org-outline-level) level))))))))
22952 (define-key org-mode-map "\C-y" 'org-yank)
22954 (defun org-back-to-heading (&optional invisible-ok)
22955 "Call `outline-back-to-heading', but provide a better error message."
22956 (condition-case nil
22957 (outline-back-to-heading invisible-ok)
22958 (error (error "Before first headline at position %d in buffer %s"
22959 (point) (current-buffer)))))
22961 (defun org-before-first-heading-p ()
22962 "Before first heading?"
22963 (save-excursion
22964 (end-of-line)
22965 (null (re-search-backward org-outline-regexp-bol nil t))))
22967 (defun org-at-heading-p (&optional ignored)
22968 (outline-on-heading-p t))
22970 (defun org-in-commented-heading-p (&optional no-inheritance)
22971 "Non-nil if point is under a commented heading.
22972 This function also checks ancestors of the current headline,
22973 unless optional argument NO-INHERITANCE is non-nil."
22974 (cond
22975 ((org-before-first-heading-p) nil)
22976 ((let ((headline (nth 4 (org-heading-components))))
22977 (and headline
22978 (let ((case-fold-search nil))
22979 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22980 headline)))))
22981 (no-inheritance nil)
22983 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22985 (defun org-at-comment-p nil
22986 "Is cursor in a commented line?"
22987 (save-excursion
22988 (save-match-data
22989 (beginning-of-line)
22990 (looking-at "^[ \t]*# "))))
22992 (defun org-at-drawer-p nil
22993 "Is cursor at a drawer keyword?"
22994 (save-excursion
22995 (move-beginning-of-line 1)
22996 (looking-at org-drawer-regexp)))
22998 (defun org-at-block-p nil
22999 "Is cursor at a block keyword?"
23000 (save-excursion
23001 (move-beginning-of-line 1)
23002 (looking-at org-block-regexp)))
23004 (defun org-point-at-end-of-empty-headline ()
23005 "If point is at the end of an empty headline, return t, else nil.
23006 If the heading only contains a TODO keyword, it is still still considered
23007 empty."
23008 (let ((case-fold-search nil))
23009 (and (looking-at "[ \t]*$")
23010 org-todo-line-regexp
23011 (save-excursion
23012 (beginning-of-line)
23013 (looking-at org-todo-line-regexp)
23014 (string= (match-string 3) "")))))
23016 (defun org-at-heading-or-item-p ()
23017 (or (org-at-heading-p) (org-at-item-p)))
23019 (defun org-at-target-p ()
23020 (or (org-in-regexp org-radio-target-regexp)
23021 (org-in-regexp org-target-regexp)))
23022 ;; Compatibility alias with Org versions < 7.8.03
23023 (defalias 'org-on-target-p 'org-at-target-p)
23025 (defun org-up-heading-all (arg)
23026 "Move to the heading line of which the present line is a subheading.
23027 This function considers both visible and invisible heading lines.
23028 With argument, move up ARG levels."
23029 (outline-up-heading arg t))
23031 (defun org-up-heading-safe ()
23032 "Move to the heading line of which the present line is a subheading.
23033 This version will not throw an error. It will return the level of the
23034 headline found, or nil if no higher level is found.
23036 Also, this function will be a lot faster than `outline-up-heading',
23037 because it relies on stars being the outline starters. This can really
23038 make a significant difference in outlines with very many siblings."
23039 (when (ignore-errors (org-back-to-heading t))
23040 (let ((level-up (1- (funcall outline-level))))
23041 (and (> level-up 0)
23042 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23043 (funcall outline-level)))))
23045 (defun org-first-sibling-p ()
23046 "Is this heading the first child of its parents?"
23047 (interactive)
23048 (let ((re org-outline-regexp-bol)
23049 level l)
23050 (unless (org-at-heading-p t)
23051 (user-error "Not at a heading"))
23052 (setq level (funcall outline-level))
23053 (save-excursion
23054 (if (not (re-search-backward re nil t))
23056 (setq l (funcall outline-level))
23057 (< l level)))))
23059 (defun org-goto-sibling (&optional previous)
23060 "Goto the next sibling, even if it is invisible.
23061 When PREVIOUS is set, go to the previous sibling instead. Returns t
23062 when a sibling was found. When none is found, return nil and don't
23063 move point."
23064 (let ((fun (if previous 're-search-backward 're-search-forward))
23065 (pos (point))
23066 (re org-outline-regexp-bol)
23067 level l)
23068 (when (ignore-errors (org-back-to-heading t))
23069 (setq level (funcall outline-level))
23070 (catch 'exit
23071 (or previous (forward-char 1))
23072 (while (funcall fun re nil t)
23073 (setq l (funcall outline-level))
23074 (when (< l level) (goto-char pos) (throw 'exit nil))
23075 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23076 (goto-char pos)
23077 nil))))
23079 (defun org-show-siblings ()
23080 "Show all siblings of the current headline."
23081 (save-excursion
23082 (while (org-goto-sibling) (org-flag-heading nil)))
23083 (save-excursion
23084 (while (org-goto-sibling 'previous)
23085 (org-flag-heading nil))))
23087 (defun org-goto-first-child ()
23088 "Goto the first child, even if it is invisible.
23089 Return t when a child was found. Otherwise don't move point and
23090 return nil."
23091 (let (level (pos (point)) (re org-outline-regexp-bol))
23092 (when (ignore-errors (org-back-to-heading t))
23093 (setq level (outline-level))
23094 (forward-char 1)
23095 (if (and (re-search-forward re nil t) (> (outline-level) level))
23096 (progn (goto-char (match-beginning 0)) t)
23097 (goto-char pos) nil))))
23099 (defun org-show-hidden-entry ()
23100 "Show an entry where even the heading is hidden."
23101 (save-excursion
23102 (org-show-entry)))
23104 (defun org-flag-heading (flag &optional entry)
23105 "Flag the current heading. FLAG non-nil means make invisible.
23106 When ENTRY is non-nil, show the entire entry."
23107 (save-excursion
23108 (org-back-to-heading t)
23109 ;; Check if we should show the entire entry
23110 (if (not entry)
23111 (org-flag-region
23112 (line-end-position 0) (line-end-position) flag 'outline)
23113 (org-show-entry)
23114 (save-excursion
23115 (and (outline-next-heading)
23116 (org-flag-heading nil))))))
23118 (defun org-get-next-sibling ()
23119 "Move to next heading of the same level, and return point.
23120 If there is no such heading, return nil.
23121 This is like outline-next-sibling, but invisible headings are ok."
23122 (let ((level (funcall outline-level)))
23123 (outline-next-heading)
23124 (while (and (not (eobp)) (> (funcall outline-level) level))
23125 (outline-next-heading))
23126 (unless (or (eobp) (< (funcall outline-level) level))
23127 (point))))
23129 (defun org-get-last-sibling ()
23130 "Move to previous heading of the same level, and return point.
23131 If there is no such heading, return nil."
23132 (let ((opoint (point))
23133 (level (funcall outline-level)))
23134 (outline-previous-heading)
23135 (when (and (/= (point) opoint) (outline-on-heading-p t))
23136 (while (and (> (funcall outline-level) level)
23137 (not (bobp)))
23138 (outline-previous-heading))
23139 (unless (< (funcall outline-level) level)
23140 (point)))))
23142 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23143 "Goto to the end of a subtree."
23144 ;; This contains an exact copy of the original function, but it uses
23145 ;; `org-back-to-heading', to make it work also in invisible
23146 ;; trees. And is uses an invisible-ok argument.
23147 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23148 ;; Furthermore, when used inside Org, finding the end of a large subtree
23149 ;; with many children and grandchildren etc, this can be much faster
23150 ;; than the outline version.
23151 (org-back-to-heading invisible-ok)
23152 (let ((first t)
23153 (level (funcall outline-level)))
23154 (if (and (derived-mode-p 'org-mode) (< level 1000))
23155 ;; A true heading (not a plain list item), in Org
23156 ;; This means we can easily find the end by looking
23157 ;; only for the right number of stars. Using a regexp to do
23158 ;; this is so much faster than using a Lisp loop.
23159 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23160 (forward-char 1)
23161 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23162 ;; something else, do it the slow way
23163 (while (and (not (eobp))
23164 (or first (> (funcall outline-level) level)))
23165 (setq first nil)
23166 (outline-next-heading)))
23167 (unless to-heading
23168 (when (memq (preceding-char) '(?\n ?\^M))
23169 ;; Go to end of line before heading
23170 (forward-char -1)
23171 (when (memq (preceding-char) '(?\n ?\^M))
23172 ;; leave blank line before heading
23173 (forward-char -1)))))
23174 (point))
23176 (defun org-end-of-meta-data (&optional full)
23177 "Skip planning line and properties drawer in current entry.
23178 When optional argument FULL is non-nil, also skip empty lines,
23179 clocking lines and regular drawers at the beginning of the
23180 entry."
23181 (org-back-to-heading t)
23182 (forward-line)
23183 (when (looking-at-p org-planning-line-re) (forward-line))
23184 (when (looking-at org-property-drawer-re)
23185 (goto-char (match-end 0))
23186 (forward-line))
23187 (when (and full (not (org-at-heading-p)))
23188 (catch 'exit
23189 (let ((end (save-excursion (outline-next-heading) (point)))
23190 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23191 (while (not (eobp))
23192 (cond ((looking-at-p org-drawer-regexp)
23193 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23194 (forward-line)
23195 (throw 'exit t)))
23196 ((looking-at-p re) (forward-line))
23197 (t (throw 'exit t))))))))
23199 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23200 "Move forward to the ARG'th subheading at same level as this one.
23201 Stop at the first and last subheadings of a superior heading.
23202 Normally this only looks at visible headings, but when INVISIBLE-OK is
23203 non-nil it will also look at invisible ones."
23204 (interactive "p")
23205 (let ((backward? (and arg (< arg 0))))
23206 (if (org-before-first-heading-p)
23207 (if backward? (goto-char (point-min)) (outline-next-heading))
23208 (org-back-to-heading invisible-ok)
23209 (unless backward? (end-of-line)) ;do not match current headline
23210 (let ((level (- (match-end 0) (match-beginning 0) 1))
23211 (f (if backward? #'re-search-backward #'re-search-forward))
23212 (count (if arg (abs arg) 1))
23213 (result (point)))
23214 (while (and (> count 0)
23215 (funcall f org-outline-regexp-bol nil 'move))
23216 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23217 (cond ((< l level) (setq count 0))
23218 ((and (= l level)
23219 (or invisible-ok
23220 (not (org-invisible-p
23221 (line-beginning-position)))))
23222 (cl-decf count)
23223 (when (= l level) (setq result (point)))))))
23224 (goto-char result))
23225 (beginning-of-line))))
23227 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23228 "Move backward to the ARG'th subheading at same level as this one.
23229 Stop at the first and last subheadings of a superior heading."
23230 (interactive "p")
23231 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23233 (defun org-next-visible-heading (arg)
23234 "Move to the next visible heading.
23236 This function wraps `outline-next-visible-heading' with
23237 `org-with-limited-levels' in order to skip over inline tasks and
23238 respect customization of `org-odd-levels-only'."
23239 (interactive "p")
23240 (org-with-limited-levels
23241 (outline-next-visible-heading arg)))
23243 (defun org-previous-visible-heading (arg)
23244 "Move to the previous visible heading.
23246 This function wraps `outline-previous-visible-heading' with
23247 `org-with-limited-levels' in order to skip over inline tasks and
23248 respect customization of `org-odd-levels-only'."
23249 (interactive "p")
23250 (org-with-limited-levels
23251 (outline-previous-visible-heading arg)))
23253 (defun org-forward-paragraph ()
23254 "Move forward to beginning of next paragraph or equivalent.
23256 The function moves point to the beginning of the next visible
23257 structural element, which can be a paragraph, a table, a list
23258 item, etc. It also provides some special moves for convenience:
23260 - On an affiliated keyword, jump to the beginning of the
23261 relative element.
23262 - On an item or a footnote definition, move to the second
23263 element inside, if any.
23264 - On a table or a property drawer, jump after it.
23265 - On a verse or source block, stop after blank lines."
23266 (interactive)
23267 (unless (eobp)
23268 (let* ((deactivate-mark nil)
23269 (element (org-element-at-point))
23270 (type (org-element-type element))
23271 (post-affiliated (org-element-property :post-affiliated element))
23272 (contents-begin (org-element-property :contents-begin element))
23273 (contents-end (org-element-property :contents-end element))
23274 (end (let ((end (org-element-property :end element)) (parent element))
23275 (while (and (setq parent (org-element-property :parent parent))
23276 (= (org-element-property :contents-end parent) end))
23277 (setq end (org-element-property :end parent)))
23278 end)))
23279 (cond ((not element)
23280 (skip-chars-forward " \r\t\n")
23281 (or (eobp) (beginning-of-line)))
23282 ;; On affiliated keywords, move to element's beginning.
23283 ((< (point) post-affiliated)
23284 (goto-char post-affiliated))
23285 ;; At a table row, move to the end of the table. Similarly,
23286 ;; at a node property, move to the end of the property
23287 ;; drawer.
23288 ((memq type '(node-property table-row))
23289 (goto-char (org-element-property
23290 :end (org-element-property :parent element))))
23291 ((memq type '(property-drawer table)) (goto-char end))
23292 ;; Consider blank lines as separators in verse and source
23293 ;; blocks to ease editing.
23294 ((memq type '(src-block verse-block))
23295 (when (eq type 'src-block)
23296 (setq contents-end
23297 (save-excursion (goto-char end)
23298 (skip-chars-backward " \r\t\n")
23299 (line-beginning-position))))
23300 (beginning-of-line)
23301 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23302 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23303 (goto-char end)
23304 (skip-chars-forward " \r\t\n")
23305 (if (= (point) contents-end) (goto-char end)
23306 (beginning-of-line))))
23307 ;; With no contents, just skip element.
23308 ((not contents-begin) (goto-char end))
23309 ;; If contents are invisible, skip the element altogether.
23310 ((org-invisible-p (line-end-position))
23311 (cl-case type
23312 (headline
23313 (org-with-limited-levels (outline-next-visible-heading 1)))
23314 ;; At a plain list, make sure we move to the next item
23315 ;; instead of skipping the whole list.
23316 (plain-list (forward-char)
23317 (org-forward-paragraph))
23318 (otherwise (goto-char end))))
23319 ((>= (point) contents-end) (goto-char end))
23320 ((>= (point) contents-begin)
23321 ;; This can only happen on paragraphs and plain lists.
23322 (cl-case type
23323 (paragraph (goto-char end))
23324 ;; At a plain list, try to move to second element in
23325 ;; first item, if possible.
23326 (plain-list (end-of-line)
23327 (org-forward-paragraph))))
23328 ;; When contents start on the middle of a line (e.g. in
23329 ;; items and footnote definitions), try to reach first
23330 ;; element starting after current line.
23331 ((> (line-end-position) contents-begin)
23332 (end-of-line)
23333 (org-forward-paragraph))
23334 (t (goto-char contents-begin))))))
23336 (defun org-backward-paragraph ()
23337 "Move backward to start of previous paragraph or equivalent.
23339 The function moves point to the beginning of the current
23340 structural element, which can be a paragraph, a table, a list
23341 item, etc., or to the beginning of the previous visible one if
23342 point is already there. It also provides some special moves for
23343 convenience:
23345 - On an affiliated keyword, jump to the first one.
23346 - On a table or a property drawer, move to its beginning.
23347 - On comment, example, export, src and verse blocks, stop
23348 before blank lines."
23349 (interactive)
23350 (unless (bobp)
23351 (let* ((deactivate-mark nil)
23352 (element (org-element-at-point))
23353 (type (org-element-type element))
23354 (contents-end (org-element-property :contents-end element))
23355 (post-affiliated (org-element-property :post-affiliated element))
23356 (begin (org-element-property :begin element))
23357 (special? ;blocks handled specially
23358 (memq type '(comment-block example-block export-block src-block
23359 verse-block)))
23360 (contents-begin
23361 (if special?
23362 ;; These types have no proper contents. Fake line
23363 ;; below the block opening line as contents beginning.
23364 (save-excursion (goto-char begin) (line-beginning-position 2))
23365 (org-element-property :contents-begin element))))
23366 (cond
23367 ((not element) (goto-char (point-min)))
23368 ((= (point) begin)
23369 (backward-char)
23370 (org-backward-paragraph))
23371 ((<= (point) post-affiliated) (goto-char begin))
23372 ;; Special behavior: on a table or a property drawer, move to
23373 ;; its beginning.
23374 ((memq type '(node-property table-row))
23375 (goto-char (org-element-property
23376 :post-affiliated (org-element-property :parent element))))
23377 (special?
23378 (if (<= (point) contents-begin) (goto-char post-affiliated)
23379 ;; Inside a verse block, see blank lines as paragraph
23380 ;; separators.
23381 (let ((origin (point)))
23382 (skip-chars-backward " \r\t\n" contents-begin)
23383 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23384 (skip-chars-forward " \r\t\n" origin)
23385 (if (= (point) origin) (goto-char contents-begin)
23386 (beginning-of-line))))))
23387 ((eq type 'paragraph) (goto-char contents-begin)
23388 ;; When at first paragraph in an item or a footnote definition,
23389 ;; move directly to beginning of line.
23390 (let ((parent-contents
23391 (org-element-property
23392 :contents-begin (org-element-property :parent element))))
23393 (when (and parent-contents (= parent-contents contents-begin))
23394 (beginning-of-line))))
23395 ;; At the end of a greater element, move to the beginning of
23396 ;; the last element within.
23397 ((and contents-end (>= (point) contents-end))
23398 (goto-char (1- contents-end))
23399 (org-backward-paragraph))
23400 (t (goto-char (or post-affiliated begin))))
23401 ;; Ensure we never leave point invisible.
23402 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23404 (defun org-forward-element ()
23405 "Move forward by one element.
23406 Move to the next element at the same level, when possible."
23407 (interactive)
23408 (cond ((eobp) (user-error "Cannot move further down"))
23409 ((org-with-limited-levels (org-at-heading-p))
23410 (let ((origin (point)))
23411 (goto-char (org-end-of-subtree nil t))
23412 (unless (org-with-limited-levels (org-at-heading-p))
23413 (goto-char origin)
23414 (user-error "Cannot move further down"))))
23416 (let* ((elem (org-element-at-point))
23417 (end (org-element-property :end elem))
23418 (parent (org-element-property :parent elem)))
23419 (cond ((and parent (= (org-element-property :contents-end parent) end))
23420 (goto-char (org-element-property :end parent)))
23421 ((integer-or-marker-p end) (goto-char end))
23422 (t (message "No element at point")))))))
23424 (defun org-backward-element ()
23425 "Move backward by one element.
23426 Move to the previous element at the same level, when possible."
23427 (interactive)
23428 (cond ((bobp) (user-error "Cannot move further up"))
23429 ((org-with-limited-levels (org-at-heading-p))
23430 ;; At a headline, move to the previous one, if any, or stay
23431 ;; here.
23432 (let ((origin (point)))
23433 (org-with-limited-levels (org-backward-heading-same-level 1))
23434 ;; When current headline has no sibling above, move to its
23435 ;; parent.
23436 (when (= (point) origin)
23437 (or (org-with-limited-levels (org-up-heading-safe))
23438 (progn (goto-char origin)
23439 (user-error "Cannot move further up"))))))
23441 (let* ((elem (org-element-at-point))
23442 (beg (org-element-property :begin elem)))
23443 (cond
23444 ;; Move to beginning of current element if point isn't
23445 ;; there already.
23446 ((null beg) (message "No element at point"))
23447 ((/= (point) beg) (goto-char beg))
23448 (t (goto-char beg)
23449 (skip-chars-backward " \r\t\n")
23450 (unless (bobp)
23451 (let ((prev (org-element-at-point)))
23452 (goto-char (org-element-property :begin prev))
23453 (while (and (setq prev (org-element-property :parent prev))
23454 (<= (org-element-property :end prev) beg))
23455 (goto-char (org-element-property :begin prev)))))))))))
23457 (defun org-up-element ()
23458 "Move to upper element."
23459 (interactive)
23460 (if (org-with-limited-levels (org-at-heading-p))
23461 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23462 (let* ((elem (org-element-at-point))
23463 (parent (org-element-property :parent elem)))
23464 (if parent (goto-char (org-element-property :begin parent))
23465 (if (org-with-limited-levels (org-before-first-heading-p))
23466 (user-error "No surrounding element")
23467 (org-with-limited-levels (org-back-to-heading)))))))
23469 (defun org-down-element ()
23470 "Move to inner element."
23471 (interactive)
23472 (let ((element (org-element-at-point)))
23473 (cond
23474 ((memq (org-element-type element) '(plain-list table))
23475 (goto-char (org-element-property :contents-begin element))
23476 (forward-char))
23477 ((memq (org-element-type element) org-element-greater-elements)
23478 ;; If contents are hidden, first disclose them.
23479 (when (org-invisible-p (line-end-position)) (org-cycle))
23480 (goto-char (or (org-element-property :contents-begin element)
23481 (user-error "No content for this element"))))
23482 (t (user-error "No inner element")))))
23484 (defun org-drag-element-backward ()
23485 "Move backward element at point."
23486 (interactive)
23487 (let ((elem (or (org-element-at-point)
23488 (user-error "No element at point"))))
23489 (if (eq (org-element-type elem) 'headline)
23490 ;; Preserve point when moving a whole tree, even if point was
23491 ;; on blank lines below the headline.
23492 (let ((offset (skip-chars-backward " \t\n")))
23493 (unwind-protect (org-move-subtree-up)
23494 (forward-char (- offset))))
23495 (let ((prev-elem
23496 (save-excursion
23497 (goto-char (org-element-property :begin elem))
23498 (skip-chars-backward " \r\t\n")
23499 (unless (bobp)
23500 (let* ((beg (org-element-property :begin elem))
23501 (prev (org-element-at-point))
23502 (up prev))
23503 (while (and (setq up (org-element-property :parent up))
23504 (<= (org-element-property :end up) beg))
23505 (setq prev up))
23506 prev)))))
23507 ;; Error out if no previous element or previous element is
23508 ;; a parent of the current one.
23509 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23510 (user-error "Cannot drag element backward")
23511 (let ((pos (point)))
23512 (org-element-swap-A-B prev-elem elem)
23513 (goto-char (+ (org-element-property :begin prev-elem)
23514 (- pos (org-element-property :begin elem))))))))))
23516 (defun org-drag-element-forward ()
23517 "Move forward element at point."
23518 (interactive)
23519 (let* ((pos (point))
23520 (elem (or (org-element-at-point)
23521 (user-error "No element at point"))))
23522 (when (= (point-max) (org-element-property :end elem))
23523 (user-error "Cannot drag element forward"))
23524 (goto-char (org-element-property :end elem))
23525 (let ((next-elem (org-element-at-point)))
23526 (when (or (org-element-nested-p elem next-elem)
23527 (and (eq (org-element-type next-elem) 'headline)
23528 (not (eq (org-element-type elem) 'headline))))
23529 (goto-char pos)
23530 (user-error "Cannot drag element forward"))
23531 ;; Compute new position of point: it's shifted by NEXT-ELEM
23532 ;; body's length (without final blanks) and by the length of
23533 ;; blanks between ELEM and NEXT-ELEM.
23534 (let ((size-next (- (save-excursion
23535 (goto-char (org-element-property :end next-elem))
23536 (skip-chars-backward " \r\t\n")
23537 (forward-line)
23538 ;; Small correction if buffer doesn't end
23539 ;; with a newline character.
23540 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23541 (org-element-property :begin next-elem)))
23542 (size-blank (- (org-element-property :end elem)
23543 (save-excursion
23544 (goto-char (org-element-property :end elem))
23545 (skip-chars-backward " \r\t\n")
23546 (forward-line)
23547 (point)))))
23548 (org-element-swap-A-B elem next-elem)
23549 (goto-char (+ pos size-next size-blank))))))
23551 (defun org-drag-line-forward (arg)
23552 "Drag the line at point ARG lines forward."
23553 (interactive "p")
23554 (dotimes (_ (abs arg))
23555 (let ((c (current-column)))
23556 (if (< 0 arg)
23557 (progn
23558 (beginning-of-line 2)
23559 (transpose-lines 1)
23560 (beginning-of-line 0))
23561 (transpose-lines 1)
23562 (beginning-of-line -1))
23563 (org-move-to-column c))))
23565 (defun org-drag-line-backward (arg)
23566 "Drag the line at point ARG lines backward."
23567 (interactive "p")
23568 (org-drag-line-forward (- arg)))
23570 (defun org-mark-element ()
23571 "Put point at beginning of this element, mark at end.
23573 Interactively, if this command is repeated or (in Transient Mark
23574 mode) if the mark is active, it marks the next element after the
23575 ones already marked."
23576 (interactive)
23577 (let (deactivate-mark)
23578 (if (and (called-interactively-p 'any)
23579 (or (and (eq last-command this-command) (mark t))
23580 (and transient-mark-mode mark-active)))
23581 (set-mark
23582 (save-excursion
23583 (goto-char (mark))
23584 (goto-char (org-element-property :end (org-element-at-point)))))
23585 (let ((element (org-element-at-point)))
23586 (end-of-line)
23587 (push-mark (org-element-property :end element) t t)
23588 (goto-char (org-element-property :begin element))))))
23590 (defun org-narrow-to-element ()
23591 "Narrow buffer to current element."
23592 (interactive)
23593 (let ((elem (org-element-at-point)))
23594 (cond
23595 ((eq (car elem) 'headline)
23596 (narrow-to-region
23597 (org-element-property :begin elem)
23598 (org-element-property :end elem)))
23599 ((memq (car elem) org-element-greater-elements)
23600 (narrow-to-region
23601 (org-element-property :contents-begin elem)
23602 (org-element-property :contents-end elem)))
23604 (narrow-to-region
23605 (org-element-property :begin elem)
23606 (org-element-property :end elem))))))
23608 (defun org-transpose-element ()
23609 "Transpose current and previous elements, keeping blank lines between.
23610 Point is moved after both elements."
23611 (interactive)
23612 (org-skip-whitespace)
23613 (let ((end (org-element-property :end (org-element-at-point))))
23614 (org-drag-element-backward)
23615 (goto-char end)))
23617 (defun org-unindent-buffer ()
23618 "Un-indent the visible part of the buffer.
23619 Relative indentation (between items, inside blocks, etc.) isn't
23620 modified."
23621 (interactive)
23622 (unless (eq major-mode 'org-mode)
23623 (user-error "Cannot un-indent a buffer not in Org mode"))
23624 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23625 (unindent-tree
23626 (lambda (contents)
23627 (dolist (element (reverse contents))
23628 (if (memq (org-element-type element) '(headline section))
23629 (funcall unindent-tree (org-element-contents element))
23630 (save-excursion
23631 (save-restriction
23632 (narrow-to-region
23633 (org-element-property :begin element)
23634 (org-element-property :end element))
23635 (org-do-remove-indentation))))))))
23636 (funcall unindent-tree (org-element-contents parse-tree))))
23638 (defun org-make-options-regexp (kwds &optional extra)
23639 "Make a regular expression for keyword lines.
23640 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23641 when non-nil, is a regexp matching keywords names."
23642 (concat "^[ \t]*#\\+\\("
23643 (regexp-opt kwds)
23644 (and extra (concat (and kwds "\\|") extra))
23645 "\\):[ \t]*\\(.*\\)"))
23648 ;;; Finish up
23650 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23651 (lambda () (add-hook 'change-major-mode-hook
23652 'org-show-all 'append 'local)))
23654 (provide 'org)
23656 (run-hooks 'org-load-hook)
23658 ;;; org.el ends here