Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blobcf8073fc2e20ff92a22f808da7169849861ade7a
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 "\\({{{\\).+?\\(}}}\\)" limit t)
5977 (add-text-properties
5978 (match-beginning 0) (match-end 0)
5979 '(font-lock-fontified t face org-macro))
5980 (when org-hide-macro-markers
5981 (add-text-properties (match-end 2) (match-beginning 2)
5982 '(invisible t))
5983 (add-text-properties (match-beginning 1) (match-end 1)
5984 '(invisible t)))
5985 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5988 (defun org-activate-footnote-links (limit)
5989 "Add text properties for footnotes."
5990 (let ((fn (org-footnote-next-reference-or-definition limit)))
5991 (when fn
5992 (let* ((beg (nth 1 fn))
5993 (end (nth 2 fn))
5994 (label (car fn))
5995 (referencep (/= (line-beginning-position) beg)))
5996 (when (and referencep (nth 3 fn))
5997 (save-excursion
5998 (goto-char beg)
5999 (search-forward (or label "fn:"))
6000 (org-remove-flyspell-overlays-in beg (match-end 0))))
6001 (add-text-properties beg end
6002 (list 'mouse-face 'highlight
6003 'keymap org-mouse-map
6004 'help-echo
6005 (if referencep "Footnote reference"
6006 "Footnote definition")
6007 'font-lock-fontified t
6008 'font-lock-multiline t
6009 'face 'org-footnote))))))
6011 (defun org-activate-dates (limit)
6012 "Add text properties for dates."
6013 (when (and (re-search-forward org-tsr-regexp-both limit t)
6014 (not (equal (char-before (match-beginning 0)) 91)))
6015 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6016 (add-text-properties (match-beginning 0) (match-end 0)
6017 (list 'mouse-face 'highlight
6018 'keymap org-mouse-map))
6019 (org-rear-nonsticky-at (match-end 0))
6020 (when org-display-custom-times
6021 ;; If it's a date range, activate custom time for second date.
6022 (when (match-end 3)
6023 (org-display-custom-time (match-beginning 3) (match-end 3)))
6024 (org-display-custom-time (match-beginning 1) (match-end 1)))
6027 (defvar-local org-target-link-regexp nil
6028 "Regular expression matching radio targets in plain text.")
6030 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6031 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6032 border border border))
6033 "Regular expression matching a link target.")
6035 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6036 "Regular expression matching a radio target.")
6038 (defconst org-any-target-regexp
6039 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6040 "Regular expression matching any target.")
6042 (defun org-activate-target-links (limit)
6043 "Add text properties for target matches."
6044 (when org-target-link-regexp
6045 (let ((case-fold-search t))
6046 (when (re-search-forward org-target-link-regexp limit t)
6047 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6048 (add-text-properties (match-beginning 1) (match-end 1)
6049 (list 'mouse-face 'highlight
6050 'keymap org-mouse-map
6051 'help-echo "Radio target link"
6052 'org-linked-text t))
6053 (org-rear-nonsticky-at (match-end 1))
6054 t))))
6056 (defun org-update-radio-target-regexp ()
6057 "Find all radio targets in this file and update the regular expression.
6058 Also refresh fontification if needed."
6059 (interactive)
6060 (let ((old-regexp org-target-link-regexp)
6061 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6062 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6063 (targets
6064 (org-with-wide-buffer
6065 (goto-char (point-min))
6066 (let (rtn)
6067 (while (re-search-forward org-radio-target-regexp nil t)
6068 ;; Make sure point is really within the object.
6069 (backward-char)
6070 (let ((obj (org-element-context)))
6071 (when (eq (org-element-type obj) 'radio-target)
6072 (cl-pushnew (org-element-property :value obj) rtn
6073 :test #'equal))))
6074 rtn))))
6075 (setq org-target-link-regexp
6076 (and targets
6077 (concat before-re
6078 (mapconcat
6079 (lambda (x)
6080 (replace-regexp-in-string
6081 " +" "\\s-+" (regexp-quote x) t t))
6082 targets
6083 "\\|")
6084 after-re)))
6085 (unless (equal old-regexp org-target-link-regexp)
6086 ;; Clean-up cache.
6087 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6088 ((not org-target-link-regexp) old-regexp)
6090 (concat before-re
6091 (mapconcat
6092 (lambda (re)
6093 (substring re (length before-re)
6094 (- (length after-re))))
6095 (list old-regexp org-target-link-regexp)
6096 "\\|")
6097 after-re)))))
6098 (org-with-wide-buffer
6099 (goto-char (point-min))
6100 (while (re-search-forward regexp nil t)
6101 (org-element-cache-refresh (match-beginning 1)))))
6102 ;; Re fontify buffer.
6103 (when (memq 'radio org-highlight-links)
6104 (org-restart-font-lock)))))
6106 (defvar org-latex-and-related-regexp nil
6107 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6109 (defun org-compute-latex-and-related-regexp ()
6110 "Compute regular expression for LaTeX, entities and sub/superscript.
6111 Result depends on variable `org-highlight-latex-and-related'."
6112 (setq-local
6113 org-latex-and-related-regexp
6114 (let* ((re-sub
6115 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6116 ((eq org-use-sub-superscripts '{})
6117 (list org-match-substring-with-braces-regexp))
6118 (org-use-sub-superscripts (list org-match-substring-regexp))))
6119 (re-latex
6120 (when (memq 'latex org-highlight-latex-and-related)
6121 (let ((matchers (plist-get org-format-latex-options :matchers)))
6122 (delq nil
6123 (mapcar (lambda (x)
6124 (and (member (car x) matchers) (nth 1 x)))
6125 org-latex-regexps)))))
6126 (re-entities
6127 (when (memq 'entities org-highlight-latex-and-related)
6128 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6129 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6131 (defun org-do-latex-and-related (limit)
6132 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6133 LIMIT bounds the search for syntax to highlight. Stop at first
6134 highlighted object, if any. Return t if some highlighting was
6135 done, nil otherwise."
6136 (when (org-string-nw-p org-latex-and-related-regexp)
6137 (catch 'found
6138 (while (re-search-forward org-latex-and-related-regexp limit t)
6139 (unless
6140 (cl-some
6141 (lambda (f)
6142 (memq f '(org-code org-verbatim underline org-special-keyword)))
6143 (save-excursion
6144 (goto-char (1+ (match-beginning 0)))
6145 (face-at-point nil t)))
6146 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6147 '(?_ ?^))
6149 0)))
6150 (font-lock-prepend-text-property
6151 (+ offset (match-beginning 0)) (match-end 0)
6152 'face 'org-latex-and-related)
6153 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6154 '(font-lock-multiline t)))
6155 (throw 'found t)))
6156 nil)))
6158 (defun org-restart-font-lock ()
6159 "Restart `font-lock-mode', to force refontification."
6160 (when (and (boundp 'font-lock-mode) font-lock-mode)
6161 (font-lock-mode -1)
6162 (font-lock-mode 1)))
6164 (defun org-activate-tags (limit)
6165 (when (re-search-forward
6166 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6167 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6168 (add-text-properties (match-beginning 1) (match-end 1)
6169 (list 'mouse-face 'highlight
6170 'keymap org-mouse-map))
6171 (org-rear-nonsticky-at (match-end 1))
6174 (defun org-outline-level ()
6175 "Compute the outline level of the heading at point.
6177 If this is called at a normal headline, the level is the number
6178 of stars. Use `org-reduced-level' to remove the effect of
6179 `org-odd-levels'. Unlike to `org-current-level', this function
6180 takes into consideration inlinetasks."
6181 (org-with-wide-buffer
6182 (end-of-line)
6183 (if (re-search-backward org-outline-regexp-bol nil t)
6184 (1- (- (match-end 0) (match-beginning 0)))
6185 0)))
6187 (defvar org-font-lock-keywords nil)
6189 (defsubst org-re-property (property &optional literal allow-null value)
6190 "Return a regexp matching a PROPERTY line.
6192 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6193 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6194 non-nil, match properties even without a value.
6196 Match group 3 is set to the value when it exists. If there is no
6197 value and ALLOW-NULL is non-nil, it is set to the empty string.
6199 With optional argument VALUE, match only property lines with
6200 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6201 unless LITERAL is non-nil."
6202 (concat
6203 "^\\(?4:[ \t]*\\)"
6204 (format "\\(?1::\\(?2:%s\\):\\)"
6205 (if literal property (regexp-quote property)))
6206 (cond (value
6207 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6208 (if literal value (regexp-quote value))))
6209 (allow-null
6210 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6212 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6214 (defconst org-property-re
6215 (org-re-property "\\S-+" 'literal t)
6216 "Regular expression matching a property line.
6217 There are four matching groups:
6218 1: :PROPKEY: including the leading and trailing colon,
6219 2: PROPKEY without the leading and trailing colon,
6220 3: PROPVAL without leading or trailing spaces,
6221 4: the indentation of the current line,
6222 5: trailing whitespace.")
6224 (defvar org-font-lock-hook nil
6225 "Functions to be called for special font lock stuff.")
6227 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6229 (defvar org-font-lock-set-keywords-hook nil
6230 "Functions that can manipulate `org-font-lock-extra-keywords'.
6231 This is called after `org-font-lock-extra-keywords' is defined, but before
6232 it is installed to be used by font lock. This can be useful if something
6233 needs to be inserted at a specific position in the font-lock sequence.")
6235 (defun org-font-lock-hook (limit)
6236 "Run `org-font-lock-hook' within LIMIT."
6237 (run-hook-with-args 'org-font-lock-hook limit))
6239 (defun org-set-font-lock-defaults ()
6240 "Set font lock defaults for the current buffer."
6241 (let* ((em org-fontify-emphasized-text)
6242 (lk org-highlight-links)
6243 (org-font-lock-extra-keywords
6244 (list
6245 ;; Call the hook
6246 '(org-font-lock-hook)
6247 ;; Headlines
6248 `(,(if org-fontify-whole-heading-line
6249 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6250 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6251 (1 (org-get-level-face 1))
6252 (2 (org-get-level-face 2))
6253 (3 (org-get-level-face 3)))
6254 ;; Table lines
6255 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6256 (1 'org-table t))
6257 ;; Table internals
6258 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6259 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6260 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6261 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6262 ;; Drawers
6263 '(org-fontify-drawers)
6264 ;; Properties
6265 (list org-property-re
6266 '(1 'org-special-keyword t)
6267 '(3 'org-property-value t))
6268 ;; Link related fontification.
6269 '(org-activate-links)
6270 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6271 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6272 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6273 (when (memq 'footnote lk) '(org-activate-footnote-links))
6274 ;; Targets.
6275 (list org-any-target-regexp '(0 'org-target t))
6276 ;; Diary sexps.
6277 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6278 ;; Macro
6279 '(org-fontify-macros)
6280 ;; TODO keyword
6281 (list (format org-heading-keyword-regexp-format
6282 org-todo-regexp)
6283 '(2 (org-get-todo-face 2) t))
6284 ;; DONE
6285 (if org-fontify-done-headline
6286 (list (format org-heading-keyword-regexp-format
6287 (concat
6288 "\\(?:"
6289 (mapconcat 'regexp-quote org-done-keywords "\\|")
6290 "\\)"))
6291 '(2 'org-headline-done t))
6292 nil)
6293 ;; Priorities
6294 '(org-font-lock-add-priority-faces)
6295 ;; Tags
6296 '(org-font-lock-add-tag-faces)
6297 ;; Tags groups
6298 (when (and org-group-tags org-tag-groups-alist)
6299 (list (concat org-outline-regexp-bol ".+\\(:"
6300 (regexp-opt (mapcar 'car org-tag-groups-alist))
6301 ":\\).*$")
6302 '(1 'org-tag-group prepend)))
6303 ;; Special keywords
6304 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6305 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6306 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6307 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6308 ;; Emphasis
6309 (when em '(org-do-emphasis-faces))
6310 ;; Checkboxes
6311 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6312 1 'org-checkbox prepend)
6313 (when (cdr (assq 'checkbox org-list-automatic-rules))
6314 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6315 (0 (org-get-checkbox-statistics-face) t)))
6316 ;; Description list items
6317 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6318 1 'org-list-dt prepend)
6319 ;; ARCHIVEd headings
6320 (list (concat
6321 org-outline-regexp-bol
6322 "\\(.*:" org-archive-tag ":.*\\)")
6323 '(1 'org-archived prepend))
6324 ;; Specials
6325 '(org-do-latex-and-related)
6326 '(org-fontify-entities)
6327 '(org-raise-scripts)
6328 ;; Code
6329 '(org-activate-code (1 'org-code t))
6330 ;; COMMENT
6331 (list (format
6332 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6333 org-todo-regexp
6334 org-comment-string)
6335 '(9 'org-special-keyword t))
6336 ;; Blocks and meta lines
6337 '(org-fontify-meta-lines-and-blocks))))
6338 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6339 (run-hooks 'org-font-lock-set-keywords-hook)
6340 ;; Now set the full font-lock-keywords
6341 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6342 (setq-local font-lock-defaults
6343 '(org-font-lock-keywords t nil nil backward-paragraph))
6344 (kill-local-variable 'font-lock-keywords)
6345 nil))
6347 (defun org-toggle-pretty-entities ()
6348 "Toggle the composition display of entities as UTF8 characters."
6349 (interactive)
6350 (setq-local org-pretty-entities (not org-pretty-entities))
6351 (org-restart-font-lock)
6352 (if org-pretty-entities
6353 (message "Entities are now displayed as UTF8 characters")
6354 (save-restriction
6355 (widen)
6356 (decompose-region (point-min) (point-max))
6357 (message "Entities are now displayed as plain text"))))
6359 (defvar-local org-custom-properties-overlays nil
6360 "List of overlays used for custom properties.")
6362 (defun org-toggle-custom-properties-visibility ()
6363 "Display or hide properties in `org-custom-properties'."
6364 (interactive)
6365 (if org-custom-properties-overlays
6366 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6367 (setq org-custom-properties-overlays nil))
6368 (when org-custom-properties
6369 (org-with-wide-buffer
6370 (goto-char (point-min))
6371 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6372 (while (re-search-forward regexp nil t)
6373 (let ((end (cdr (save-match-data (org-get-property-block)))))
6374 (when (and end (< (point) end))
6375 ;; Hide first custom property in current drawer.
6376 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6377 (overlay-put o 'invisible t)
6378 (overlay-put o 'org-custom-property t)
6379 (push o org-custom-properties-overlays))
6380 ;; Hide additional custom properties in the same drawer.
6381 (while (re-search-forward regexp end t)
6382 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6383 (overlay-put o 'invisible t)
6384 (overlay-put o 'org-custom-property t)
6385 (push o org-custom-properties-overlays)))))
6386 ;; Each entry is limited to a single property drawer.
6387 (outline-next-heading)))))))
6389 (defun org-fontify-entities (limit)
6390 "Find an entity to fontify."
6391 (let (ee)
6392 (when org-pretty-entities
6393 (catch 'match
6394 ;; "\_ "-family is left out on purpose. Only the first one,
6395 ;; i.e., "\_ ", could be fontified anyway, and it would be
6396 ;; confusing when adding a second white space character.
6397 (while (re-search-forward
6398 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6399 limit t)
6400 (when (and (not (org-at-comment-p))
6401 (setq ee (org-entity-get (match-string 1)))
6402 (= (length (nth 6 ee)) 1))
6403 (let* ((end (if (equal (match-string 2) "{}")
6404 (match-end 2)
6405 (match-end 1))))
6406 (add-text-properties
6407 (match-beginning 0) end
6408 (list 'font-lock-fontified t))
6409 (compose-region (match-beginning 0) end
6410 (nth 6 ee) nil)
6411 (backward-char 1)
6412 (throw 'match t))))
6413 nil))))
6415 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6416 "Fontify string S like in Org mode."
6417 (with-temp-buffer
6418 (insert s)
6419 (let ((org-odd-levels-only odd-levels))
6420 (org-mode)
6421 (org-font-lock-ensure)
6422 (buffer-string))))
6424 (defvar org-m nil)
6425 (defvar org-l nil)
6426 (defvar org-f nil)
6427 (defun org-get-level-face (n)
6428 "Get the right face for match N in font-lock matching of headlines."
6429 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6430 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6431 (if org-cycle-level-faces
6432 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6433 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6434 (cond
6435 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6436 ((eq n 2) org-f)
6437 (t (unless org-level-color-stars-only org-f))))
6439 (defun org-face-from-face-or-color (context inherit face-or-color)
6440 "Create a face list that inherits INHERIT, but sets the foreground color.
6441 When FACE-OR-COLOR is not a string, just return it."
6442 (if (stringp face-or-color)
6443 (list :inherit inherit
6444 (cdr (assoc context org-faces-easy-properties))
6445 face-or-color)
6446 face-or-color))
6448 (defun org-get-todo-face (kwd)
6449 "Get the right face for a TODO keyword KWD.
6450 If KWD is a number, get the corresponding match group."
6451 (when (numberp kwd) (setq kwd (match-string kwd)))
6452 (or (org-face-from-face-or-color
6453 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6454 (and (member kwd org-done-keywords) 'org-done)
6455 'org-todo))
6457 (defun org-get-priority-face (priority)
6458 "Get the right face for PRIORITY.
6459 PRIORITY is a character."
6460 (or (org-face-from-face-or-color
6461 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6462 'org-priority))
6464 (defun org-get-tag-face (tag)
6465 "Get the right face for TAG.
6466 If TAG is a number, get the corresponding match group."
6467 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6468 (or (org-face-from-face-or-color
6469 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6470 'org-tag)))
6472 (defun org-font-lock-add-priority-faces (limit)
6473 "Add the special priority faces."
6474 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6475 (add-text-properties
6476 (match-beginning 1) (match-end 1)
6477 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6478 'font-lock-fontified t))))
6480 (defun org-font-lock-add-tag-faces (limit)
6481 "Add the special tag faces."
6482 (when (and org-tag-faces org-tags-special-faces-re)
6483 (while (re-search-forward org-tags-special-faces-re limit t)
6484 (add-text-properties (match-beginning 1) (match-end 1)
6485 (list 'face (org-get-tag-face 1)
6486 'font-lock-fontified t))
6487 (backward-char 1))))
6489 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6490 "Remove fontification and activation overlays from links."
6491 (font-lock-default-unfontify-region beg end)
6492 (let* ((buffer-undo-list t)
6493 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6494 (inhibit-modification-hooks t)
6495 deactivate-mark buffer-file-name buffer-file-truename)
6496 (decompose-region beg end)
6497 (remove-text-properties beg end
6498 '(mouse-face t keymap t org-linked-text t
6499 invisible t intangible t
6500 org-emphasis t))
6501 (org-remove-font-lock-display-properties beg end)))
6503 (defconst org-script-display '(((raise -0.3) (height 0.7))
6504 ((raise 0.3) (height 0.7))
6505 ((raise -0.5))
6506 ((raise 0.5)))
6507 "Display properties for showing superscripts and subscripts.")
6509 (defun org-remove-font-lock-display-properties (beg end)
6510 "Remove specific display properties that have been added by font lock.
6511 The will remove the raise properties that are used to show superscripts
6512 and subscripts."
6513 (let (next prop)
6514 (while (< beg end)
6515 (setq next (next-single-property-change beg 'display nil end)
6516 prop (get-text-property beg 'display))
6517 (when (member prop org-script-display)
6518 (put-text-property beg next 'display nil))
6519 (setq beg next))))
6521 (defun org-raise-scripts (limit)
6522 "Add raise properties to sub/superscripts."
6523 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6524 (re-search-forward
6525 (if (eq org-use-sub-superscripts t)
6526 org-match-substring-regexp
6527 org-match-substring-with-braces-regexp)
6528 limit t))
6529 (let* ((pos (point)) table-p comment-p
6530 (mpos (match-beginning 3))
6531 (emph-p (get-text-property mpos 'org-emphasis))
6532 (link-p (get-text-property mpos 'mouse-face))
6533 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6534 (goto-char (point-at-bol))
6535 (setq table-p (looking-at-p org-table-dataline-regexp)
6536 comment-p (looking-at-p "^[ \t]*#[ +]"))
6537 (goto-char pos)
6538 ;; Handle a_b^c
6539 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6540 (unless (or comment-p emph-p link-p keyw-p)
6541 (put-text-property (match-beginning 3) (match-end 0)
6542 'display
6543 (if (equal (char-after (match-beginning 2)) ?^)
6544 (nth (if table-p 3 1) org-script-display)
6545 (nth (if table-p 2 0) org-script-display)))
6546 (add-text-properties (match-beginning 2) (match-end 2)
6547 (list 'invisible t))
6548 (when (and (eq (char-after (match-beginning 3)) ?{)
6549 (eq (char-before (match-end 3)) ?}))
6550 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6551 (list 'invisible t))
6552 (add-text-properties (1- (match-end 3)) (match-end 3)
6553 (list 'invisible t))))
6554 t)))
6556 (defun org-remove-empty-overlays-at (pos)
6557 "Remove outline overlays that do not contain non-white stuff."
6558 (dolist (o (overlays-at pos))
6559 (and (eq 'outline (overlay-get o 'invisible))
6560 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6561 (overlay-end o))))
6562 (delete-overlay o))))
6564 (defun org-show-empty-lines-in-parent ()
6565 "Move to the parent and re-show empty lines before visible headlines."
6566 (save-excursion
6567 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6568 (org-cycle-show-empty-lines context))))
6570 (defun org-files-list ()
6571 "Return `org-agenda-files' list, plus all open Org files.
6572 This is useful for operations that need to scan all of a user's
6573 open and agenda-wise Org files."
6574 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6575 (dolist (buf (buffer-list))
6576 (with-current-buffer buf
6577 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6578 (cl-pushnew (expand-file-name (buffer-file-name)) files
6579 :test #'equal))))
6580 files))
6582 (defsubst org-entry-beginning-position ()
6583 "Return the beginning position of the current entry."
6584 (save-excursion (org-back-to-heading t) (point)))
6586 (defsubst org-entry-end-position ()
6587 "Return the end position of the current entry."
6588 (save-excursion (outline-next-heading) (point)))
6590 (defun org-subtree-end-visible-p ()
6591 "Is the end of the current subtree visible?"
6592 (pos-visible-in-window-p
6593 (save-excursion (org-end-of-subtree t) (point))))
6595 (defun org-first-headline-recenter ()
6596 "Move cursor to the first headline and recenter the headline."
6597 (let ((window (get-buffer-window)))
6598 (when window
6599 (goto-char (point-min))
6600 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6601 (set-window-start window (line-beginning-position))))))
6604 ;;; Visibility (headlines, blocks, drawers)
6606 (defun org-flag-region (from to flag spec)
6607 "Hide or show lines from FROM to TO, according to FLAG.
6608 SPEC is the invisibility spec, as a symbol."
6609 (remove-overlays from to 'invisible spec)
6610 ;; Use `front-advance' since text right before to the beginning of
6611 ;; the overlay belongs to the visible line than to the contents.
6612 (when flag
6613 (let ((o (make-overlay from to nil 'front-advance)))
6614 (overlay-put o 'evaporate t)
6615 (overlay-put o 'invisible spec)
6616 (overlay-put o 'isearch-open-invisible #'delete-overlay))))
6618 ;;;; Headlines visibility
6620 (defun org-show-entry ()
6621 "Show the body directly following this heading.
6622 Show the heading too, if it is currently invisible."
6623 (interactive)
6624 (save-excursion
6625 (ignore-errors
6626 (org-back-to-heading t)
6627 (org-flag-region
6628 (line-end-position 0)
6629 (save-excursion
6630 (if (re-search-forward
6631 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6632 (match-beginning 1)
6633 (point-max)))
6635 'outline))))
6637 (defun org-show-children (&optional level)
6638 "Show all direct subheadings of this heading.
6639 Prefix arg LEVEL is how many levels below the current level
6640 should be shown. Default is enough to cause the following
6641 heading to appear."
6642 (interactive "p")
6643 (save-excursion
6644 (org-back-to-heading t)
6645 (let* ((current-level (funcall outline-level))
6646 (max-level (org-get-valid-level
6647 current-level
6648 (if level (prefix-numeric-value level) 1)))
6649 (end (save-excursion (org-end-of-subtree t t)))
6650 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6651 (past-first-child nil)
6652 ;; Make sure to skip inlinetasks.
6653 (re (format regexp-fmt
6654 current-level
6655 (cond
6656 ((not (featurep 'org-inlinetask)) "")
6657 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6659 (t (1- org-inlinetask-min-level))))))
6660 ;; Display parent heading.
6661 (org-flag-heading nil)
6662 (forward-line)
6663 ;; Display children. First child may be deeper than expected
6664 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6665 ;; MAX-LEVEL accordingly.
6666 (while (re-search-forward re end t)
6667 (unless past-first-child
6668 (setq re (format regexp-fmt
6669 current-level
6670 (max (funcall outline-level) max-level)))
6671 (setq past-first-child t))
6672 (org-flag-heading nil)))))
6674 (defun org-show-subtree ()
6675 "Show everything after this heading at deeper levels."
6676 (interactive)
6677 (org-flag-region
6678 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6680 ;;;; Blocks visibility
6682 (defun org-hide-block-toggle-maybe ()
6683 "Toggle visibility of block at point.
6684 Unlike to `org-hide-block-toggle', this function does not throw
6685 an error. Return a non-nil value when toggling is successful."
6686 (interactive)
6687 (ignore-errors (org-hide-block-toggle)))
6689 (defun org-hide-block-toggle (&optional force)
6690 "Toggle the visibility of the current block.
6691 When optional argument FORCE is `off', make block visible. If it
6692 is non-nil, hide it unconditionally. Throw an error when not at
6693 a block. Return a non-nil value when toggling is successful."
6694 (interactive)
6695 (let ((element (org-element-at-point)))
6696 (unless (memq (org-element-type element)
6697 '(center-block comment-block dynamic-block example-block
6698 export-block quote-block special-block
6699 src-block verse-block))
6700 (user-error "Not at a block"))
6701 (let* ((post (org-element-property :post-affiliated element))
6702 (start (save-excursion
6703 (goto-char post)
6704 (line-end-position)))
6705 (end (save-excursion
6706 (goto-char (org-element-property :end element))
6707 (skip-chars-backward " \t\n")
6708 (line-end-position))))
6709 ;; Do nothing when not before or at the block opening line or at
6710 ;; the block closing line.
6711 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6712 (cond ((eq force 'off)
6713 (org-flag-region start end nil 'org-hide-block))
6714 (force
6715 (org-flag-region start end t 'org-hide-block))
6716 ((eq (get-char-property start 'invisible) 'org-hide-block)
6717 (org-flag-region start end nil 'org-hide-block))
6719 (org-flag-region start end t 'org-hide-block)))
6720 ;; When the block is hidden away, make sure point is left in
6721 ;; a visible part of the buffer.
6722 (when (invisible-p (max (1- (point)) (point-min)))
6723 (goto-char post))
6724 ;; Signal success.
6725 t))))
6727 (defun org-hide-block-toggle-all ()
6728 "Toggle the visibility of all blocks in the current buffer."
6729 (org-block-map 'org-hide-block-toggle))
6731 (defun org-hide-block-all ()
6732 "Fold all blocks in the current buffer."
6733 (interactive)
6734 (org-show-all '(blocks))
6735 (org-block-map 'org-hide-block-toggle-maybe))
6737 ;;;; Drawers visibility
6739 (defun org-cycle-hide-drawers (state &optional exceptions)
6740 "Re-hide all drawers after a visibility state change.
6741 STATE should be one of the symbols listed in the docstring of
6742 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6743 a list of strings specifying which drawers should not be hidden."
6744 (when (and (derived-mode-p 'org-mode)
6745 (not (memq state '(overview folded contents))))
6746 (save-excursion
6747 (let* ((globalp (eq state 'all))
6748 (beg (if globalp (point-min) (point)))
6749 (end (if globalp (point-max)
6750 (if (eq state 'children)
6751 (save-excursion (outline-next-heading) (point))
6752 (org-end-of-subtree t)))))
6753 (goto-char beg)
6754 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6755 (unless (member-ignore-case (match-string 1) exceptions)
6756 (let ((drawer (org-element-at-point)))
6757 (when (memq (org-element-type drawer) '(drawer property-drawer))
6758 (org-flag-drawer t drawer)
6759 ;; Make sure to skip drawer entirely or we might flag
6760 ;; it another time when matching its ending line with
6761 ;; `org-drawer-regexp'.
6762 (goto-char (org-element-property :end drawer))))))))))
6764 (defun org-flag-drawer (flag &optional element)
6765 "When FLAG is non-nil, hide the drawer we are at.
6766 Otherwise make it visible. When optional argument ELEMENT is
6767 a parsed drawer, as returned by `org-element-at-point', hide or
6768 show that drawer instead."
6769 (let ((drawer (or element
6770 (and (save-excursion
6771 (beginning-of-line)
6772 (looking-at-p org-drawer-regexp))
6773 (org-element-at-point)))))
6774 (when (memq (org-element-type drawer) '(drawer property-drawer))
6775 (let ((post (org-element-property :post-affiliated drawer)))
6776 (org-flag-region
6777 (save-excursion (goto-char post) (line-end-position))
6778 (save-excursion (goto-char (org-element-property :end drawer))
6779 (skip-chars-backward " \t\n")
6780 (line-end-position))
6781 flag 'org-hide-drawer)
6782 ;; When the drawer is hidden away, make sure point lies in
6783 ;; a visible part of the buffer.
6784 (when (invisible-p (max (1- (point)) (point-min)))
6785 (goto-char post))))))
6787 ;;;; Visibility cycling
6789 (defvar-local org-cycle-global-status nil)
6790 (put 'org-cycle-global-status 'org-state t)
6791 (defvar-local org-cycle-subtree-status nil)
6792 (put 'org-cycle-subtree-status 'org-state t)
6794 (defun org-show-all (&optional types)
6795 "Show all contents in the visible part of the buffer.
6796 By default, the function expands headings, blocks and drawers.
6797 When optional argument TYPE is a list of symbols among `blocks',
6798 `drawers' and `headings', to only expand one specific type."
6799 (dolist (type (or types '(blocks drawers headings)))
6800 (org-flag-region (point-min) (point-max) nil
6801 (pcase type
6802 (`blocks 'org-hide-block)
6803 (`drawers 'org-hide-drawer)
6804 (`headings 'outline)
6805 (_ (error "Invalid type: %S" type))))))
6807 ;;;###autoload
6808 (defun org-cycle (&optional arg)
6809 "TAB-action and visibility cycling for Org mode.
6811 This is the command invoked in Org mode by the `TAB' key. Its main
6812 purpose is outline visibility cycling, but it also invokes other actions
6813 in special contexts.
6815 When this function is called with a `\\[universal-argument]' prefix, rotate \
6816 the entire
6817 buffer through 3 states (global cycling)
6818 1. OVERVIEW: Show only top-level headlines.
6819 2. CONTENTS: Show all headlines of all levels, but no body text.
6820 3. SHOW ALL: Show everything.
6822 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6823 switch to the startup visibility,
6824 determined by the variable `org-startup-folded', and by any VISIBILITY
6825 properties in the buffer.
6827 With a `\\[universal-argument] \\[universal-argument] \
6828 \\[universal-argument]' prefix argument, show the entire buffer, including
6829 any drawers.
6831 When inside a table, re-align the table and move to the next field.
6833 When point is at the beginning of a headline, rotate the subtree started
6834 by this line through 3 different states (local cycling)
6835 1. FOLDED: Only the main headline is shown.
6836 2. CHILDREN: The main headline and the direct children are shown.
6837 From this state, you can move to one of the children
6838 and zoom in further.
6839 3. SUBTREE: Show the entire subtree, including body text.
6840 If there is no subtree, switch directly from CHILDREN to FOLDED.
6842 When point is at the beginning of an empty headline and the variable
6843 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6844 of the headline by demoting and promoting it to likely levels. This
6845 speeds up creation document structure by pressing `TAB' once or several
6846 times right after creating a new headline.
6848 When there is a numeric prefix, go up to a heading with level ARG, do
6849 a `show-subtree' and return to the previous cursor position. If ARG
6850 is negative, go up that many levels.
6852 When point is not at the beginning of a headline, execute the global
6853 binding for `TAB', which is re-indenting the line. See the option
6854 `org-cycle-emulate-tab' for details.
6856 As a special case, if point is at the beginning of the buffer and there is
6857 no headline in line 1, this function will act as if called with prefix arg
6858 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6859 prefix arg, but only
6860 if the variable `org-cycle-global-at-bob' is t."
6861 (interactive "P")
6862 (org-load-modules-maybe)
6863 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6864 (and org-cycle-level-after-item/entry-creation
6865 (or (org-cycle-level)
6866 (org-cycle-item-indentation))))
6867 (let* ((limit-level
6868 (or org-cycle-max-level
6869 (and (boundp 'org-inlinetask-min-level)
6870 org-inlinetask-min-level
6871 (1- org-inlinetask-min-level))))
6872 (nstars (and limit-level
6873 (if org-odd-levels-only
6874 (and limit-level (1- (* limit-level 2)))
6875 limit-level)))
6876 (org-outline-regexp
6877 (if (not (derived-mode-p 'org-mode))
6878 outline-regexp
6879 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6880 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6881 (not (looking-at org-outline-regexp))))
6882 (org-cycle-hook
6883 (if bob-special
6884 (delq 'org-optimize-window-after-visibility-change
6885 (copy-sequence org-cycle-hook))
6886 org-cycle-hook))
6887 (pos (point)))
6889 (cond
6891 ((equal arg '(16))
6892 (setq last-command 'dummy)
6893 (org-set-startup-visibility)
6894 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6896 ((equal arg '(64))
6897 (org-show-all)
6898 (org-unlogged-message "Entire buffer visible, including drawers"))
6900 ((equal arg '(4)) (org-cycle-internal-global))
6902 ;; Try hiding block at point.
6903 ((org-hide-block-toggle-maybe))
6905 ;; Try cdlatex TAB completion
6906 ((org-try-cdlatex-tab))
6908 ;; Table: enter it or move to the next field.
6909 ((org-at-table-p 'any)
6910 (if (org-at-table.el-p)
6911 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6912 Use `\\[org-edit-special]' to edit table.el tables"))
6913 (if arg (org-table-edit-field t)
6914 (org-table-justify-field-maybe)
6915 (call-interactively 'org-table-next-field))))
6917 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6919 ;; Global cycling: delegate to `org-cycle-internal-global'.
6920 (bob-special (org-cycle-internal-global))
6922 ;; Drawers: delegate to `org-flag-drawer'.
6923 ((save-excursion
6924 (beginning-of-line 1)
6925 (looking-at org-drawer-regexp))
6926 (org-flag-drawer ; toggle block visibility
6927 (not (get-char-property (match-end 0) 'invisible))))
6929 ;; Show-subtree, ARG levels up from here.
6930 ((integerp arg)
6931 (save-excursion
6932 (org-back-to-heading)
6933 (outline-up-heading (if (< arg 0) (- arg)
6934 (- (funcall outline-level) arg)))
6935 (org-show-subtree)))
6937 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6938 ((and (featurep 'org-inlinetask)
6939 (org-inlinetask-at-task-p)
6940 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6941 (org-inlinetask-toggle-visibility))
6943 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6944 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6945 (save-excursion (move-beginning-of-line 1)
6946 (looking-at org-outline-regexp)))
6947 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6948 (org-cycle-internal-local))
6950 ;; From there: TAB emulation and template completion.
6951 (buffer-read-only (org-back-to-heading))
6953 ((run-hook-with-args-until-success
6954 'org-tab-after-check-for-cycling-hook))
6956 ((run-hook-with-args-until-success
6957 'org-tab-before-tab-emulation-hook))
6959 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6960 (or (not (bolp))
6961 (not (looking-at org-outline-regexp))))
6962 (call-interactively (global-key-binding "\t")))
6964 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6965 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6966 (or (and (eq org-cycle-emulate-tab 'white)
6967 (= (match-end 0) (point-at-eol)))
6968 (and (eq org-cycle-emulate-tab 'whitestart)
6969 (>= (match-end 0) pos))))
6971 (eq org-cycle-emulate-tab t))
6972 (call-interactively (global-key-binding "\t")))
6974 (t (save-excursion
6975 (org-back-to-heading)
6976 (org-cycle)))))))
6978 (defun org-cycle-internal-global ()
6979 "Do the global cycling action."
6980 ;; Hack to avoid display of messages for .org attachments in Gnus
6981 (let ((ga (string-match "\\*fontification" (buffer-name))))
6982 (cond
6983 ((and (eq last-command this-command)
6984 (eq org-cycle-global-status 'overview))
6985 ;; We just created the overview - now do table of contents
6986 ;; This can be slow in very large buffers, so indicate action
6987 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6988 (unless ga (org-unlogged-message "CONTENTS..."))
6989 (org-content)
6990 (unless ga (org-unlogged-message "CONTENTS...done"))
6991 (setq org-cycle-global-status 'contents)
6992 (run-hook-with-args 'org-cycle-hook 'contents))
6994 ((and (eq last-command this-command)
6995 (eq org-cycle-global-status 'contents))
6996 ;; We just showed the table of contents - now show everything
6997 (run-hook-with-args 'org-pre-cycle-hook 'all)
6998 (org-show-all '(headings blocks))
6999 (unless ga (org-unlogged-message "SHOW ALL"))
7000 (setq org-cycle-global-status 'all)
7001 (run-hook-with-args 'org-cycle-hook 'all))
7004 ;; Default action: go to overview
7005 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7006 (org-overview)
7007 (unless ga (org-unlogged-message "OVERVIEW"))
7008 (setq org-cycle-global-status 'overview)
7009 (run-hook-with-args 'org-cycle-hook 'overview)))))
7011 (defvar org-called-with-limited-levels nil
7012 "Non-nil when `org-with-limited-levels' is currently active.")
7014 (defun org-cycle-internal-local ()
7015 "Do the local cycling action."
7016 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7017 ;; First, determine end of headline (EOH), end of subtree or item
7018 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7019 (save-excursion
7020 (if (org-at-item-p)
7021 (progn
7022 (beginning-of-line)
7023 (setq struct (org-list-struct))
7024 (setq eoh (point-at-eol))
7025 (setq eos (org-list-get-item-end-before-blank (point) struct))
7026 (setq has-children (org-list-has-child-p (point) struct)))
7027 (org-back-to-heading)
7028 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7029 (setq eos (save-excursion (org-end-of-subtree t t)
7030 (when (bolp) (backward-char)) (point)))
7031 (setq has-children
7032 (or (save-excursion
7033 (let ((level (funcall outline-level)))
7034 (outline-next-heading)
7035 (and (org-at-heading-p t)
7036 (> (funcall outline-level) level))))
7037 (save-excursion
7038 (org-list-search-forward (org-item-beginning-re) eos t)))))
7039 ;; Determine end invisible part of buffer (EOL)
7040 (beginning-of-line 2)
7041 (while (and (not (eobp)) ;This is like `next-line'.
7042 (get-char-property (1- (point)) 'invisible))
7043 (goto-char (next-single-char-property-change (point) 'invisible))
7044 (and (eolp) (beginning-of-line 2)))
7045 (setq eol (point)))
7046 ;; Find out what to do next and set `this-command'
7047 (cond
7048 ((= eos eoh)
7049 ;; Nothing is hidden behind this heading
7050 (unless (org-before-first-heading-p)
7051 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7052 (org-unlogged-message "EMPTY ENTRY")
7053 (setq org-cycle-subtree-status nil)
7054 (save-excursion
7055 (goto-char eos)
7056 (outline-next-heading)
7057 (when (org-invisible-p) (org-flag-heading nil))))
7058 ((and (or (>= eol eos)
7059 (not (string-match "\\S-" (buffer-substring eol eos))))
7060 (or has-children
7061 (not (setq children-skipped
7062 org-cycle-skip-children-state-if-no-children))))
7063 ;; Entire subtree is hidden in one line: children view
7064 (unless (org-before-first-heading-p)
7065 (run-hook-with-args 'org-pre-cycle-hook 'children))
7066 (if (org-at-item-p)
7067 (org-list-set-item-visibility (point-at-bol) struct 'children)
7068 (org-show-entry)
7069 (org-with-limited-levels (org-show-children))
7070 (org-show-set-visibility 'canonical)
7071 ;; Fold every list in subtree to top-level items.
7072 (when (eq org-cycle-include-plain-lists 'integrate)
7073 (save-excursion
7074 (org-back-to-heading)
7075 (while (org-list-search-forward (org-item-beginning-re) eos t)
7076 (beginning-of-line 1)
7077 (let* ((struct (org-list-struct))
7078 (prevs (org-list-prevs-alist struct))
7079 (end (org-list-get-bottom-point struct)))
7080 (dolist (e (org-list-get-all-items (point) struct prevs))
7081 (org-list-set-item-visibility e struct 'folded))
7082 (goto-char (if (< end eos) end eos)))))))
7083 (org-unlogged-message "CHILDREN")
7084 (save-excursion
7085 (goto-char eos)
7086 (outline-next-heading)
7087 (when (org-invisible-p) (org-flag-heading nil)))
7088 (setq org-cycle-subtree-status 'children)
7089 (unless (org-before-first-heading-p)
7090 (run-hook-with-args 'org-cycle-hook 'children)))
7091 ((or children-skipped
7092 (and (eq last-command this-command)
7093 (eq org-cycle-subtree-status 'children)))
7094 ;; We just showed the children, or no children are there,
7095 ;; now show everything.
7096 (unless (org-before-first-heading-p)
7097 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7098 (org-flag-region eoh eos nil 'outline)
7099 (org-unlogged-message
7100 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7101 (setq org-cycle-subtree-status 'subtree)
7102 (unless (org-before-first-heading-p)
7103 (run-hook-with-args 'org-cycle-hook 'subtree)))
7105 ;; Default action: hide the subtree.
7106 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7107 (org-flag-region eoh eos t 'outline)
7108 (org-unlogged-message "FOLDED")
7109 (setq org-cycle-subtree-status 'folded)
7110 (unless (org-before-first-heading-p)
7111 (run-hook-with-args 'org-cycle-hook 'folded))))))
7113 ;;;###autoload
7114 (defun org-global-cycle (&optional arg)
7115 "Cycle the global visibility. For details see `org-cycle'.
7116 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7117 With a numeric prefix, show all headlines up to that level."
7118 (interactive "P")
7119 (let ((org-cycle-include-plain-lists
7120 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7121 (cond
7122 ((integerp arg)
7123 (org-show-all '(headings blocks))
7124 (outline-hide-sublevels arg)
7125 (setq org-cycle-global-status 'contents))
7126 ((equal arg '(4))
7127 (org-set-startup-visibility)
7128 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7130 (org-cycle '(4))))))
7132 (defun org-set-startup-visibility ()
7133 "Set the visibility required by startup options and properties."
7134 (cond
7135 ((eq org-startup-folded t)
7136 (org-overview))
7137 ((eq org-startup-folded 'content)
7138 (org-content))
7139 ((or (eq org-startup-folded 'showeverything)
7140 (eq org-startup-folded nil))
7141 (org-show-all)))
7142 (unless (eq org-startup-folded 'showeverything)
7143 (when org-hide-block-startup (org-hide-block-all))
7144 (org-set-visibility-according-to-property)
7145 (org-cycle-hide-archived-subtrees 'all)
7146 (org-cycle-hide-drawers 'all)
7147 (org-cycle-show-empty-lines t)))
7149 (defun org-set-visibility-according-to-property ()
7150 "Switch subtree visibilities according to :VISIBILITY: property."
7151 (interactive)
7152 (org-with-wide-buffer
7153 (goto-char (point-min))
7154 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7155 (if (not (org-at-property-p)) (outline-next-heading)
7156 (let ((state (match-string 3)))
7157 (save-excursion
7158 (org-back-to-heading t)
7159 (outline-hide-subtree)
7160 (org-reveal)
7161 (cond
7162 ((equal state "folded")
7163 (outline-hide-subtree))
7164 ((equal state "children")
7165 (org-show-hidden-entry)
7166 (org-show-children))
7167 ((equal state "content")
7168 (save-excursion
7169 (save-restriction
7170 (org-narrow-to-subtree)
7171 (org-content))))
7172 ((member state '("all" "showall"))
7173 (outline-show-subtree)))))))))
7175 (defun org-overview ()
7176 "Switch to overview mode, showing only top-level headlines.
7177 This shows all headlines with a level equal or greater than the level
7178 of the first headline in the buffer. This is important, because if the
7179 first headline is not level one, then (hide-sublevels 1) gives confusing
7180 results."
7181 (interactive)
7182 (save-excursion
7183 (let ((level
7184 (save-excursion
7185 (goto-char (point-min))
7186 (when (re-search-forward org-outline-regexp-bol nil t)
7187 (goto-char (match-beginning 0))
7188 (funcall outline-level)))))
7189 (and level (outline-hide-sublevels level)))))
7191 (defun org-content (&optional arg)
7192 "Show all headlines in the buffer, like a table of contents.
7193 With numerical argument N, show content up to level N."
7194 (interactive "P")
7195 (org-overview)
7196 (save-excursion
7197 ;; Visit all headings and show their offspring
7198 (and (integerp arg) (org-overview))
7199 (goto-char (point-max))
7200 (catch 'exit
7201 (while (and (progn (condition-case nil
7202 (outline-previous-visible-heading 1)
7203 (error (goto-char (point-min))))
7205 (looking-at org-outline-regexp))
7206 (if (integerp arg)
7207 (org-show-children (1- arg))
7208 (outline-show-branches))
7209 (when (bobp) (throw 'exit nil))))))
7211 (defun org-optimize-window-after-visibility-change (state)
7212 "Adjust the window after a change in outline visibility.
7213 This function is the default value of the hook `org-cycle-hook'."
7214 (when (get-buffer-window (current-buffer))
7215 (cond
7216 ((eq state 'content) nil)
7217 ((eq state 'all) nil)
7218 ((eq state 'folded) nil)
7219 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7220 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7222 (defun org-clean-visibility-after-subtree-move ()
7223 "Fix visibility issues after moving a subtree."
7224 ;; First, find a reasonable region to look at:
7225 ;; Start two siblings above, end three below
7226 (let* ((beg (save-excursion
7227 (and (org-get-last-sibling)
7228 (org-get-last-sibling))
7229 (point)))
7230 (end (save-excursion
7231 (and (org-get-next-sibling)
7232 (org-get-next-sibling)
7233 (org-get-next-sibling))
7234 (if (org-at-heading-p)
7235 (point-at-eol)
7236 (point))))
7237 (level (looking-at "\\*+"))
7238 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7239 (save-excursion
7240 (save-restriction
7241 (narrow-to-region beg end)
7242 (when re
7243 ;; Properly fold already folded siblings
7244 (goto-char (point-min))
7245 (while (re-search-forward re nil t)
7246 (when (and (not (org-invisible-p))
7247 (org-invisible-p (line-end-position)))
7248 (outline-hide-entry))))
7249 (org-cycle-hide-drawers 'all)
7250 (org-cycle-show-empty-lines 'overview)))))
7252 (defun org-cycle-show-empty-lines (state)
7253 "Show empty lines above all visible headlines.
7254 The region to be covered depends on STATE when called through
7255 `org-cycle-hook'. Lisp program can use t for STATE to get the
7256 entire buffer covered. Note that an empty line is only shown if there
7257 are at least `org-cycle-separator-lines' empty lines before the headline."
7258 (when (/= org-cycle-separator-lines 0)
7259 (save-excursion
7260 (let* ((n (abs org-cycle-separator-lines))
7261 (re (cond
7262 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7263 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7264 (t (let ((ns (number-to-string (- n 2))))
7265 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7266 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7267 beg end)
7268 (cond
7269 ((memq state '(overview contents t))
7270 (setq beg (point-min) end (point-max)))
7271 ((memq state '(children folded))
7272 (setq beg (point)
7273 end (progn (org-end-of-subtree t t)
7274 (line-beginning-position 2)))))
7275 (when beg
7276 (goto-char beg)
7277 (while (re-search-forward re end t)
7278 (unless (get-char-property (match-end 1) 'invisible)
7279 (let ((e (match-end 1))
7280 (b (if (>= org-cycle-separator-lines 0)
7281 (match-beginning 1)
7282 (save-excursion
7283 (goto-char (match-beginning 0))
7284 (skip-chars-backward " \t\n")
7285 (line-end-position)))))
7286 (org-flag-region b e nil 'outline))))))))
7287 ;; Never hide empty lines at the end of the file.
7288 (save-excursion
7289 (goto-char (point-max))
7290 (outline-previous-heading)
7291 (outline-end-of-heading)
7292 (when (and (looking-at "[ \t\n]+")
7293 (= (match-end 0) (point-max)))
7294 (org-flag-region (point) (match-end 0) nil 'outline))))
7296 ;;;; Reveal point location
7298 (defun org-show-context (&optional key)
7299 "Make sure point and context are visible.
7300 Optional argument KEY, when non-nil, is a symbol. See
7301 `org-show-context-detail' for allowed values and how much is to
7302 be shown."
7303 (org-show-set-visibility
7304 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7305 ((cdr (assq key org-show-context-detail)))
7306 (t (cdr (assq 'default org-show-context-detail))))))
7308 (defun org-show-set-visibility (detail)
7309 "Set visibility around point according to DETAIL.
7310 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7311 `tree', `canonical' or t. See `org-show-context-detail' for more
7312 information."
7313 ;; Show current heading and possibly its entry, following headline
7314 ;; or all children.
7315 (if (and (org-at-heading-p) (not (eq detail 'local)))
7316 (org-flag-heading nil)
7317 (org-show-entry)
7318 ;; If point is hidden within a drawer or a block, make sure to
7319 ;; expose it.
7320 (dolist (o (overlays-at (point)))
7321 (when (memq (overlay-get o 'invisible)
7322 '(org-hide-block org-hide-drawer outline))
7323 (delete-overlay o)))
7324 (unless (org-before-first-heading-p)
7325 (org-with-limited-levels
7326 (cl-case detail
7327 ((tree canonical t) (org-show-children))
7328 ((nil minimal ancestors))
7329 (t (save-excursion
7330 (outline-next-heading)
7331 (org-flag-heading nil)))))))
7332 ;; Show all siblings.
7333 (when (eq detail 'lineage) (org-show-siblings))
7334 ;; Show ancestors, possibly with their children.
7335 (when (memq detail '(ancestors lineage tree canonical t))
7336 (save-excursion
7337 (while (org-up-heading-safe)
7338 (org-flag-heading nil)
7339 (when (memq detail '(canonical t)) (org-show-entry))
7340 (when (memq detail '(tree canonical t)) (org-show-children))))))
7342 (defvar org-reveal-start-hook nil
7343 "Hook run before revealing a location.")
7345 (defun org-reveal (&optional siblings)
7346 "Show current entry, hierarchy above it, and the following headline.
7348 This can be used to show a consistent set of context around
7349 locations exposed with `org-show-context'.
7351 With optional argument SIBLINGS, on each level of the hierarchy all
7352 siblings are shown. This repairs the tree structure to what it would
7353 look like when opened with hierarchical calls to `org-cycle'.
7355 With a \\[universal-argument] \\[universal-argument] prefix, \
7356 go to the parent and show the entire tree."
7357 (interactive "P")
7358 (run-hooks 'org-reveal-start-hook)
7359 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7360 ((equal siblings '(16))
7361 (save-excursion
7362 (when (org-up-heading-safe)
7363 (org-show-subtree)
7364 (run-hook-with-args 'org-cycle-hook 'subtree))))
7365 (t (org-show-set-visibility 'lineage))))
7368 ;;; Indirect buffer display of subtrees
7370 (defvar org-indirect-dedicated-frame nil
7371 "This is the frame being used for indirect tree display.")
7372 (defvar org-last-indirect-buffer nil)
7374 (defun org-tree-to-indirect-buffer (&optional arg)
7375 "Create indirect buffer and narrow it to current subtree.
7377 With a numerical prefix ARG, go up to this level and then take that tree.
7378 If ARG is negative, go up that many levels.
7380 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7381 indirect buffer previously made with this command, to avoid proliferation of
7382 indirect buffers. However, when you call the command with a \
7383 `\\[universal-argument]' prefix, or
7384 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7385 so that you can work with several indirect buffers at the same time. If
7386 `org-indirect-buffer-display' is `dedicated-frame', the \
7387 `\\[universal-argument]' prefix also
7388 requests that a new frame be made for the new buffer, so that the dedicated
7389 frame is not changed."
7390 (interactive "P")
7391 (let ((cbuf (current-buffer))
7392 (cwin (selected-window))
7393 (pos (point))
7394 beg end level heading ibuf)
7395 (save-excursion
7396 (org-back-to-heading t)
7397 (when (numberp arg)
7398 (setq level (org-outline-level))
7399 (when (< arg 0) (setq arg (+ level arg)))
7400 (while (> (setq level (org-outline-level)) arg)
7401 (org-up-heading-safe)))
7402 (setq beg (point)
7403 heading (org-get-heading 'no-tags))
7404 (org-end-of-subtree t t)
7405 (when (org-at-heading-p) (backward-char 1))
7406 (setq end (point)))
7407 (when (and (buffer-live-p org-last-indirect-buffer)
7408 (not (eq org-indirect-buffer-display 'new-frame))
7409 (not arg))
7410 (kill-buffer org-last-indirect-buffer))
7411 (setq ibuf (org-get-indirect-buffer cbuf heading)
7412 org-last-indirect-buffer ibuf)
7413 (cond
7414 ((or (eq org-indirect-buffer-display 'new-frame)
7415 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7416 (select-frame (make-frame))
7417 (delete-other-windows)
7418 (pop-to-buffer-same-window ibuf)
7419 (org-set-frame-title heading))
7420 ((eq org-indirect-buffer-display 'dedicated-frame)
7421 (raise-frame
7422 (select-frame (or (and org-indirect-dedicated-frame
7423 (frame-live-p org-indirect-dedicated-frame)
7424 org-indirect-dedicated-frame)
7425 (setq org-indirect-dedicated-frame (make-frame)))))
7426 (delete-other-windows)
7427 (pop-to-buffer-same-window ibuf)
7428 (org-set-frame-title (concat "Indirect: " heading)))
7429 ((eq org-indirect-buffer-display 'current-window)
7430 (pop-to-buffer-same-window ibuf))
7431 ((eq org-indirect-buffer-display 'other-window)
7432 (pop-to-buffer ibuf))
7433 (t (error "Invalid value")))
7434 (narrow-to-region beg end)
7435 (org-show-all '(headings blocks))
7436 (goto-char pos)
7437 (run-hook-with-args 'org-cycle-hook 'all)
7438 (and (window-live-p cwin) (select-window cwin))))
7440 (defun org-get-indirect-buffer (&optional buffer heading)
7441 (setq buffer (or buffer (current-buffer)))
7442 (let ((n 1) (base (buffer-name buffer)) bname)
7443 (while (buffer-live-p
7444 (get-buffer
7445 (setq bname
7446 (concat base "-"
7447 (if heading (concat heading "-" (number-to-string n))
7448 (number-to-string n))))))
7449 (setq n (1+ n)))
7450 (condition-case nil
7451 (make-indirect-buffer buffer bname 'clone)
7452 (error (make-indirect-buffer buffer bname)))))
7454 (defun org-set-frame-title (title)
7455 "Set the title of the current frame to the string TITLE."
7456 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7458 ;;;; Structure editing
7460 ;;; Inserting headlines
7462 (defun org--line-empty-p (n)
7463 "Is the Nth next line empty?
7465 Counts the current line as N = 1 and the previous line as N = 0;
7466 see `beginning-of-line'."
7467 (save-excursion
7468 (and (not (bobp))
7469 (or (beginning-of-line n) t)
7470 (save-match-data
7471 (looking-at "[ \t]*$")))))
7473 (defun org-previous-line-empty-p ()
7474 "Is the previous line a blank line?
7475 When NEXT is non-nil, check the next line instead."
7476 (org--line-empty-p 0))
7478 (defun org-next-line-empty-p ()
7479 "Is the previous line a blank line?
7480 When NEXT is non-nil, check the next line instead."
7481 (org--line-empty-p 2))
7483 (defun org--blank-before-heading-p (&optional parent)
7484 "Non-nil when an empty line should precede a new heading here.
7485 When optional argument PARENT is non-nil, consider parent
7486 headline instead of current one."
7487 (pcase (assq 'heading org-blank-before-new-entry)
7488 (`(heading . auto)
7489 (save-excursion
7490 (org-with-limited-levels
7491 (unless (and (org-before-first-heading-p)
7492 (not (outline-next-heading)))
7493 (org-back-to-heading t)
7494 (when parent (org-up-heading-safe))
7495 (cond ((not (bobp))
7496 (org-previous-line-empty-p))
7497 ((outline-next-heading)
7498 (org-previous-line-empty-p))
7499 ;; Ignore trailing spaces on last buffer line.
7500 ((progn (skip-chars-backward " \t") (bolp))
7501 (org-previous-line-empty-p))
7502 (t nil))))))
7503 (`(heading . ,value) value)
7504 (_ nil)))
7506 (defun org-insert-heading (&optional arg invisible-ok top)
7507 "Insert a new heading or an item with the same depth at point.
7509 If point is at the beginning of a heading, insert a new heading
7510 or a new headline above the current one. When at the beginning
7511 of a regular line of text, turn it into a heading.
7513 If point is in the middle of a line, split it and create a new
7514 headline with the text in the current line after point (see
7515 `org-M-RET-may-split-line' on how to modify this behavior). As
7516 a special case, on a headline, splitting can only happen on the
7517 title itself. E.g., this excludes breaking stars or tags.
7519 With a `\\[universal-argument]' prefix, set \
7520 `org-insert-heading-respect-content' to
7521 a non-nil value for the duration of the command. This forces the
7522 insertion of a heading after the current subtree, independently
7523 on the location of point.
7525 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7526 insert the heading at the end of the tree
7527 above the current heading. For example, if point is within a
7528 2nd-level heading, then it will insert a 2nd-level heading at
7529 the end of the 1st-level parent subtree.
7531 When INVISIBLE-OK is set, stop at invisible headlines when going
7532 back. This is important for non-interactive uses of the
7533 command.
7535 When optional argument TOP is non-nil, insert a level 1 heading,
7536 unconditionally."
7537 (interactive "P")
7538 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7539 (level (org-current-level))
7540 (stars (make-string (if (and level (not top)) level 1) ?*)))
7541 (cond
7542 ((or org-insert-heading-respect-content
7543 (member arg '((4) (16)))
7544 (and (not invisible-ok)
7545 (invisible-p (max (1- (point)) (point-min)))))
7546 ;; Position point at the location of insertion.
7547 (if (not level) ;before first headline
7548 (org-with-limited-levels (outline-next-heading))
7549 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7550 ;; is nil.
7551 (org-with-limited-levels (org-back-to-heading invisible-ok))
7552 (cond ((equal arg '(16))
7553 (org-up-heading-safe)
7554 (org-end-of-subtree t t))
7556 (org-end-of-subtree t t))))
7557 (unless (bolp) (insert "\n")) ;ensure final newline
7558 (unless (and blank? (org-previous-line-empty-p))
7559 (org-N-empty-lines-before-current (if blank? 1 0)))
7560 (insert stars " \n")
7561 (forward-char -1))
7562 ;; At a headline...
7563 ((org-at-heading-p)
7564 (cond ((bolp)
7565 (when blank? (save-excursion (insert "\n")))
7566 (save-excursion (insert stars " \n"))
7567 (unless (and blank? (org-previous-line-empty-p))
7568 (org-N-empty-lines-before-current (if blank? 1 0)))
7569 (end-of-line))
7570 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7571 (org-match-line org-complex-heading-regexp)
7572 (org-pos-in-match-range (point) 4))
7573 ;; Grab the text that should moved to the new headline.
7574 ;; Preserve tags.
7575 (let ((split (delete-and-extract-region (point) (match-end 4))))
7576 (if (looking-at "[ \t]*$") (replace-match "")
7577 (org-set-tags nil t))
7578 (end-of-line)
7579 (when blank? (insert "\n"))
7580 (insert "\n" stars " ")
7581 (when (org-string-nw-p split) (insert split))
7582 (when (eobp) (save-excursion (insert "\n")))))
7584 (end-of-line)
7585 (when blank? (insert "\n"))
7586 (insert "\n" stars " ")
7587 (when (eobp) (save-excursion (insert "\n"))))))
7588 ;; On regular text, turn line into a headline or split, if
7589 ;; appropriate.
7590 ((bolp)
7591 (insert stars " ")
7592 (unless (and blank? (org-previous-line-empty-p))
7593 (org-N-empty-lines-before-current (if blank? 1 0))))
7595 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7596 (end-of-line))
7597 (insert "\n" stars " ")
7598 (unless (and blank? (org-previous-line-empty-p))
7599 (org-N-empty-lines-before-current (if blank? 1 0))))))
7600 (run-hooks 'org-insert-heading-hook))
7602 (defun org-N-empty-lines-before-current (n)
7603 "Make the number of empty lines before current exactly N.
7604 So this will delete or add empty lines."
7605 (let ((column (current-column)))
7606 (beginning-of-line)
7607 (unless (bobp)
7608 (let ((start (save-excursion
7609 (skip-chars-backward " \r\t\n")
7610 (line-end-position))))
7611 (delete-region start (line-end-position 0))))
7612 (insert (make-string n ?\n))
7613 (move-to-column column)))
7615 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7616 "Return the heading of the current entry, without the stars.
7617 When NO-TAGS is non-nil, don't include tags.
7618 When NO-TODO is non-nil, don't include TODO keywords.
7619 When NO-PRIORITY is non-nil, don't include priority cookie.
7620 When NO-COMMENT is non-nil, don't include COMMENT string."
7621 (save-excursion
7622 (org-back-to-heading t)
7623 (let ((case-fold-search nil))
7624 (looking-at org-complex-heading-regexp)
7625 (let ((todo (and (not no-todo) (match-string 2)))
7626 (priority (and (not no-priority) (match-string 3)))
7627 (headline (pcase (match-string 4)
7628 (`nil "")
7629 ((and (guard no-comment) h)
7630 (replace-regexp-in-string
7631 (eval-when-compile
7632 (format "\\`%s[ \t]+" org-comment-string))
7633 "" h))
7634 (h h)))
7635 (tags (and (not no-tags) (match-string 5))))
7636 (mapconcat #'identity
7637 (delq nil (list todo priority headline tags))
7638 " ")))))
7640 (defun org-heading-components ()
7641 "Return the components of the current heading.
7642 This is a list with the following elements:
7643 - the level as an integer
7644 - the reduced level, different if `org-odd-levels-only' is set.
7645 - the TODO keyword, or nil
7646 - the priority character, like ?A, or nil if no priority is given
7647 - the headline text itself, or the tags string if no headline text
7648 - the tags string, or nil."
7649 (save-excursion
7650 (org-back-to-heading t)
7651 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7652 (list (length (match-string 1))
7653 (org-reduced-level (length (match-string 1)))
7654 (match-string-no-properties 2)
7655 (and (match-end 3) (aref (match-string 3) 2))
7656 (match-string-no-properties 4)
7657 (match-string-no-properties 5)))))
7659 (defun org-get-entry ()
7660 "Get the entry text, after heading, entire subtree."
7661 (save-excursion
7662 (org-back-to-heading t)
7663 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7665 (defun org-edit-headline (&optional heading)
7666 "Edit the current headline.
7667 Set it to HEADING when provided."
7668 (interactive)
7669 (org-with-wide-buffer
7670 (org-back-to-heading t)
7671 (let ((case-fold-search nil))
7672 (when (looking-at org-complex-heading-regexp)
7673 (let* ((old (match-string-no-properties 4))
7674 (new (save-match-data
7675 (org-trim (or heading (read-string "Edit: " old))))))
7676 (unless (equal old new)
7677 (if old (replace-match new t t nil 4)
7678 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7679 (insert " " new))
7680 (org-set-tags nil t)
7681 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7683 (defun org-insert-heading-after-current ()
7684 "Insert a new heading with same level as current, after current subtree."
7685 (interactive)
7686 (org-back-to-heading)
7687 (org-insert-heading)
7688 (org-move-subtree-down)
7689 (end-of-line 1))
7691 (defun org-insert-heading-respect-content (&optional invisible-ok)
7692 "Insert heading with `org-insert-heading-respect-content' set to t."
7693 (interactive)
7694 (org-insert-heading '(4) invisible-ok))
7696 (defun org-insert-todo-heading-respect-content (&optional force-state)
7697 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7698 (interactive)
7699 (org-insert-todo-heading force-state '(4)))
7701 (defun org-insert-todo-heading (arg &optional force-heading)
7702 "Insert a new heading with the same level and TODO state as current heading.
7704 If the heading has no TODO state, or if the state is DONE, use
7705 the first state (TODO by default). Also with one prefix arg,
7706 force first state. With two prefix args, force inserting at the
7707 end of the parent subtree.
7709 When called at a plain list item, insert a new item with an
7710 unchecked check box."
7711 (interactive "P")
7712 (when (or force-heading (not (org-insert-item 'checkbox)))
7713 (org-insert-heading (or (and (equal arg '(16)) '(16))
7714 force-heading))
7715 (save-excursion
7716 (org-forward-heading-same-level -1)
7717 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7718 (let* ((new-mark-x
7719 (if (or (equal arg '(4))
7720 (not (match-beginning 2))
7721 (member (match-string 2) org-done-keywords))
7722 (car org-todo-keywords-1)
7723 (match-string 2)))
7724 (new-mark
7726 (run-hook-with-args-until-success
7727 'org-todo-get-default-hook new-mark-x nil)
7728 new-mark-x)))
7729 (beginning-of-line 1)
7730 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7731 (if org-treat-insert-todo-heading-as-state-change
7732 (org-todo new-mark)
7733 (insert new-mark " "))))
7734 (when org-provide-todo-statistics
7735 (org-update-parent-todo-statistics))))
7737 (defun org-insert-subheading (arg)
7738 "Insert a new subheading and demote it.
7739 Works for outline headings and for plain lists alike."
7740 (interactive "P")
7741 (org-insert-heading arg)
7742 (cond
7743 ((org-at-heading-p) (org-do-demote))
7744 ((org-at-item-p) (org-indent-item))))
7746 (defun org-insert-todo-subheading (arg)
7747 "Insert a new subheading with TODO keyword or checkbox and demote it.
7748 Works for outline headings and for plain lists alike."
7749 (interactive "P")
7750 (org-insert-todo-heading arg)
7751 (cond
7752 ((org-at-heading-p) (org-do-demote))
7753 ((org-at-item-p) (org-indent-item))))
7755 ;;; Promotion and Demotion
7757 (defvar org-after-demote-entry-hook nil
7758 "Hook run after an entry has been demoted.
7759 The cursor will be at the beginning of the entry.
7760 When a subtree is being demoted, the hook will be called for each node.")
7762 (defvar org-after-promote-entry-hook nil
7763 "Hook run after an entry has been promoted.
7764 The cursor will be at the beginning of the entry.
7765 When a subtree is being promoted, the hook will be called for each node.")
7767 (defun org-promote-subtree ()
7768 "Promote the entire subtree.
7769 See also `org-promote'."
7770 (interactive)
7771 (save-excursion
7772 (org-with-limited-levels (org-map-tree 'org-promote)))
7773 (org-fix-position-after-promote))
7775 (defun org-demote-subtree ()
7776 "Demote the entire subtree.
7777 See `org-demote' and `org-promote'."
7778 (interactive)
7779 (save-excursion
7780 (org-with-limited-levels (org-map-tree 'org-demote)))
7781 (org-fix-position-after-promote))
7783 (defun org-do-promote ()
7784 "Promote the current heading higher up the tree.
7785 If the region is active in `transient-mark-mode', promote all
7786 headings in the region."
7787 (interactive)
7788 (save-excursion
7789 (if (org-region-active-p)
7790 (org-map-region 'org-promote (region-beginning) (region-end))
7791 (org-promote)))
7792 (org-fix-position-after-promote))
7794 (defun org-do-demote ()
7795 "Demote the current heading lower down the tree.
7796 If the region is active in `transient-mark-mode', demote all
7797 headings in the region."
7798 (interactive)
7799 (save-excursion
7800 (if (org-region-active-p)
7801 (org-map-region 'org-demote (region-beginning) (region-end))
7802 (org-demote)))
7803 (org-fix-position-after-promote))
7805 (defun org-fix-position-after-promote ()
7806 "Fix cursor position and indentation after demoting/promoting."
7807 (let ((pos (point)))
7808 (when (save-excursion
7809 (beginning-of-line)
7810 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7811 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7812 (cond ((eobp) (insert " "))
7813 ((eolp) (insert " "))
7814 ((equal (char-after) ?\s) (forward-char 1))))))
7816 (defun org-current-level ()
7817 "Return the level of the current entry, or nil if before the first headline.
7818 The level is the number of stars at the beginning of the
7819 headline. Use `org-reduced-level' to remove the effect of
7820 `org-odd-levels'. Unlike to `org-outline-level', this function
7821 ignores inlinetasks."
7822 (let ((level (org-with-limited-levels (org-outline-level))))
7823 (and (> level 0) level)))
7825 (defun org-get-previous-line-level ()
7826 "Return the outline depth of the last headline before the current line.
7827 Returns 0 for the first headline in the buffer, and nil if before the
7828 first headline."
7829 (and (org-current-level)
7830 (or (and (/= (line-beginning-position) (point-min))
7831 (save-excursion (beginning-of-line 0) (org-current-level)))
7832 0)))
7834 (defun org-reduced-level (l)
7835 "Compute the effective level of a heading.
7836 This takes into account the setting of `org-odd-levels-only'."
7837 (cond
7838 ((zerop l) 0)
7839 (org-odd-levels-only (1+ (floor (/ l 2))))
7840 (t l)))
7842 (defun org-level-increment ()
7843 "Return the number of stars that will be added or removed at a
7844 time to headlines when structure editing, based on the value of
7845 `org-odd-levels-only'."
7846 (if org-odd-levels-only 2 1))
7848 (defun org-get-valid-level (level &optional change)
7849 "Rectify a level change under the influence of `org-odd-levels-only'.
7850 LEVEL is a current level, CHANGE is by how much the level should
7851 be modified. Even if CHANGE is nil, LEVEL may be returned
7852 modified because even level numbers will become the next higher
7853 odd number. Returns values greater than 0."
7854 (if org-odd-levels-only
7855 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7856 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7857 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7858 (max 1 (+ level (or change 0)))))
7860 (defun org-promote ()
7861 "Promote the current heading higher up the tree."
7862 (org-with-wide-buffer
7863 (org-back-to-heading t)
7864 (let* ((after-change-functions (remq 'flyspell-after-change-function
7865 after-change-functions))
7866 (level (save-match-data (funcall outline-level)))
7867 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7868 (diff (abs (- level (length up-head) -1))))
7869 (cond
7870 ((and (= level 1) org-allow-promoting-top-level-subtree)
7871 (replace-match "# " nil t))
7872 ((= level 1)
7873 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7874 (t (replace-match up-head nil t)))
7875 (unless (= level 1)
7876 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7877 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7878 (run-hooks 'org-after-promote-entry-hook))))
7880 (defun org-demote ()
7881 "Demote the current heading lower down the tree."
7882 (org-with-wide-buffer
7883 (org-back-to-heading t)
7884 (let* ((after-change-functions (remq 'flyspell-after-change-function
7885 after-change-functions))
7886 (level (save-match-data (funcall outline-level)))
7887 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7888 (diff (abs (- level (length down-head) -1))))
7889 (replace-match down-head nil t)
7890 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7891 (when org-adapt-indentation (org-fixup-indentation diff))
7892 (run-hooks 'org-after-demote-entry-hook))))
7894 (defun org-cycle-level ()
7895 "Cycle the level of an empty headline through possible states.
7896 This goes first to child, then to parent, level, then up the hierarchy.
7897 After top level, it switches back to sibling level."
7898 (interactive)
7899 (let ((org-adapt-indentation nil))
7900 (when (org-point-at-end-of-empty-headline)
7901 (setq this-command 'org-cycle-level) ; Only needed for caching
7902 (let ((cur-level (org-current-level))
7903 (prev-level (org-get-previous-line-level)))
7904 (cond
7905 ;; If first headline in file, promote to top-level.
7906 ((= prev-level 0)
7907 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7908 do (org-do-promote)))
7909 ;; If same level as prev, demote one.
7910 ((= prev-level cur-level)
7911 (org-do-demote))
7912 ;; If parent is top-level, promote to top level if not already.
7913 ((= prev-level 1)
7914 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7915 do (org-do-promote)))
7916 ;; If top-level, return to prev-level.
7917 ((= cur-level 1)
7918 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7919 do (org-do-demote)))
7920 ;; If less than prev-level, promote one.
7921 ((< cur-level prev-level)
7922 (org-do-promote))
7923 ;; If deeper than prev-level, promote until higher than
7924 ;; prev-level.
7925 ((> cur-level prev-level)
7926 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7927 do (org-do-promote))))
7928 t))))
7930 (defun org-map-tree (fun)
7931 "Call FUN for every heading underneath the current one."
7932 (org-back-to-heading t)
7933 (let ((level (funcall outline-level)))
7934 (save-excursion
7935 (funcall fun)
7936 (while (and (progn
7937 (outline-next-heading)
7938 (> (funcall outline-level) level))
7939 (not (eobp)))
7940 (funcall fun)))))
7942 (defun org-map-region (fun beg end)
7943 "Call FUN for every heading between BEG and END."
7944 (let ((org-ignore-region t))
7945 (save-excursion
7946 (setq end (copy-marker end))
7947 (goto-char beg)
7948 (when (and (re-search-forward org-outline-regexp-bol nil t)
7949 (< (point) end))
7950 (funcall fun))
7951 (while (and (progn
7952 (outline-next-heading)
7953 (< (point) end))
7954 (not (eobp)))
7955 (funcall fun)))))
7957 (defun org-fixup-indentation (diff)
7958 "Change the indentation in the current entry by DIFF.
7960 DIFF is an integer. Indentation is done according to the
7961 following rules:
7963 - Planning information and property drawers are always indented
7964 according to the new level of the headline;
7966 - Footnote definitions and their contents are ignored;
7968 - Inlinetasks' boundaries are not shifted;
7970 - Empty lines are ignored;
7972 - Other lines' indentation are shifted by DIFF columns, unless
7973 it would introduce a structural change in the document, in
7974 which case no shifting is done at all.
7976 Assume point is at a heading or an inlinetask beginning."
7977 (org-with-wide-buffer
7978 (narrow-to-region (line-beginning-position)
7979 (save-excursion
7980 (if (org-with-limited-levels (org-at-heading-p))
7981 (org-with-limited-levels (outline-next-heading))
7982 (org-inlinetask-goto-end))
7983 (point)))
7984 (forward-line)
7985 ;; Indent properly planning info and property drawer.
7986 (when (looking-at-p org-planning-line-re)
7987 (org-indent-line)
7988 (forward-line))
7989 (when (looking-at org-property-drawer-re)
7990 (goto-char (match-end 0))
7991 (forward-line)
7992 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7993 (catch 'no-shift
7994 (when (zerop diff) (throw 'no-shift nil))
7995 ;; If DIFF is negative, first check if a shift is possible at all
7996 ;; (e.g., it doesn't break structure). This can only happen if
7997 ;; some contents are not properly indented.
7998 (let ((case-fold-search t))
7999 (when (< diff 0)
8000 (let ((diff (- diff))
8001 (forbidden-re (concat org-outline-regexp
8002 "\\|"
8003 (substring org-footnote-definition-re 1))))
8004 (save-excursion
8005 (while (not (eobp))
8006 (cond
8007 ((looking-at-p "[ \t]*$") (forward-line))
8008 ((and (looking-at-p org-footnote-definition-re)
8009 (let ((e (org-element-at-point)))
8010 (and (eq (org-element-type e) 'footnote-definition)
8011 (goto-char (org-element-property :end e))))))
8012 ((looking-at-p org-outline-regexp) (forward-line))
8013 ;; Give up if shifting would move before column 0 or
8014 ;; if it would introduce a headline or a footnote
8015 ;; definition.
8017 (skip-chars-forward " \t")
8018 (let ((ind (current-column)))
8019 (when (or (< ind diff)
8020 (and (= ind diff) (looking-at-p forbidden-re)))
8021 (throw 'no-shift nil)))
8022 ;; Ignore contents of example blocks and source
8023 ;; blocks if their indentation is meant to be
8024 ;; preserved. Jump to block's closing line.
8025 (beginning-of-line)
8026 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8027 (let ((e (org-element-at-point)))
8028 (and (memq (org-element-type e)
8029 '(example-block src-block))
8030 (or org-src-preserve-indentation
8031 (org-element-property :preserve-indent e))
8032 (goto-char (org-element-property :end e))
8033 (progn (skip-chars-backward " \r\t\n")
8034 (beginning-of-line)
8035 t))))
8036 (forward-line))))))))
8037 ;; Shift lines but footnote definitions, inlinetasks boundaries
8038 ;; by DIFF. Also skip contents of source or example blocks
8039 ;; when indentation is meant to be preserved.
8040 (while (not (eobp))
8041 (cond
8042 ((and (looking-at-p org-footnote-definition-re)
8043 (let ((e (org-element-at-point)))
8044 (and (eq (org-element-type e) 'footnote-definition)
8045 (goto-char (org-element-property :end e))))))
8046 ((looking-at-p org-outline-regexp) (forward-line))
8047 ((looking-at-p "[ \t]*$") (forward-line))
8049 (indent-line-to (+ (org-get-indentation) diff))
8050 (beginning-of-line)
8051 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8052 (let ((e (org-element-at-point)))
8053 (and (memq (org-element-type e)
8054 '(example-block src-block))
8055 (or org-src-preserve-indentation
8056 (org-element-property :preserve-indent e))
8057 (goto-char (org-element-property :end e))
8058 (progn (skip-chars-backward " \r\t\n")
8059 (beginning-of-line)
8060 t))))
8061 (forward-line)))))))))
8063 (defun org-convert-to-odd-levels ()
8064 "Convert an Org file with all levels allowed to one with odd levels.
8065 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8066 level 5 etc."
8067 (interactive)
8068 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8069 (let ((outline-level 'org-outline-level)
8070 (org-odd-levels-only nil) n)
8071 (save-excursion
8072 (goto-char (point-min))
8073 (while (re-search-forward "^\\*\\*+ " nil t)
8074 (setq n (- (length (match-string 0)) 2))
8075 (while (>= (setq n (1- n)) 0)
8076 (org-demote))
8077 (end-of-line 1))))))
8079 (defun org-convert-to-oddeven-levels ()
8080 "Convert an Org file with only odd levels to one with odd/even levels.
8081 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8082 file contains a section with an even level, conversion would
8083 destroy the structure of the file. An error is signaled in this
8084 case."
8085 (interactive)
8086 (goto-char (point-min))
8087 ;; First check if there are no even levels
8088 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8089 (org-show-set-visibility 'canonical)
8090 (error "Not all levels are odd in this file. Conversion not possible"))
8091 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8092 (let ((outline-regexp org-outline-regexp)
8093 (outline-level 'org-outline-level)
8094 (org-odd-levels-only nil) n)
8095 (save-excursion
8096 (goto-char (point-min))
8097 (while (re-search-forward "^\\*\\*+ " nil t)
8098 (setq n (/ (1- (length (match-string 0))) 2))
8099 (while (>= (setq n (1- n)) 0)
8100 (org-promote))
8101 (end-of-line 1))))))
8103 (defun org-tr-level (n)
8104 "Make N odd if required."
8105 (if org-odd-levels-only (1+ (/ n 2)) n))
8107 ;;; Vertical tree motion, cutting and pasting of subtrees
8109 (defun org-move-subtree-up (&optional arg)
8110 "Move the current subtree up past ARG headlines of the same level."
8111 (interactive "p")
8112 (org-move-subtree-down (- (prefix-numeric-value arg))))
8114 (defun org-move-subtree-down (&optional arg)
8115 "Move the current subtree down past ARG headlines of the same level."
8116 (interactive "p")
8117 (setq arg (prefix-numeric-value arg))
8118 (org-preserve-local-variables
8119 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8120 'org-get-last-sibling))
8121 (ins-point (make-marker))
8122 (cnt (abs arg))
8123 (col (current-column))
8124 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8125 ;; Select the tree
8126 (org-back-to-heading)
8127 (setq beg0 (point))
8128 (save-excursion
8129 (setq ne-beg (org-back-over-empty-lines))
8130 (setq beg (point)))
8131 (save-match-data
8132 (save-excursion (outline-end-of-heading)
8133 (setq folded (org-invisible-p)))
8134 (progn (org-end-of-subtree nil t)
8135 (unless (eobp) (backward-char))))
8136 (outline-next-heading)
8137 (setq ne-end (org-back-over-empty-lines))
8138 (setq end (point))
8139 (goto-char beg0)
8140 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8141 ;; include less whitespace
8142 (save-excursion
8143 (goto-char beg)
8144 (forward-line (- ne-beg ne-end))
8145 (setq beg (point))))
8146 ;; Find insertion point, with error handling
8147 (while (> cnt 0)
8148 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8149 (goto-char beg0)
8150 (user-error "Cannot move past superior level or buffer limit"))
8151 (setq cnt (1- cnt)))
8152 (when (> arg 0)
8153 ;; Moving forward - still need to move over subtree
8154 (org-end-of-subtree t t)
8155 (save-excursion
8156 (org-back-over-empty-lines)
8157 (or (bolp) (newline))))
8158 (setq ne-ins (org-back-over-empty-lines))
8159 (move-marker ins-point (point))
8160 (setq txt (buffer-substring beg end))
8161 (org-save-markers-in-region beg end)
8162 (delete-region beg end)
8163 (org-remove-empty-overlays-at beg)
8164 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8165 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8166 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8167 (let ((bbb (point)))
8168 (insert-before-markers txt)
8169 (org-reinstall-markers-in-region bbb)
8170 (move-marker ins-point bbb))
8171 (or (bolp) (insert "\n"))
8172 (setq ins-end (point))
8173 (goto-char ins-point)
8174 (org-skip-whitespace)
8175 (when (and (< arg 0)
8176 (org-first-sibling-p)
8177 (> ne-ins ne-beg))
8178 ;; Move whitespace back to beginning
8179 (save-excursion
8180 (goto-char ins-end)
8181 (let ((kill-whole-line t))
8182 (kill-line (- ne-ins ne-beg)) (point)))
8183 (insert (make-string (- ne-ins ne-beg) ?\n)))
8184 (move-marker ins-point nil)
8185 (if folded
8186 (outline-hide-subtree)
8187 (org-show-entry)
8188 (org-show-children))
8189 (org-clean-visibility-after-subtree-move)
8190 ;; move back to the initial column we were at
8191 (move-to-column col))))
8193 (defvar org-subtree-clip ""
8194 "Clipboard for cut and paste of subtrees.
8195 This is actually only a copy of the kill, because we use the normal kill
8196 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8198 (defvar org-subtree-clip-folded nil
8199 "Was the last copied subtree folded?
8200 This is used to fold the tree back after pasting.")
8202 (defun org-cut-subtree (&optional n)
8203 "Cut the current subtree into the clipboard.
8204 With prefix arg N, cut this many sequential subtrees.
8205 This is a short-hand for marking the subtree and then cutting it."
8206 (interactive "p")
8207 (org-copy-subtree n 'cut))
8209 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8210 "Copy the current subtree into the clipboard.
8211 With prefix arg N, copy this many sequential subtrees.
8212 This is a short-hand for marking the subtree and then copying it.
8213 If CUT is non-nil, actually cut the subtree.
8214 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8215 of some markers in the region, even if CUT is non-nil. This is
8216 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8217 (interactive "p")
8218 (org-preserve-local-variables
8219 (let (beg end folded (beg0 (point)))
8220 (if (called-interactively-p 'any)
8221 (org-back-to-heading nil) ; take what looks like a subtree
8222 (org-back-to-heading t)) ; take what is really there
8223 (setq beg (point))
8224 (skip-chars-forward " \t\r\n")
8225 (save-match-data
8226 (if nosubtrees
8227 (outline-next-heading)
8228 (save-excursion (outline-end-of-heading)
8229 (setq folded (org-invisible-p)))
8230 (ignore-errors (org-forward-heading-same-level (1- n) t))
8231 (org-end-of-subtree t t)))
8232 ;; Include the end of an inlinetask
8233 (when (and (featurep 'org-inlinetask)
8234 (looking-at-p (concat (org-inlinetask-outline-regexp)
8235 "END[ \t]*$")))
8236 (end-of-line))
8237 (setq end (point))
8238 (goto-char beg0)
8239 (when (> end beg)
8240 (setq org-subtree-clip-folded folded)
8241 (when (or cut force-store-markers)
8242 (org-save-markers-in-region beg end))
8243 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8244 (setq org-subtree-clip (current-kill 0))
8245 (message "%s: Subtree(s) with %d characters"
8246 (if cut "Cut" "Copied")
8247 (length org-subtree-clip))))))
8249 (defun org-paste-subtree (&optional level tree for-yank remove)
8250 "Paste the clipboard as a subtree, with modification of headline level.
8251 The entire subtree is promoted or demoted in order to match a new headline
8252 level.
8254 If the cursor is at the beginning of a headline, the same level as
8255 that headline is used to paste the tree.
8257 If not, the new level is derived from the *visible* headings
8258 before and after the insertion point, and taken to be the inferior headline
8259 level of the two. So if the previous visible heading is level 3 and the
8260 next is level 4 (or vice versa), level 4 will be used for insertion.
8261 This makes sure that the subtree remains an independent subtree and does
8262 not swallow low level entries.
8264 You can also force a different level, either by using a numeric prefix
8265 argument, or by inserting the heading marker by hand. For example, if the
8266 cursor is after \"*****\", then the tree will be shifted to level 5.
8268 If optional TREE is given, use this text instead of the kill ring.
8270 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8271 move back over whitespace before inserting, and move point to the end of
8272 the inserted text when done.
8274 When REMOVE is non-nil, remove the subtree from the clipboard."
8275 (interactive "P")
8276 (setq tree (or tree (and kill-ring (current-kill 0))))
8277 (unless (org-kill-is-subtree-p tree)
8278 (user-error "%s"
8279 (substitute-command-keys
8280 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8281 (org-with-limited-levels
8282 (let* ((visp (not (org-invisible-p)))
8283 (txt tree)
8284 (^re_ "\\(\\*+\\)[ \t]*")
8285 (old-level (if (string-match org-outline-regexp-bol txt)
8286 (- (match-end 0) (match-beginning 0) 1)
8287 -1))
8288 (force-level (cond (level (prefix-numeric-value level))
8289 ((and (looking-at "[ \t]*$")
8290 (string-match
8291 "^\\*+$" (buffer-substring
8292 (point-at-bol) (point))))
8293 (- (match-end 0) (match-beginning 0)))
8294 ((and (bolp)
8295 (looking-at org-outline-regexp))
8296 (- (match-end 0) (point) 1))))
8297 (previous-level (save-excursion
8298 (condition-case nil
8299 (progn
8300 (outline-previous-visible-heading 1)
8301 (if (looking-at ^re_)
8302 (- (match-end 0) (match-beginning 0) 1)
8304 (error 1))))
8305 (next-level (save-excursion
8306 (condition-case nil
8307 (progn
8308 (or (looking-at org-outline-regexp)
8309 (outline-next-visible-heading 1))
8310 (if (looking-at ^re_)
8311 (- (match-end 0) (match-beginning 0) 1)
8313 (error 1))))
8314 (new-level (or force-level (max previous-level next-level)))
8315 (shift (if (or (= old-level -1)
8316 (= new-level -1)
8317 (= old-level new-level))
8319 (- new-level old-level)))
8320 (delta (if (> shift 0) -1 1))
8321 (func (if (> shift 0) 'org-demote 'org-promote))
8322 (org-odd-levels-only nil)
8323 beg end newend)
8324 ;; Remove the forced level indicator
8325 (when force-level
8326 (delete-region (point-at-bol) (point)))
8327 ;; Paste
8328 (beginning-of-line (if (bolp) 1 2))
8329 (setq beg (point))
8330 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8331 (insert-before-markers txt)
8332 (unless (string-suffix-p "\n" txt) (insert "\n"))
8333 (setq newend (point))
8334 (org-reinstall-markers-in-region beg)
8335 (setq end (point))
8336 (goto-char beg)
8337 (skip-chars-forward " \t\n\r")
8338 (setq beg (point))
8339 (when (and (org-invisible-p) visp)
8340 (save-excursion (outline-show-heading)))
8341 ;; Shift if necessary
8342 (unless (= shift 0)
8343 (save-restriction
8344 (narrow-to-region beg end)
8345 (while (not (= shift 0))
8346 (org-map-region func (point-min) (point-max))
8347 (setq shift (+ delta shift)))
8348 (goto-char (point-min))
8349 (setq newend (point-max))))
8350 (when (or (called-interactively-p 'interactive) for-yank)
8351 (message "Clipboard pasted as level %d subtree" new-level))
8352 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8353 kill-ring
8354 (eq org-subtree-clip (current-kill 0))
8355 org-subtree-clip-folded)
8356 ;; The tree was folded before it was killed/copied
8357 (outline-hide-subtree))
8358 (and for-yank (goto-char newend))
8359 (and remove (setq kill-ring (cdr kill-ring))))))
8361 (defun org-kill-is-subtree-p (&optional txt)
8362 "Check if the current kill is an outline subtree, or a set of trees.
8363 Returns nil if kill does not start with a headline, or if the first
8364 headline level is not the largest headline level in the tree.
8365 So this will actually accept several entries of equal levels as well,
8366 which is OK for `org-paste-subtree'.
8367 If optional TXT is given, check this string instead of the current kill."
8368 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8369 (re (org-get-limited-outline-regexp))
8370 (^re (concat "^" re))
8371 (start-level (and kill
8372 (string-match
8373 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8374 kill)
8375 (- (match-end 2) (match-beginning 2) 1)))
8376 (start (1+ (or (match-beginning 2) -1))))
8377 (if (not start-level)
8378 (progn
8379 nil) ;; does not even start with a heading
8380 (catch 'exit
8381 (while (setq start (string-match ^re kill (1+ start)))
8382 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8383 (throw 'exit nil)))
8384 t))))
8386 (defvar org-markers-to-move nil
8387 "Markers that should be moved with a cut-and-paste operation.
8388 Those markers are stored together with their positions relative to
8389 the start of the region.")
8391 (defun org-save-markers-in-region (beg end)
8392 "Check markers in region.
8393 If these markers are between BEG and END, record their position relative
8394 to BEG, so that after moving the block of text, we can put the markers back
8395 into place.
8396 This function gets called just before an entry or tree gets cut from the
8397 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8398 called immediately, to move the markers with the entries."
8399 (setq org-markers-to-move nil)
8400 (when (featurep 'org-clock)
8401 (org-clock-save-markers-for-cut-and-paste beg end))
8402 (when (featurep 'org-agenda)
8403 (org-agenda-save-markers-for-cut-and-paste beg end)))
8405 (defun org-check-and-save-marker (marker beg end)
8406 "Check if MARKER is between BEG and END.
8407 If yes, remember the marker and the distance to BEG."
8408 (when (and (marker-buffer marker)
8409 (equal (marker-buffer marker) (current-buffer))
8410 (>= marker beg) (< marker end))
8411 (push (cons marker (- marker beg)) org-markers-to-move)))
8413 (defun org-reinstall-markers-in-region (beg)
8414 "Move all remembered markers to their position relative to BEG."
8415 (dolist (x org-markers-to-move)
8416 (move-marker (car x) (+ beg (cdr x))))
8417 (setq org-markers-to-move nil))
8419 (defun org-narrow-to-subtree ()
8420 "Narrow buffer to the current subtree."
8421 (interactive)
8422 (save-excursion
8423 (save-match-data
8424 (org-with-limited-levels
8425 (narrow-to-region
8426 (progn (org-back-to-heading t) (point))
8427 (progn (org-end-of-subtree t t)
8428 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8429 (point)))))))
8431 (defun org-narrow-to-block ()
8432 "Narrow buffer to the current block."
8433 (interactive)
8434 (let* ((case-fold-search t)
8435 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8436 "^[ \t]*#\\+end_.*")))
8437 (if blockp
8438 (narrow-to-region (car blockp) (cdr blockp))
8439 (user-error "Not in a block"))))
8441 (defun org-clone-subtree-with-time-shift (n &optional shift)
8442 "Clone the task (subtree) at point N times.
8443 The clones will be inserted as siblings.
8445 In interactive use, the user will be prompted for the number of
8446 clones to be produced. If the entry has a timestamp, the user
8447 will also be prompted for a time shift, which may be a repeater
8448 as used in time stamps, for example `+3d'. To disable this,
8449 you can call the function with a universal prefix argument.
8451 When a valid repeater is given and the entry contains any time
8452 stamps, the clones will become a sequence in time, with time
8453 stamps in the subtree shifted for each clone produced. If SHIFT
8454 is nil or the empty string, time stamps will be left alone. The
8455 ID property of the original subtree is removed.
8457 In each clone, all the CLOCK entries will be removed. This
8458 prevents Org from considering that the clocked times overlap.
8460 If the original subtree did contain time stamps with a repeater,
8461 the following will happen:
8462 - the repeater will be removed in each clone
8463 - an additional clone will be produced, with the current, unshifted
8464 date(s) in the entry.
8465 - the original entry will be placed *after* all the clones, with
8466 repeater intact.
8467 - the start days in the repeater in the original entry will be shifted
8468 to past the last clone.
8469 In this way you can spell out a number of instances of a repeating task,
8470 and still retain the repeater to cover future instances of the task.
8472 As described above, N+1 clones are produced when the original
8473 subtree has a repeater. Setting N to 0, then, can be used to
8474 remove the repeater from a subtree and create a shifted clone
8475 with the original repeater."
8476 (interactive "nNumber of clones to produce: ")
8477 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8478 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8479 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8480 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8481 (shift
8482 (or shift
8483 (if (and (not (equal current-prefix-arg '(4)))
8484 (save-excursion
8485 (goto-char beg)
8486 (re-search-forward org-ts-regexp-both end-of-tree t)))
8487 (read-from-minibuffer
8488 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8489 ""))) ;No time shift
8490 (doshift
8491 (and (org-string-nw-p shift)
8492 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8493 shift)
8494 (user-error "Invalid shift specification %s" shift)))))
8495 (goto-char end-of-tree)
8496 (unless (bolp) (insert "\n"))
8497 (let* ((end (point))
8498 (template (buffer-substring beg end))
8499 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8500 (shift-what (pcase (and doshift (match-string 2 shift))
8501 (`nil nil)
8502 ("d" 'day)
8503 ("w" (setq shift-n (* 7 shift-n)) 'day)
8504 ("m" 'month)
8505 ("y" 'year)
8506 (_ (error "Unsupported time unit"))))
8507 (nmin 1)
8508 (nmax n)
8509 (n-no-remove -1)
8510 (idprop (org-entry-get nil "ID")))
8511 (when (and doshift
8512 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8513 template))
8514 (delete-region beg end)
8515 (setq end beg)
8516 (setq nmin 0)
8517 (setq nmax (1+ nmax))
8518 (setq n-no-remove nmax))
8519 (goto-char end)
8520 (cl-loop for n from nmin to nmax do
8521 (insert
8522 ;; Prepare clone.
8523 (with-temp-buffer
8524 (insert template)
8525 (org-mode)
8526 (goto-char (point-min))
8527 (org-show-subtree)
8528 (and idprop (if org-clone-delete-id
8529 (org-entry-delete nil "ID")
8530 (org-id-get-create t)))
8531 (unless (= n 0)
8532 (while (re-search-forward org-clock-line-re nil t)
8533 (delete-region (line-beginning-position)
8534 (line-beginning-position 2)))
8535 (goto-char (point-min))
8536 (while (re-search-forward org-drawer-regexp nil t)
8537 (org-remove-empty-drawer-at (point))))
8538 (goto-char (point-min))
8539 (when doshift
8540 (while (re-search-forward org-ts-regexp-both nil t)
8541 (org-timestamp-change (* n shift-n) shift-what))
8542 (unless (= n n-no-remove)
8543 (goto-char (point-min))
8544 (while (re-search-forward org-ts-regexp nil t)
8545 (save-excursion
8546 (goto-char (match-beginning 0))
8547 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8548 (delete-region (match-beginning 1) (match-end 1)))))))
8549 (buffer-string)))))
8550 (goto-char beg)))
8552 ;;; Outline Sorting
8554 (defun org-sort (&optional with-case)
8555 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8556 Optional argument WITH-CASE means sort case-sensitively."
8557 (interactive "P")
8558 (org-call-with-arg
8559 (cond ((org-at-table-p) #'org-table-sort-lines)
8560 ((org-at-item-p) #'org-sort-list)
8561 (t #'org-sort-entries))
8562 with-case))
8564 (defun org-sort-remove-invisible (s)
8565 "Remove invisible part of links and emphasis markers from string S."
8566 (remove-text-properties 0 (length s) org-rm-props s)
8567 (replace-regexp-in-string
8568 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8569 (replace-regexp-in-string
8570 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8571 (org-link-display-format s)
8572 t t) t t))
8574 (defvar org-priority-regexp) ; defined later in the file
8576 (defvar org-after-sorting-entries-or-items-hook nil
8577 "Hook that is run after a bunch of entries or items have been sorted.
8578 When children are sorted, the cursor is in the parent line when this
8579 hook gets called. When a region or a plain list is sorted, the cursor
8580 will be in the first entry of the sorted region/list.")
8582 (defun org-sort-entries
8583 (&optional with-case sorting-type getkey-func compare-func property
8584 interactive?)
8585 "Sort entries on a certain level of an outline tree.
8586 If there is an active region, the entries in the region are sorted.
8587 Else, if the cursor is before the first entry, sort the top-level items.
8588 Else, the children of the entry at point are sorted.
8590 Sorting can be alphabetically, numerically, by date/time as given by
8591 a time stamp, by a property, by priority order, or by a custom function.
8593 The command prompts for the sorting type unless it has been given to the
8594 function through the SORTING-TYPE argument, which needs to be a character,
8595 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8596 the precise meaning of each character:
8598 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8599 c By creation time, which is assumed to be the first inactive time stamp
8600 at the beginning of a line.
8601 d By deadline date/time.
8602 k By clocking time.
8603 n Numerically, by converting the beginning of the entry/item to a number.
8604 o By order of TODO keywords.
8605 p By priority according to the cookie.
8606 r By the value of a property.
8607 s By scheduled date/time.
8608 t By date/time, either the first active time stamp in the entry, or, if
8609 none exist, by the first inactive one.
8611 Capital letters will reverse the sort order.
8613 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8614 called with point at the beginning of the record. It must return a
8615 value that is compatible with COMPARE-FUNC, the function used to
8616 compare entries.
8618 Comparing entries ignores case by default. However, with an optional argument
8619 WITH-CASE, the sorting considers case as well.
8621 Sorting is done against the visible part of the headlines, it ignores hidden
8622 links.
8624 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8626 A non-nil value for INTERACTIVE? is used to signal that this
8627 function is being called interactively."
8628 (interactive (list current-prefix-arg nil nil nil nil t))
8629 (let ((case-func (if with-case 'identity 'downcase))
8630 start beg end stars re re2
8631 txt what tmp)
8632 ;; Find beginning and end of region to sort
8633 (cond
8634 ((org-region-active-p)
8635 ;; we will sort the region
8636 (setq end (region-end)
8637 what "region")
8638 (goto-char (region-beginning))
8639 (unless (org-at-heading-p) (outline-next-heading))
8640 (setq start (point)))
8641 ((or (org-at-heading-p)
8642 (ignore-errors (progn (org-back-to-heading) t)))
8643 ;; we will sort the children of the current headline
8644 (org-back-to-heading)
8645 (setq start (point)
8646 end (progn (org-end-of-subtree t t)
8647 (or (bolp) (insert "\n"))
8648 (when (>= (org-back-over-empty-lines) 1)
8649 (forward-line 1))
8650 (point))
8651 what "children")
8652 (goto-char start)
8653 (outline-show-subtree)
8654 (outline-next-heading))
8656 ;; we will sort the top-level entries in this file
8657 (goto-char (point-min))
8658 (or (org-at-heading-p) (outline-next-heading))
8659 (setq start (point))
8660 (goto-char (point-max))
8661 (beginning-of-line 1)
8662 (when (looking-at ".*?\\S-")
8663 ;; File ends in a non-white line
8664 (end-of-line 1)
8665 (insert "\n"))
8666 (setq end (point-max))
8667 (setq what "top-level")
8668 (goto-char start)
8669 (org-show-all '(headings blocks))))
8671 (setq beg (point))
8672 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8674 (looking-at "\\(\\*+\\)")
8675 (setq stars (match-string 1)
8676 re (concat "^" (regexp-quote stars) " +")
8677 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8678 txt (buffer-substring beg end))
8679 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8680 (when (and (not (equal stars "*")) (string-match re2 txt))
8681 (user-error "Region to sort contains a level above the first entry"))
8683 (unless sorting-type
8684 (message
8685 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8686 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8687 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8688 what)
8689 (setq sorting-type (read-char-exclusive)))
8691 (unless getkey-func
8692 (and (= (downcase sorting-type) ?f)
8693 (setq getkey-func
8694 (or (and interactive?
8695 (org-read-function
8696 "Function for extracting keys: "))
8697 (error "Missing key extractor")))))
8699 (and (= (downcase sorting-type) ?r)
8700 (not property)
8701 (setq property
8702 (completing-read "Property: "
8703 (mapcar #'list (org-buffer-property-keys t))
8704 nil t)))
8706 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8707 (message "Sorting entries...")
8709 (save-restriction
8710 (narrow-to-region start end)
8711 (let ((restore-clock?
8712 ;; The clock marker is lost when using `sort-subr'; mark
8713 ;; the clock with temporary `:org-clock-marker-backup'
8714 ;; text property.
8715 (when (and (eq (org-clock-is-active) (current-buffer))
8716 (<= start (marker-position org-clock-marker))
8717 (>= end (marker-position org-clock-marker)))
8718 (org-with-silent-modifications
8719 (put-text-property (1- org-clock-marker) org-clock-marker
8720 :org-clock-marker-backup t))
8722 (dcst (downcase sorting-type))
8723 (case-fold-search nil)
8724 (now (current-time)))
8725 (org-preserve-local-variables
8726 (sort-subr
8727 (/= dcst sorting-type)
8728 ;; This function moves to the beginning character of the
8729 ;; "record" to be sorted.
8730 (lambda nil
8731 (if (re-search-forward re nil t)
8732 (goto-char (match-beginning 0))
8733 (goto-char (point-max))))
8734 ;; This function moves to the last character of the "record" being
8735 ;; sorted.
8736 (lambda nil
8737 (save-match-data
8738 (condition-case nil
8739 (outline-forward-same-level 1)
8740 (error
8741 (goto-char (point-max))))))
8742 ;; This function returns the value that gets sorted against.
8743 (lambda ()
8744 (cond
8745 ((= dcst ?n)
8746 (if (looking-at org-complex-heading-regexp)
8747 (string-to-number
8748 (org-sort-remove-invisible (match-string 4)))
8749 nil))
8750 ((= dcst ?a)
8751 (if (looking-at org-complex-heading-regexp)
8752 (funcall case-func
8753 (org-sort-remove-invisible (match-string 4)))
8754 nil))
8755 ((= dcst ?k)
8756 (or (get-text-property (point) :org-clock-minutes) 0))
8757 ((= dcst ?t)
8758 (let ((end (save-excursion (outline-next-heading) (point))))
8759 (if (or (re-search-forward org-ts-regexp end t)
8760 (re-search-forward org-ts-regexp-both end t))
8761 (org-time-string-to-seconds (match-string 0))
8762 (float-time now))))
8763 ((= dcst ?c)
8764 (let ((end (save-excursion (outline-next-heading) (point))))
8765 (if (re-search-forward
8766 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8767 end t)
8768 (org-time-string-to-seconds (match-string 0))
8769 (float-time now))))
8770 ((= dcst ?s)
8771 (let ((end (save-excursion (outline-next-heading) (point))))
8772 (if (re-search-forward org-scheduled-time-regexp end t)
8773 (org-time-string-to-seconds (match-string 1))
8774 (float-time now))))
8775 ((= dcst ?d)
8776 (let ((end (save-excursion (outline-next-heading) (point))))
8777 (if (re-search-forward org-deadline-time-regexp end t)
8778 (org-time-string-to-seconds (match-string 1))
8779 (float-time now))))
8780 ((= dcst ?p)
8781 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8782 (string-to-char (match-string 2))
8783 org-default-priority))
8784 ((= dcst ?r)
8785 (or (org-entry-get nil property) ""))
8786 ((= dcst ?o)
8787 (when (looking-at org-complex-heading-regexp)
8788 (let* ((m (match-string 2))
8789 (s (if (member m org-done-keywords) '- '+)))
8790 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8791 ((= dcst ?f)
8792 (if getkey-func
8793 (progn
8794 (setq tmp (funcall getkey-func))
8795 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8796 tmp)
8797 (error "Invalid key function `%s'" getkey-func)))
8798 (t (error "Invalid sorting type `%c'" sorting-type))))
8800 (cond
8801 ((= dcst ?a) 'string<)
8802 ((= dcst ?f)
8803 (or compare-func
8804 (and interactive?
8805 (org-read-function
8806 (concat "Function for comparing keys "
8807 "(empty for default `sort-subr' predicate): ")
8808 'allow-empty))))
8809 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8810 (when restore-clock?
8811 (move-marker org-clock-marker
8812 (1+ (next-single-property-change
8813 start :org-clock-marker-backup)))
8814 (remove-text-properties (1- org-clock-marker) org-clock-marker
8815 '(:org-clock-marker-backup t)))))
8816 (run-hooks 'org-after-sorting-entries-or-items-hook)
8817 (message "Sorting entries...done")))
8819 (defun org-contextualize-keys (alist contexts)
8820 "Return valid elements in ALIST depending on CONTEXTS.
8822 `org-agenda-custom-commands' or `org-capture-templates' are the
8823 values used for ALIST, and `org-agenda-custom-commands-contexts'
8824 or `org-capture-templates-contexts' are the associated contexts
8825 definitions."
8826 (let ((contexts
8827 ;; normalize contexts
8828 (mapcar
8829 (lambda(c) (cond ((listp (cadr c))
8830 (list (car c) (car c) (nth 1 c)))
8831 ((string= "" (cadr c))
8832 (list (car c) (car c) (nth 2 c)))
8833 (t c)))
8834 contexts))
8835 (a alist) r s)
8836 ;; loop over all commands or templates
8837 (dolist (c a)
8838 (let (vrules repl)
8839 (cond
8840 ((not (assoc (car c) contexts))
8841 (push c r))
8842 ((and (assoc (car c) contexts)
8843 (setq vrules (org-contextualize-validate-key
8844 (car c) contexts)))
8845 (mapc (lambda (vr)
8846 (unless (equal (car vr) (cadr vr))
8847 (setq repl vr)))
8848 vrules)
8849 (if (not repl) (push c r)
8850 (push (cadr repl) s)
8851 (push
8852 (cons (car c)
8853 (cdr (or (assoc (cadr repl) alist)
8854 (error "Undefined key `%s' as contextual replacement for `%s'"
8855 (cadr repl) (car c)))))
8856 r))))))
8857 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8858 (delq
8860 (delete-dups
8861 (mapcar (lambda (x)
8862 (let ((tpl (car x)))
8863 (unless (delq
8865 (mapcar (lambda (y)
8866 (equal y tpl))
8868 x)))
8869 (reverse r))))))
8871 (defun org-contextualize-validate-key (key contexts)
8872 "Check CONTEXTS for agenda or capture KEY."
8873 (let (res)
8874 (dolist (r contexts)
8875 (dolist (rr (car (last r)))
8876 (when
8877 (and (equal key (car r))
8878 (if (functionp rr) (funcall rr)
8879 (or (and (eq (car rr) 'in-file)
8880 (buffer-file-name)
8881 (string-match (cdr rr) (buffer-file-name)))
8882 (and (eq (car rr) 'in-mode)
8883 (string-match (cdr rr) (symbol-name major-mode)))
8884 (and (eq (car rr) 'in-buffer)
8885 (string-match (cdr rr) (buffer-name)))
8886 (when (and (eq (car rr) 'not-in-file)
8887 (buffer-file-name))
8888 (not (string-match (cdr rr) (buffer-file-name))))
8889 (when (eq (car rr) 'not-in-mode)
8890 (not (string-match (cdr rr) (symbol-name major-mode))))
8891 (when (eq (car rr) 'not-in-buffer)
8892 (not (string-match (cdr rr) (buffer-name)))))))
8893 (push r res))))
8894 (delete-dups (delq nil res))))
8896 (defun org-context-p (&rest contexts)
8897 "Check if local context is any of CONTEXTS.
8898 Possible values in the list of contexts are `table', `headline', and `item'."
8899 (let ((pos (point)))
8900 (goto-char (point-at-bol))
8901 (prog1 (or (and (memq 'table contexts)
8902 (looking-at "[ \t]*|"))
8903 (and (memq 'headline contexts)
8904 (looking-at org-outline-regexp))
8905 (and (memq 'item contexts)
8906 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8907 (and (memq 'item-body contexts)
8908 (org-in-item-p)))
8909 (goto-char pos))))
8911 ;;;###autoload
8912 (defun org-run-like-in-org-mode (cmd)
8913 "Run a command, pretending that the current buffer is in Org mode.
8914 This will temporarily bind local variables that are typically bound in
8915 Org mode to the values they have in Org mode, and then interactively
8916 call CMD."
8917 (org-load-modules-maybe)
8918 (let (binds)
8919 (dolist (var (org-get-local-variables))
8920 (when (or (not (boundp (car var)))
8921 (eq (symbol-value (car var))
8922 (default-value (car var))))
8923 (push (list (car var) `(quote ,(cadr var))) binds)))
8924 (eval `(let ,binds
8925 (call-interactively (quote ,cmd))))))
8927 (defun org-get-category (&optional pos force-refresh)
8928 "Get the category applying to position POS."
8929 (save-match-data
8930 (when force-refresh (org-refresh-category-properties))
8931 (let ((pos (or pos (point))))
8932 (or (get-text-property pos 'org-category)
8933 (progn (org-refresh-category-properties)
8934 (get-text-property pos 'org-category))))))
8936 ;;; Refresh properties
8938 (defun org-refresh-properties (dprop tprop)
8939 "Refresh buffer text properties.
8940 DPROP is the drawer property and TPROP is either the
8941 corresponding text property to set, or an alist with each element
8942 being a text property (as a symbol) and a function to apply to
8943 the value of the drawer property."
8944 (let* ((case-fold-search t)
8945 (inhibit-read-only t)
8946 (inherit? (org-property-inherit-p dprop))
8947 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8948 (global (and inherit? (org--property-global-value dprop nil))))
8949 (org-with-silent-modifications
8950 (org-with-point-at 1
8951 ;; Set global values (e.g., values defined through
8952 ;; "#+PROPERTY:" keywords) to the whole buffer.
8953 (when global (put-text-property (point-min) (point-max) tprop global))
8954 ;; Set local values.
8955 (while (re-search-forward property-re nil t)
8956 (when (org-at-property-p)
8957 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8958 (outline-next-heading))))))
8960 (defun org-refresh-property (tprop p &optional inherit)
8961 "Refresh the buffer text property TPROP from the drawer property P.
8962 The refresh happens only for the current headline, or the whole
8963 sub-tree if optional argument INHERIT is non-nil."
8964 (unless (org-before-first-heading-p)
8965 (save-excursion
8966 (org-back-to-heading t)
8967 (let ((start (point))
8968 (end (save-excursion
8969 (if inherit (org-end-of-subtree t t)
8970 (or (outline-next-heading) (point-max))))))
8971 (if (symbolp tprop)
8972 ;; TPROP is a text property symbol.
8973 (put-text-property start end tprop p)
8974 ;; TPROP is an alist with (property . function) elements.
8975 (pcase-dolist (`(,prop . ,f) tprop)
8976 (put-text-property start end prop (funcall f p))))))))
8978 (defun org-refresh-category-properties ()
8979 "Refresh category text properties in the buffer."
8980 (let ((case-fold-search t)
8981 (inhibit-read-only t)
8982 (default-category
8983 (cond ((null org-category)
8984 (if buffer-file-name
8985 (file-name-sans-extension
8986 (file-name-nondirectory buffer-file-name))
8987 "???"))
8988 ((symbolp org-category) (symbol-name org-category))
8989 (t org-category))))
8990 (org-with-silent-modifications
8991 (org-with-wide-buffer
8992 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8993 ;; This is the default category for the buffer. If none is
8994 ;; found, fall-back to `org-category' or buffer file name.
8995 (put-text-property
8996 (point-min) (point-max)
8997 'org-category
8998 (catch 'buffer-category
8999 (goto-char (point-max))
9000 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9001 (let ((element (org-element-at-point)))
9002 (when (eq (org-element-type element) 'keyword)
9003 (throw 'buffer-category
9004 (org-element-property :value element)))))
9005 default-category))
9006 ;; Set sub-tree specific categories.
9007 (goto-char (point-min))
9008 (let ((regexp (org-re-property "CATEGORY")))
9009 (while (re-search-forward regexp nil t)
9010 (let ((value (match-string-no-properties 3)))
9011 (when (org-at-property-p)
9012 (put-text-property
9013 (save-excursion (org-back-to-heading t) (point))
9014 (save-excursion (org-end-of-subtree t t) (point))
9015 'org-category
9016 value)))))))))
9018 (defun org-refresh-stats-properties ()
9019 "Refresh stats text properties in the buffer."
9020 (org-with-silent-modifications
9021 (org-with-point-at 1
9022 (let ((regexp (concat org-outline-regexp-bol
9023 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9024 (while (re-search-forward regexp nil t)
9025 (let* ((numerator (string-to-number (match-string 1)))
9026 (denominator (and (match-end 2)
9027 (string-to-number (match-string 2))))
9028 (stats (cond ((not denominator) numerator) ;percent
9029 ((= denominator 0) 0)
9030 (t (/ (* numerator 100) denominator)))))
9031 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9032 'org-stats stats)))))))
9034 (defun org-refresh-effort-properties ()
9035 "Refresh effort properties"
9036 (org-refresh-properties
9037 org-effort-property
9038 '((effort . identity)
9039 (effort-minutes . org-duration-to-minutes))))
9041 ;;;; Link Stuff
9043 ;;; Link abbreviations
9045 (defun org-link-expand-abbrev (link)
9046 "Apply replacements as defined in `org-link-abbrev-alist'."
9047 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9048 (let* ((key (match-string 1 link))
9049 (as (or (assoc key org-link-abbrev-alist-local)
9050 (assoc key org-link-abbrev-alist)))
9051 (tag (and (match-end 2) (match-string 3 link)))
9052 rpl)
9053 (if (not as)
9054 link
9055 (setq rpl (cdr as))
9056 (cond
9057 ((symbolp rpl) (funcall rpl tag))
9058 ((string-match "%(\\([^)]+\\))" rpl)
9059 (replace-match
9060 (save-match-data
9061 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9062 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9063 ((string-match "%h" rpl)
9064 (replace-match (url-hexify-string (or tag "")) t t rpl))
9065 (t (concat rpl tag)))))
9066 link))
9068 ;;; Storing and inserting links
9070 (defvar org-insert-link-history nil
9071 "Minibuffer history for links inserted with `org-insert-link'.")
9073 (defvar org-stored-links nil
9074 "Contains the links stored with `org-store-link'.")
9076 (defvar org-store-link-plist nil
9077 "Plist with info about the most recently link created with `org-store-link'.")
9079 (defun org-store-link-functions ()
9080 "Return a list of functions that are called to create and store a link.
9081 The functions defined in the :store property of
9082 `org-link-parameters'.
9084 Each function will be called in turn until one returns a non-nil
9085 value. Each function should check if it is responsible for
9086 creating this link (for example by looking at the major mode).
9087 If not, it must exit and return nil. If yes, it should return
9088 a non-nil value after calling `org-store-link-props' with a list
9089 of properties and values. Special properties are:
9091 :type The link prefix, like \"http\". This must be given.
9092 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9093 This is obligatory as well.
9094 :description Optional default description for the second pair
9095 of brackets in an Org mode link. The user can still change
9096 this when inserting this link into an Org mode buffer.
9098 In addition to these, any additional properties can be specified
9099 and then used in capture templates."
9100 (cl-loop for link in org-link-parameters
9101 with store-func
9102 do (setq store-func (org-link-get-parameter (car link) :store))
9103 if store-func
9104 collect store-func))
9106 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9107 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9109 ;;;###autoload
9110 (defun org-store-link (arg &optional interactive?)
9111 "Store an org-link to the current location.
9112 \\<org-mode-map>
9113 This link is added to `org-stored-links' and can later be inserted
9114 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9116 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9117 A single
9118 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9119 `org-gnus-prefer-web-links' for links to Usenet articles.
9121 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9122 skipping storing functions that are not
9123 part of Org core.
9125 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9126 prefix ARG forces storing a link for each line in the
9127 active region.
9129 Assume the function is called interactively if INTERACTIVE? is
9130 non-nil."
9131 (interactive "P\np")
9132 (org-load-modules-maybe)
9133 (if (and (equal arg '(64)) (org-region-active-p))
9134 (save-excursion
9135 (let ((end (region-end)))
9136 (goto-char (region-beginning))
9137 (set-mark (point))
9138 (while (< (point-at-eol) end)
9139 (move-end-of-line 1) (activate-mark)
9140 (let (current-prefix-arg)
9141 (call-interactively 'org-store-link))
9142 (move-beginning-of-line 2)
9143 (set-mark (point)))))
9144 (setq org-store-link-plist nil)
9145 (let (link cpltxt desc description search txt custom-id agenda-link)
9146 (cond
9147 ;; Store a link using an external link type, if any function is
9148 ;; available. If more than one can generate a link from current
9149 ;; location, ask which one to use.
9150 ((and (not (equal arg '(16)))
9151 (let ((results-alist nil))
9152 (dolist (f (org-store-link-functions))
9153 (when (funcall f)
9154 ;; XXX: return value is not link's plist, so we
9155 ;; store the new value before it is modified. It
9156 ;; would be cleaner to ask store link functions to
9157 ;; return the plist instead.
9158 (push (cons f (copy-sequence org-store-link-plist))
9159 results-alist)))
9160 (pcase results-alist
9161 (`nil nil)
9162 (`((,_ . ,_)) t) ;single choice: nothing to do
9163 (`((,name . ,_) . ,_)
9164 ;; Reinstate link plist associated to the chosen
9165 ;; function.
9166 (apply #'org-store-link-props
9167 (cdr (assoc-string
9168 (completing-read
9169 "Which function for creating the link? "
9170 (mapcar #'car results-alist)
9171 nil t (symbol-name name))
9172 results-alist)))
9173 t))))
9174 (setq link (plist-get org-store-link-plist :link))
9175 (setq desc (or (plist-get org-store-link-plist :description)
9176 link)))
9178 ;; Store a link from a source code buffer.
9179 ((org-src-edit-buffer-p)
9180 (let ((coderef-format (org-src-coderef-format)))
9181 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9182 (setq link (format "(%s)" (match-string-no-properties 3))))
9183 (interactive?
9184 (let ((label (read-string "Code line label: ")))
9185 (end-of-line)
9186 (setq link (format coderef-format label))
9187 (let ((gc (- 79 (length link))))
9188 (if (< (current-column) gc)
9189 (org-move-to-column gc t)
9190 (insert " ")))
9191 (insert link)
9192 (setq link (concat "(" label ")"))
9193 (setq desc nil)))
9194 (t (setq link nil)))))
9196 ;; We are in the agenda, link to referenced location
9197 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9198 (let ((m (or (get-text-property (point) 'org-hd-marker)
9199 (get-text-property (point) 'org-marker))))
9200 (when m
9201 (org-with-point-at m
9202 (setq agenda-link (org-store-link nil interactive?))))))
9204 ((eq major-mode 'calendar-mode)
9205 (let ((cd (calendar-cursor-to-date)))
9206 (setq link
9207 (format-time-string
9208 (car org-time-stamp-formats)
9209 (apply 'encode-time
9210 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9211 nil nil nil))))
9212 (org-store-link-props :type "calendar" :date cd)))
9214 ((eq major-mode 'help-mode)
9215 (setq link (concat "help:" (save-excursion
9216 (goto-char (point-min))
9217 (looking-at "^[^ ]+")
9218 (match-string 0))))
9219 (org-store-link-props :type "help"))
9221 ((eq major-mode 'w3-mode)
9222 (setq cpltxt (if (and (buffer-name)
9223 (not (string-match "Untitled" (buffer-name))))
9224 (buffer-name)
9225 (url-view-url t))
9226 link (url-view-url t))
9227 (org-store-link-props :type "w3" :url (url-view-url t)))
9229 ((eq major-mode 'image-mode)
9230 (setq cpltxt (concat "file:"
9231 (abbreviate-file-name buffer-file-name))
9232 link cpltxt)
9233 (org-store-link-props :type "image" :file buffer-file-name))
9235 ;; In dired, store a link to the file of the current line
9236 ((derived-mode-p 'dired-mode)
9237 (let ((file (dired-get-filename nil t)))
9238 (setq file (if file
9239 (abbreviate-file-name
9240 (expand-file-name (dired-get-filename nil t)))
9241 ;; otherwise, no file so use current directory.
9242 default-directory))
9243 (setq cpltxt (concat "file:" file)
9244 link cpltxt)))
9246 ((setq search (run-hook-with-args-until-success
9247 'org-create-file-search-functions))
9248 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9249 "::" search))
9250 (setq cpltxt (or description link)))
9252 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9253 (org-with-limited-levels
9254 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9255 (cond
9256 ;; Store a link using the target at point
9257 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9258 (setq cpltxt
9259 (concat "file:"
9260 (abbreviate-file-name
9261 (buffer-file-name (buffer-base-buffer)))
9262 "::" (match-string 1))
9263 link cpltxt))
9264 ((and (featurep 'org-id)
9265 (or (eq org-id-link-to-org-use-id t)
9266 (and interactive?
9267 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9268 (and (eq org-id-link-to-org-use-id
9269 'create-if-interactive-and-no-custom-id)
9270 (not custom-id))))
9271 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9272 ;; Store a link using the ID at point
9273 (setq link (condition-case nil
9274 (prog1 (org-id-store-link)
9275 (setq desc (or (plist-get org-store-link-plist
9276 :description)
9277 "")))
9278 (error
9279 ;; Probably before first headline, link only to file
9280 (concat "file:"
9281 (abbreviate-file-name
9282 (buffer-file-name (buffer-base-buffer))))))))
9284 ;; Just link to current headline
9285 (setq cpltxt (concat "file:"
9286 (abbreviate-file-name
9287 (buffer-file-name (buffer-base-buffer)))))
9288 ;; Add a context search string
9289 (when (org-xor org-context-in-file-links
9290 (equal arg '(4)))
9291 (let* ((element (org-element-at-point))
9292 (name (org-element-property :name element)))
9293 (setq txt (cond
9294 ((org-at-heading-p) nil)
9295 (name)
9296 ((org-region-active-p)
9297 (buffer-substring (region-beginning) (region-end)))))
9298 (when (or (null txt) (string-match "\\S-" txt))
9299 (setq cpltxt
9300 (concat cpltxt "::"
9301 (condition-case nil
9302 (org-make-org-heading-search-string txt)
9303 (error "")))
9304 desc (or name
9305 (nth 4 (ignore-errors (org-heading-components)))
9306 "NONE")))))
9307 (when (string-match "::\\'" cpltxt)
9308 (setq cpltxt (substring cpltxt 0 -2)))
9309 (setq link cpltxt)))))
9311 ((buffer-file-name (buffer-base-buffer))
9312 ;; Just link to this file here.
9313 (setq cpltxt (concat "file:"
9314 (abbreviate-file-name
9315 (buffer-file-name (buffer-base-buffer)))))
9316 ;; Add a context string.
9317 (when (org-xor org-context-in-file-links
9318 (equal arg '(4)))
9319 (setq txt (if (org-region-active-p)
9320 (buffer-substring (region-beginning) (region-end))
9321 (buffer-substring (point-at-bol) (point-at-eol))))
9322 ;; Only use search option if there is some text.
9323 (when (string-match "\\S-" txt)
9324 (setq cpltxt
9325 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9326 desc "NONE")))
9327 (setq link cpltxt))
9329 (interactive?
9330 (user-error "No method for storing a link from this buffer"))
9332 (t (setq link nil)))
9334 ;; We're done setting link and desc, clean up
9335 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9336 (setq link (or link cpltxt)
9337 desc (or desc cpltxt))
9338 (cond ((not desc))
9339 ((equal desc "NONE") (setq desc nil))
9340 (t (setq desc
9341 (replace-regexp-in-string
9342 org-bracket-link-analytic-regexp
9343 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9344 desc))))
9345 ;; Return the link
9346 (if (not (and interactive? link))
9347 (or agenda-link (and link (org-make-link-string link desc)))
9348 (push (list link desc) org-stored-links)
9349 (message "Stored: %s" (or desc link))
9350 (when custom-id
9351 (setq link (concat "file:" (abbreviate-file-name
9352 (buffer-file-name)) "::#" custom-id))
9353 (push (list link desc) org-stored-links))
9354 (car org-stored-links)))))
9356 (defun org-store-link-props (&rest plist)
9357 "Store link properties.
9358 The properties are pre-processed by extracting names, addresses
9359 and dates."
9360 (let ((x (plist-get plist :from)))
9361 (when x
9362 (let ((adr (mail-extract-address-components x)))
9363 (setq plist (plist-put plist :fromname (car adr)))
9364 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9365 (let ((x (plist-get plist :to)))
9366 (when x
9367 (let ((adr (mail-extract-address-components x)))
9368 (setq plist (plist-put plist :toname (car adr)))
9369 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9370 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9371 (when x
9372 (setq plist (plist-put plist :date-timestamp
9373 (format-time-string
9374 (org-time-stamp-format t) x)))
9375 (setq plist (plist-put plist :date-timestamp-inactive
9376 (format-time-string
9377 (org-time-stamp-format t t) x)))))
9378 (let ((from (plist-get plist :from))
9379 (to (plist-get plist :to)))
9380 (when (and from to org-from-is-user-regexp)
9381 (setq plist
9382 (plist-put plist :fromto
9383 (if (string-match org-from-is-user-regexp from)
9384 (concat "to %t")
9385 (concat "from %f"))))))
9386 (setq org-store-link-plist plist))
9388 (defun org-add-link-props (&rest plist)
9389 "Add these properties to the link property list."
9390 (let (key value)
9391 (while plist
9392 (setq key (pop plist) value (pop plist))
9393 (setq org-store-link-plist
9394 (plist-put org-store-link-plist key value)))))
9396 (defun org-email-link-description (&optional fmt)
9397 "Return the description part of an email link.
9398 This takes information from `org-store-link-plist' and formats it
9399 according to FMT (default from `org-email-link-description-format')."
9400 (setq fmt (or fmt org-email-link-description-format))
9401 (let* ((p org-store-link-plist)
9402 (to (plist-get p :toaddress))
9403 (from (plist-get p :fromaddress))
9404 (table
9405 (list
9406 (cons "%c" (plist-get p :fromto))
9407 (cons "%F" (plist-get p :from))
9408 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9409 (cons "%T" (plist-get p :to))
9410 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9411 (cons "%s" (plist-get p :subject))
9412 (cons "%d" (plist-get p :date))
9413 (cons "%m" (plist-get p :message-id)))))
9414 (when (string-match "%c" fmt)
9415 ;; Check if the user wrote this message
9416 (if (and org-from-is-user-regexp from to
9417 (save-match-data (string-match org-from-is-user-regexp from)))
9418 (setq fmt (replace-match "to %t" t t fmt))
9419 (setq fmt (replace-match "from %f" t t fmt))))
9420 (org-replace-escapes fmt table)))
9422 (defun org-make-org-heading-search-string (&optional string)
9423 "Make search string for the current headline or STRING."
9424 (let ((s (or string
9425 (and (derived-mode-p 'org-mode)
9426 (save-excursion
9427 (org-back-to-heading t)
9428 (org-element-property :raw-value (org-element-at-point))))))
9429 (lines org-context-in-file-links))
9430 (unless string (setq s (concat "*" s))) ;Add * for headlines
9431 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9432 (when (and string (integerp lines) (> lines 0))
9433 (let ((slines (org-split-string s "\n")))
9434 (when (< lines (length slines))
9435 (setq s (mapconcat
9436 'identity
9437 (reverse (nthcdr (- (length slines) lines)
9438 (reverse slines))) "\n")))))
9439 (mapconcat #'identity (split-string s) " ")))
9441 (defconst org-link-escape-chars
9442 ;;%20 %5B %5D %25
9443 '(?\s ?\[ ?\] ?%)
9444 "List of characters that should be escaped in a link when stored to Org.
9445 This is the list that is used for internal purposes.")
9447 (defun org-make-link-string (link &optional description)
9448 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9449 (unless (org-string-nw-p link) (error "Empty link"))
9450 (let ((uri (cond ((string-match org-link-types-re link)
9451 (concat (match-string 1 link)
9452 (org-link-escape (substring link (match-end 1)))))
9453 ((or (file-name-absolute-p link)
9454 (string-match-p "\\`\\.\\.?/" link))
9455 (org-link-escape link))
9456 ;; For readability, do not encode space characters
9457 ;; in fuzzy links.
9458 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9459 (description
9460 (and (org-string-nw-p description)
9461 ;; Remove brackets from description, as they are fatal.
9462 (replace-regexp-in-string
9463 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9464 (org-trim description)))))
9465 (format "[[%s]%s]"
9467 (if description (format "[%s]" description) ""))))
9469 (defun org-link-escape (text &optional table merge)
9470 "Return percent escaped representation of TEXT.
9471 TEXT is a string with the text to escape.
9472 Optional argument TABLE is a list with characters that should be
9473 escaped. When nil, `org-link-escape-chars' is used.
9474 If optional argument MERGE is set, merge TABLE into
9475 `org-link-escape-chars'."
9476 (let ((characters-to-encode
9477 (cond ((null table) org-link-escape-chars)
9478 (merge (append org-link-escape-chars table))
9479 (t table))))
9480 (mapconcat
9481 (lambda (c)
9482 (if (or (memq c characters-to-encode)
9483 (and org-url-hexify-p (or (< c 32) (> c 126))))
9484 (mapconcat (lambda (e) (format "%%%.2X" e))
9485 (or (encode-coding-char c 'utf-8)
9486 (error "Unable to percent escape character: %c" c))
9488 (char-to-string c)))
9489 text "")))
9491 (defun org-link-unescape (str)
9492 "Unhex hexified Unicode parts in string STR.
9493 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9494 reciprocal of `org-link-escape', which see."
9495 (if (org-string-nw-p str)
9496 (replace-regexp-in-string
9497 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9498 str))
9500 (defun org-link-unescape-compound (hex)
9501 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9502 Note: this function also decodes single byte encodings like
9503 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9504 (save-match-data
9505 (let* ((bytes (cdr (split-string hex "%")))
9506 (ret "")
9507 (eat 0)
9508 (sum 0))
9509 (while bytes
9510 (let* ((val (string-to-number (pop bytes) 16))
9511 (shift-xor
9512 (if (= 0 eat)
9513 (cond
9514 ((>= val 252) (cons 6 252))
9515 ((>= val 248) (cons 5 248))
9516 ((>= val 240) (cons 4 240))
9517 ((>= val 224) (cons 3 224))
9518 ((>= val 192) (cons 2 192))
9519 (t (cons 0 0)))
9520 (cons 6 128))))
9521 (when (>= val 192) (setq eat (car shift-xor)))
9522 (setq val (logxor val (cdr shift-xor)))
9523 (setq sum (+ (lsh sum (car shift-xor)) val))
9524 (when (> eat 0) (setq eat (- eat 1)))
9525 (cond
9526 ((= 0 eat) ;multi byte
9527 (setq ret (concat ret (char-to-string sum)))
9528 (setq sum 0))
9529 ((not bytes) ; single byte(s)
9530 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9531 ret)))
9533 (defun org-link-unescape-single-byte-sequence (hex)
9534 "Unhexify hex-encoded single byte character sequences."
9535 (mapconcat (lambda (byte)
9536 (char-to-string (string-to-number byte 16)))
9537 (cdr (split-string hex "%")) ""))
9539 (defun org-fixup-message-id-for-http (s)
9540 "Replace special characters in a message id, so it can be used in an http query."
9541 (when (string-match "%" s)
9542 (setq s (mapconcat (lambda (c)
9543 (if (eq c ?%)
9544 "%25"
9545 (char-to-string c)))
9546 s "")))
9547 (while (string-match "<" s)
9548 (setq s (replace-match "%3C" t t s)))
9549 (while (string-match ">" s)
9550 (setq s (replace-match "%3E" t t s)))
9551 (while (string-match "@" s)
9552 (setq s (replace-match "%40" t t s)))
9555 (defun org-link-prettify (link)
9556 "Return a human-readable representation of LINK.
9557 The car of LINK must be a raw link.
9558 The cdr of LINK must be either a link description or nil."
9559 (let ((desc (or (cadr link) "<no description>")))
9560 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9561 "<" (car link) ">")))
9563 ;;;###autoload
9564 (defun org-insert-link-global ()
9565 "Insert a link like Org mode does.
9566 This command can be called in any mode to insert a link in Org syntax."
9567 (interactive)
9568 (org-load-modules-maybe)
9569 (org-run-like-in-org-mode 'org-insert-link))
9571 (defun org-insert-all-links (arg &optional pre post)
9572 "Insert all links in `org-stored-links'.
9573 When a universal prefix, do not delete the links from `org-stored-links'.
9574 When `ARG' is a number, insert the last N link(s).
9575 `PRE' and `POST' are optional arguments to define a string to
9576 prepend or to append."
9577 (interactive "P")
9578 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9579 (links (copy-sequence org-stored-links))
9580 (pr (or pre "- "))
9581 (po (or post "\n"))
9582 (cnt 1) l)
9583 (if (null org-stored-links)
9584 (message "No link to insert")
9585 (while (and (or (listp arg) (>= arg cnt))
9586 (setq l (if (listp arg)
9587 (pop links)
9588 (pop org-stored-links))))
9589 (setq cnt (1+ cnt))
9590 (insert pr)
9591 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9592 (insert po)))))
9594 (defun org-insert-last-stored-link (arg)
9595 "Insert the last link stored in `org-stored-links'."
9596 (interactive "p")
9597 (org-insert-all-links arg "" "\n"))
9599 (defun org-link-fontify-links-to-this-file ()
9600 "Fontify links to the current file in `org-stored-links'."
9601 (let ((f (buffer-file-name)) a b)
9602 (setq a (mapcar (lambda(l)
9603 (let ((ll (car l)))
9604 (when (and (string-match "^file:\\(.+\\)::" ll)
9605 (equal f (expand-file-name (match-string 1 ll))))
9606 ll)))
9607 org-stored-links))
9608 (when (featurep 'org-id)
9609 (setq b (mapcar (lambda(l)
9610 (let ((ll (car l)))
9611 (when (and (string-match "^id:\\(.+\\)$" ll)
9612 (equal f (expand-file-name
9613 (or (org-id-find-id-file
9614 (match-string 1 ll)) ""))))
9615 ll)))
9616 org-stored-links)))
9617 (mapcar (lambda(l)
9618 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9619 (delq nil (append a b)))))
9621 (defvar org--links-history nil)
9622 (defun org-insert-link (&optional complete-file link-location default-description)
9623 "Insert a link. At the prompt, enter the link.
9625 Completion can be used to insert any of the link protocol prefixes in use.
9627 The history can be used to select a link previously stored with
9628 `org-store-link'. When the empty string is entered (i.e. if you just
9629 press `RET' at the prompt), the link defaults to the most recently
9630 stored link. As `SPC' triggers completion in the minibuffer, you need to
9631 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9633 You will also be prompted for a description, and if one is given, it will
9634 be displayed in the buffer instead of the link.
9636 If there is already a link at point, this command will allow you to edit
9637 link and description parts.
9639 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9640 file name can be
9641 selected using completion. The path to the file will be relative to the
9642 current directory if the file is in the current directory or a subdirectory.
9643 Otherwise, the link will be the absolute path as completed in the minibuffer
9644 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9645 option `org-link-file-path-type'.
9647 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9648 absolute path even if the file is in
9649 the current directory or below.
9651 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9652 prefix negates `org-keep-stored-link-after-insertion'.
9654 If the LINK-LOCATION parameter is non-nil, this value will be used as
9655 the link location instead of reading one interactively.
9657 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9658 be used as the default description. Otherwise, if
9659 `org-make-link-description-function' is non-nil, this function
9660 will be called with the link target, and the result will be the
9661 default link description. When called non-interactivily, don't
9662 allow to edit the default description."
9663 (interactive "P")
9664 (let* ((wcf (current-window-configuration))
9665 (origbuf (current-buffer))
9666 (region (when (org-region-active-p)
9667 (buffer-substring (region-beginning) (region-end))))
9668 (remove (and region (list (region-beginning) (region-end))))
9669 (desc region)
9670 (link link-location)
9671 (abbrevs org-link-abbrev-alist-local)
9672 entry all-prefixes auto-desc)
9673 (cond
9674 (link-location) ; specified by arg, just use it.
9675 ((org-in-regexp org-bracket-link-regexp 1)
9676 ;; We do have a link at point, and we are going to edit it.
9677 (setq remove (list (match-beginning 0) (match-end 0)))
9678 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9679 (setq link (read-string "Link: "
9680 (org-link-unescape
9681 (match-string-no-properties 1)))))
9682 ((or (org-in-regexp org-angle-link-re)
9683 (org-in-regexp org-plain-link-re))
9684 ;; Convert to bracket link
9685 (setq remove (list (match-beginning 0) (match-end 0))
9686 link (read-string "Link: "
9687 (org-unbracket-string "<" ">" (match-string 0)))))
9688 ((member complete-file '((4) (16)))
9689 ;; Completing read for file names.
9690 (setq link (org-file-complete-link complete-file)))
9692 ;; Read link, with completion for stored links.
9693 (org-link-fontify-links-to-this-file)
9694 (org-switch-to-buffer-other-window "*Org Links*")
9695 (with-current-buffer "*Org Links*"
9696 (erase-buffer)
9697 (insert "Insert a link.
9698 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9699 (when org-stored-links
9700 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9701 (insert (mapconcat 'org-link-prettify
9702 (reverse org-stored-links) "\n")))
9703 (goto-char (point-min)))
9704 (let ((cw (selected-window)))
9705 (select-window (get-buffer-window "*Org Links*" 'visible))
9706 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9707 (unless (pos-visible-in-window-p (point-max))
9708 (org-fit-window-to-buffer))
9709 (and (window-live-p cw) (select-window cw)))
9710 (setq all-prefixes (append (mapcar 'car abbrevs)
9711 (mapcar 'car org-link-abbrev-alist)
9712 (org-link-types)))
9713 (unwind-protect
9714 ;; Fake a link history, containing the stored links.
9715 (let ((org--links-history
9716 (append (mapcar #'car org-stored-links)
9717 org-insert-link-history)))
9718 (setq link
9719 (org-completing-read
9720 "Link: "
9721 (append
9722 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9723 (mapcar #'car org-stored-links))
9724 nil nil nil
9725 'org--links-history
9726 (caar org-stored-links)))
9727 (unless (org-string-nw-p link) (user-error "No link selected"))
9728 (dolist (l org-stored-links)
9729 (when (equal link (cadr l))
9730 (setq link (car l))
9731 (setq auto-desc t)))
9732 (when (or (member link all-prefixes)
9733 (and (equal ":" (substring link -1))
9734 (member (substring link 0 -1) all-prefixes)
9735 (setq link (substring link 0 -1))))
9736 (setq link (with-current-buffer origbuf
9737 (org-link-try-special-completion link)))))
9738 (set-window-configuration wcf)
9739 (kill-buffer "*Org Links*"))
9740 (setq entry (assoc link org-stored-links))
9741 (or entry (push link org-insert-link-history))
9742 (setq desc (or desc (nth 1 entry)))))
9744 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9745 (not org-keep-stored-link-after-insertion))
9746 (setq org-stored-links (delq (assoc link org-stored-links)
9747 org-stored-links)))
9749 (when (and (string-match org-plain-link-re link)
9750 (not (string-match org-ts-regexp link)))
9751 ;; URL-like link, normalize the use of angular brackets.
9752 (setq link (org-unbracket-string "<" ">" link)))
9754 ;; Check if we are linking to the current file with a search
9755 ;; option If yes, simplify the link by using only the search
9756 ;; option.
9757 (when (and buffer-file-name
9758 (let ((case-fold-search nil))
9759 (string-match "\\`file:\\(.+?\\)::" link)))
9760 (let ((path (match-string-no-properties 1 link))
9761 (search (substring-no-properties link (match-end 0))))
9762 (save-match-data
9763 (when (equal (file-truename buffer-file-name) (file-truename path))
9764 ;; We are linking to this same file, with a search option
9765 (setq link search)))))
9767 ;; Check if we can/should use a relative path. If yes, simplify
9768 ;; the link.
9769 (let ((case-fold-search nil))
9770 (when (string-match "\\`\\(file\\|docview\\):" link)
9771 (let* ((type (match-string-no-properties 0 link))
9772 (path-start (match-end 0))
9773 (search (and (string-match "::\\(.*\\)\\'" link)
9774 (match-string 1 link)))
9775 (path
9776 (if search
9777 (substring-no-properties
9778 link path-start (match-beginning 0))
9779 (substring-no-properties link (match-end 0))))
9780 (origpath path))
9781 (cond
9782 ((or (eq org-link-file-path-type 'absolute)
9783 (equal complete-file '(16)))
9784 (setq path (abbreviate-file-name (expand-file-name path))))
9785 ((eq org-link-file-path-type 'noabbrev)
9786 (setq path (expand-file-name path)))
9787 ((eq org-link-file-path-type 'relative)
9788 (setq path (file-relative-name path)))
9790 (save-match-data
9791 (if (string-match (concat "^" (regexp-quote
9792 (expand-file-name
9793 (file-name-as-directory
9794 default-directory))))
9795 (expand-file-name path))
9796 ;; We are linking a file with relative path name.
9797 (setq path (substring (expand-file-name path)
9798 (match-end 0)))
9799 (setq path (abbreviate-file-name (expand-file-name path)))))))
9800 (setq link (concat type path (and search (concat "::" search))))
9801 (when (equal desc origpath)
9802 (setq desc path)))))
9804 (unless auto-desc
9805 (let ((initial-input
9806 (cond
9807 (default-description)
9808 ((not org-make-link-description-function) desc)
9809 (t (condition-case nil
9810 (funcall org-make-link-description-function link desc)
9811 (error
9812 (message "Can't get link description from `%s'"
9813 (symbol-name org-make-link-description-function))
9814 (sit-for 2)
9815 nil))))))
9816 (setq desc (if (called-interactively-p 'any)
9817 (read-string "Description: " initial-input)
9818 initial-input))))
9820 (unless (string-match "\\S-" desc) (setq desc nil))
9821 (when remove (apply 'delete-region remove))
9822 (insert (org-make-link-string link desc))
9823 ;; Redisplay so as the new link has proper invisible characters.
9824 (sit-for 0)))
9826 (defun org-link-try-special-completion (type)
9827 "If there is completion support for link type TYPE, offer it."
9828 (let ((fun (org-link-get-parameter type :complete)))
9829 (if (functionp fun)
9830 (funcall fun)
9831 (read-string "Link (no completion support): " (concat type ":")))))
9833 (defun org-file-complete-link (&optional arg)
9834 "Create a file link using completion."
9835 (let ((file (read-file-name "File: "))
9836 (pwd (file-name-as-directory (expand-file-name ".")))
9837 (pwd1 (file-name-as-directory (abbreviate-file-name
9838 (expand-file-name ".")))))
9839 (cond ((equal arg '(16))
9840 (concat "file:"
9841 (abbreviate-file-name (expand-file-name file))))
9842 ((string-match
9843 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9844 (concat "file:" (match-string 1 file)))
9845 ((string-match
9846 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9847 (expand-file-name file))
9848 (concat "file:"
9849 (match-string 1 (expand-file-name file))))
9850 (t (concat "file:" file)))))
9853 ;;; Opening/following a link
9855 (defvar org-link-search-failed nil)
9857 (defvar org-open-link-functions nil
9858 "Hook for functions finding a plain text link.
9859 These functions must take a single argument, the link content.
9860 They will be called for links that look like [[link text][description]]
9861 when LINK TEXT does not have a protocol like \"http:\" and does not look
9862 like a filename (e.g. \"./blue.png\").
9864 These functions will be called *before* Org attempts to resolve the
9865 link by doing text searches in the current buffer - so if you want a
9866 link \"[[target]]\" to still find \"<<target>>\", your function should
9867 handle this as a special case.
9869 When the function does handle the link, it must return a non-nil value.
9870 If it decides that it is not responsible for this link, it must return
9871 nil to indicate that that Org can continue with other options like
9872 exact and fuzzy text search.")
9874 (defun org-next-link (&optional search-backward)
9875 "Move forward to the next link.
9876 If the link is in hidden text, expose it."
9877 (interactive "P")
9878 (when (and org-link-search-failed (eq this-command last-command))
9879 (goto-char (point-min))
9880 (message "Link search wrapped back to beginning of buffer"))
9881 (setq org-link-search-failed nil)
9882 (let* ((pos (point))
9883 (ct (org-context))
9884 (a (assq :link ct))
9885 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9886 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9887 ((looking-at org-any-link-re)
9888 ;; Don't stay stuck at link without an org-link face
9889 (forward-char (if search-backward -1 1))))
9890 (if (funcall srch-fun org-any-link-re nil t)
9891 (progn
9892 (goto-char (match-beginning 0))
9893 (when (org-invisible-p) (org-show-context)))
9894 (goto-char pos)
9895 (setq org-link-search-failed t)
9896 (message "No further link found"))))
9898 (defun org-previous-link ()
9899 "Move backward to the previous link.
9900 If the link is in hidden text, expose it."
9901 (interactive)
9902 (funcall 'org-next-link t))
9904 (defun org-translate-link (s)
9905 "Translate a link string if a translation function has been defined."
9906 (with-temp-buffer
9907 (insert (org-trim s))
9908 (org-trim (org-element-interpret-data (org-element-context)))))
9910 (defun org-translate-link-from-planner (type path)
9911 "Translate a link from Emacs Planner syntax so that Org can follow it.
9912 This is still an experimental function, your mileage may vary."
9913 (cond
9914 ((member type '("http" "https" "news" "ftp"))
9915 ;; standard Internet links are the same.
9916 nil)
9917 ((and (equal type "irc") (string-match "^//" path))
9918 ;; Planner has two / at the beginning of an irc link, we have 1.
9919 ;; We should have zero, actually....
9920 (setq path (substring path 1)))
9921 ((and (equal type "lisp") (string-match "^/" path))
9922 ;; Planner has a slash, we do not.
9923 (setq type "elisp" path (substring path 1)))
9924 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9925 ;; A typical message link. Planner has the id after the final slash,
9926 ;; we separate it with a hash mark
9927 (setq path (concat (match-string 1 path) "#"
9928 (org-unbracket-string "<" ">" (match-string 2 path))))))
9929 (cons type path))
9931 (defun org-find-file-at-mouse (ev)
9932 "Open file link or URL at mouse."
9933 (interactive "e")
9934 (mouse-set-point ev)
9935 (org-open-at-point 'in-emacs))
9937 (defun org-open-at-mouse (ev)
9938 "Open file link or URL at mouse.
9939 See the docstring of `org-open-file' for details."
9940 (interactive "e")
9941 (mouse-set-point ev)
9942 (when (eq major-mode 'org-agenda-mode)
9943 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9944 (org-open-at-point))
9946 (defvar org-window-config-before-follow-link nil
9947 "The window configuration before following a link.
9948 This is saved in case the need arises to restore it.")
9950 ;;;###autoload
9951 (defun org-open-at-point-global ()
9952 "Follow a link or time-stamp like Org mode does.
9953 This command can be called in any mode to follow an external link
9954 or a time-stamp that has Org mode syntax. Its behavior is
9955 undefined when called on internal links (e.g., fuzzy links).
9956 Raise an error when there is nothing to follow. "
9957 (interactive)
9958 (cond ((org-in-regexp org-any-link-re)
9959 (org-open-link-from-string (match-string-no-properties 0)))
9960 ((or (org-in-regexp org-ts-regexp-both nil t)
9961 (org-in-regexp org-tsr-regexp-both nil t))
9962 (org-follow-timestamp-link))
9963 (t (user-error "No link found"))))
9965 ;;;###autoload
9966 (defun org-open-link-from-string (s &optional arg reference-buffer)
9967 "Open a link in the string S, as if it was in Org mode."
9968 (interactive "sLink: \nP")
9969 (let ((reference-buffer (or reference-buffer (current-buffer))))
9970 (with-temp-buffer
9971 (let ((org-inhibit-startup (not reference-buffer)))
9972 (org-mode)
9973 (insert s)
9974 (goto-char (point-min))
9975 (when reference-buffer
9976 (setq org-link-abbrev-alist-local
9977 (with-current-buffer reference-buffer
9978 org-link-abbrev-alist-local)))
9979 (org-open-at-point arg reference-buffer)))))
9981 (defvar org-open-at-point-functions nil
9982 "Hook that is run when following a link at point.
9984 Functions in this hook must return t if they identify and follow
9985 a link at point. If they don't find anything interesting at point,
9986 they must return nil.")
9988 (defvar org-link-search-inhibit-query nil)
9989 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9990 (defun org--open-doi-link (path)
9991 "Open a \"doi\" type link.
9992 PATH is a the path to search for, as a string."
9993 (browse-url (url-encode-url (concat org-doi-server-url path))))
9995 (defun org--open-elisp-link (path)
9996 "Open a \"elisp\" type link.
9997 PATH is the sexp to evaluate, as a string."
9998 (let ((cmd path))
9999 (if (or (and (org-string-nw-p
10000 org-confirm-elisp-link-not-regexp)
10001 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10002 (not org-confirm-elisp-link-function)
10003 (funcall org-confirm-elisp-link-function
10004 (format "Execute \"%s\" as elisp? "
10005 (org-add-props cmd nil 'face 'org-warning))))
10006 (message "%s => %s" cmd
10007 (if (eq (string-to-char cmd) ?\()
10008 (eval (read cmd))
10009 (call-interactively (read cmd))))
10010 (user-error "Abort"))))
10012 (defun org--open-help-link (path)
10013 "Open a \"help\" type link.
10014 PATH is a symbol name, as a string."
10015 (pcase (intern path)
10016 ((and (pred fboundp) variable) (describe-function variable))
10017 ((and (pred boundp) function) (describe-variable function))
10018 (name (user-error "Unknown function or variable: %s" name))))
10020 (defun org--open-shell-link (path)
10021 "Open a \"shell\" type link.
10022 PATH is the command to execute, as a string."
10023 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10024 (cmd path))
10025 (if (or (and (org-string-nw-p
10026 org-confirm-shell-link-not-regexp)
10027 (string-match
10028 org-confirm-shell-link-not-regexp cmd))
10029 (not org-confirm-shell-link-function)
10030 (funcall org-confirm-shell-link-function
10031 (format "Execute \"%s\" in shell? "
10032 (org-add-props cmd nil
10033 'face 'org-warning))))
10034 (progn
10035 (message "Executing %s" cmd)
10036 (shell-command cmd buf)
10037 (when (featurep 'midnight)
10038 (setq clean-buffer-list-kill-buffer-names
10039 (cons (buffer-name buf)
10040 clean-buffer-list-kill-buffer-names))))
10041 (user-error "Abort"))))
10043 (defun org-open-at-point (&optional arg reference-buffer)
10044 "Open link, timestamp, footnote or tags at point.
10046 When point is on a link, follow it. Normally, files will be
10047 opened by an appropriate application. If the optional prefix
10048 argument ARG is non-nil, Emacs will visit the file. With
10049 a double prefix argument, try to open outside of Emacs, in the
10050 application the system uses for this file type.
10052 When point is on a timestamp, open the agenda at the day
10053 specified.
10055 When point is a footnote definition, move to the first reference
10056 found. If it is on a reference, move to the associated
10057 definition.
10059 When point is on a headline, display a list of every link in the
10060 entry, so it is possible to pick one, or all, of them. If point
10061 is on a tag, call `org-tags-view' instead.
10063 When optional argument REFERENCE-BUFFER is non-nil, it should
10064 specify a buffer from where the link search should happen. This
10065 is used internally by `org-open-link-from-string'.
10067 On top of syntactically correct links, this function will also
10068 try to open links and time-stamps in comments, example
10069 blocks... i.e., whenever point is on something looking like
10070 a timestamp or a link."
10071 (interactive "P")
10072 ;; On a code block, open block's results.
10073 (unless (call-interactively 'org-babel-open-src-block-result)
10074 (org-load-modules-maybe)
10075 (setq org-window-config-before-follow-link (current-window-configuration))
10076 (org-remove-occur-highlights nil nil t)
10077 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10078 (let* ((context
10079 ;; Only consider supported types, even if they are not
10080 ;; the closest one.
10081 (org-element-lineage
10082 (org-element-context)
10083 '(clock footnote-definition footnote-reference headline
10084 inlinetask link timestamp)
10086 (type (org-element-type context))
10087 (value (org-element-property :value context)))
10088 (cond
10089 ;; On a headline or an inlinetask, but not on a timestamp,
10090 ;; a link, a footnote reference.
10091 ((memq type '(headline inlinetask))
10092 (org-match-line org-complex-heading-regexp)
10093 (if (and (match-beginning 5)
10094 (>= (point) (match-beginning 5))
10095 (< (point) (match-end 5)))
10096 ;; On tags.
10097 (org-tags-view arg (substring (match-string 5) 0 -1))
10098 ;; Not on tags.
10099 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10100 (`(nil . ,_)
10101 (require 'org-attach)
10102 (org-attach-reveal 'if-exists))
10103 (`(,links . ,links-end)
10104 (dolist (link (if (stringp links) (list links) links))
10105 (search-forward link nil links-end)
10106 (goto-char (match-beginning 0))
10107 (org-open-at-point))))))
10108 ;; On a footnote reference or at definition's label.
10109 ((or (eq type 'footnote-reference)
10110 (and (eq type 'footnote-definition)
10111 (save-excursion
10112 ;; Do not validate action when point is on the
10113 ;; spaces right after the footnote label, in
10114 ;; order to be on par with behaviour on links.
10115 (skip-chars-forward " \t")
10116 (let ((begin
10117 (org-element-property :contents-begin context)))
10118 (if begin (< (point) begin)
10119 (= (org-element-property :post-affiliated context)
10120 (line-beginning-position)))))))
10121 (org-footnote-action))
10122 ;; No valid context. Ignore catch-all types like `headline'.
10123 ;; If point is on something looking like a link or
10124 ;; a time-stamp, try opening it. It may be useful in
10125 ;; comments, example blocks...
10126 ((memq type '(footnote-definition headline inlinetask nil))
10127 (call-interactively #'org-open-at-point-global))
10128 ;; On a clock line, make sure point is on the timestamp
10129 ;; before opening it.
10130 ((and (eq type 'clock)
10131 value
10132 (>= (point) (org-element-property :begin value))
10133 (<= (point) (org-element-property :end value)))
10134 (org-follow-timestamp-link))
10135 ;; Do nothing on white spaces after an object.
10136 ((>= (point)
10137 (save-excursion
10138 (goto-char (org-element-property :end context))
10139 (skip-chars-backward " \t")
10140 (point)))
10141 (user-error "No link found"))
10142 ((eq type 'timestamp) (org-follow-timestamp-link))
10143 ((eq type 'link)
10144 (let ((type (org-element-property :type context))
10145 (path (org-link-unescape (org-element-property :path context))))
10146 ;; Switch back to REFERENCE-BUFFER needed when called in
10147 ;; a temporary buffer through `org-open-link-from-string'.
10148 (with-current-buffer (or reference-buffer (current-buffer))
10149 (cond
10150 ((equal type "file")
10151 (if (string-match "[*?{]" (file-name-nondirectory path))
10152 (dired path)
10153 ;; Look into `org-link-parameters' in order to find
10154 ;; a DEDICATED-FUNCTION to open file. The function
10155 ;; will be applied on raw link instead of parsed
10156 ;; link due to the limitation in `org-add-link-type'
10157 ;; ("open" function called with a single argument).
10158 ;; If no such function is found, fallback to
10159 ;; `org-open-file'.
10160 (let* ((option (org-element-property :search-option context))
10161 (app (org-element-property :application context))
10162 (dedicated-function
10163 (org-link-get-parameter
10164 (if app (concat type "+" app) type)
10165 :follow)))
10166 (if dedicated-function
10167 (funcall dedicated-function
10168 (concat path
10169 (and option (concat "::" option))))
10170 (apply #'org-open-file
10171 path
10172 (cond (arg)
10173 ((equal app "emacs") 'emacs)
10174 ((equal app "sys") 'system))
10175 (cond ((not option) nil)
10176 ((string-match-p "\\`[0-9]+\\'" option)
10177 (list (string-to-number option)))
10178 (t (list nil
10179 (org-link-unescape option)))))))))
10180 ((functionp (org-link-get-parameter type :follow))
10181 (funcall (org-link-get-parameter type :follow) path))
10182 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10183 (unless (run-hook-with-args-until-success
10184 'org-open-link-functions path)
10185 (if (not arg) (org-mark-ring-push)
10186 (switch-to-buffer-other-window
10187 (org-get-buffer-for-internal-link (current-buffer))))
10188 (let ((destination
10189 (org-with-wide-buffer
10190 (if (equal type "radio")
10191 (org-search-radio-target
10192 (org-element-property :path context))
10193 (org-link-search
10194 (if (member type '("custom-id" "coderef"))
10195 (org-element-property :raw-link context)
10196 path)
10197 ;; Prevent fuzzy links from matching
10198 ;; themselves.
10199 (and (equal type "fuzzy")
10200 (+ 2 (org-element-property :begin context)))))
10201 (point))))
10202 (unless (and (<= (point-min) destination)
10203 (>= (point-max) destination))
10204 (widen))
10205 (goto-char destination))))
10206 (t (browse-url-at-point))))))
10207 (t (user-error "No link found")))))
10208 (run-hook-with-args 'org-follow-link-hook)))
10210 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10211 "Offer links in the current entry and return the selected link.
10212 If there is only one link, return it.
10213 If NTH is an integer, return the NTH link found.
10214 If ZERO is a string, check also this string for a link, and if
10215 there is one, return it."
10216 (with-current-buffer buffer
10217 (org-with-wide-buffer
10218 (goto-char marker)
10219 (let ((cnt ?0)
10220 have-zero end links link c)
10221 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10222 (push (match-string 0 zero) links)
10223 (setq cnt (1- cnt) have-zero t))
10224 (save-excursion
10225 (org-back-to-heading t)
10226 (setq end (save-excursion (outline-next-heading) (point)))
10227 (while (re-search-forward org-any-link-re end t)
10228 (push (match-string 0) links))
10229 (setq links (org-uniquify (reverse links))))
10230 (cond
10231 ((null links)
10232 (message "No links"))
10233 ((equal (length links) 1)
10234 (setq link (car links)))
10235 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10236 (setq link (nth (if have-zero nth (1- nth)) links)))
10237 (t ; we have to select a link
10238 (save-excursion
10239 (save-window-excursion
10240 (delete-other-windows)
10241 (with-output-to-temp-buffer "*Select Link*"
10242 (dolist (l links)
10243 (cond
10244 ((not (string-match org-bracket-link-regexp l))
10245 (princ (format "[%c] %s\n" (cl-incf cnt)
10246 (org-unbracket-string "<" ">" l))))
10247 ((match-end 3)
10248 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10249 (match-string 3 l) (match-string 1 l))))
10250 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10251 (match-string 1 l)))))))
10252 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10253 (message "Select link to open, RET to open all:")
10254 (setq c (read-char-exclusive))
10255 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10256 (when (equal c ?q) (user-error "Abort"))
10257 (if (equal c ?\C-m)
10258 (setq link links)
10259 (setq nth (- c ?0))
10260 (when have-zero (setq nth (1+ nth)))
10261 (unless (and (integerp nth) (>= (length links) nth))
10262 (user-error "Invalid link selection"))
10263 (setq link (nth (1- nth) links)))))
10264 (cons link end)))))
10266 ;; TODO: These functions are deprecated since `org-open-at-point'
10267 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10268 (defun org-open-file-with-system (path)
10269 "Open file at PATH using the system way of opening it."
10270 (org-open-file path 'system))
10271 (defun org-open-file-with-emacs (path)
10272 "Open file at PATH in Emacs."
10273 (org-open-file path 'emacs))
10276 ;;; File search
10278 (defvar org-create-file-search-functions nil
10279 "List of functions to construct the right search string for a file link.
10280 These functions are called in turn with point at the location to
10281 which the link should point.
10283 A function in the hook should first test if it would like to
10284 handle this file type, for example by checking the `major-mode'
10285 or the file extension. If it decides not to handle this file, it
10286 should just return nil to give other functions a chance. If it
10287 does handle the file, it must return the search string to be used
10288 when following the link. The search string will be part of the
10289 file link, given after a double colon, and `org-open-at-point'
10290 will automatically search for it. If special measures must be
10291 taken to make the search successful, another function should be
10292 added to the companion hook `org-execute-file-search-functions',
10293 which see.
10295 A function in this hook may also use `setq' to set the variable
10296 `description' to provide a suggestion for the descriptive text to
10297 be used for this link when it gets inserted into an Org buffer
10298 with \\[org-insert-link].")
10300 (defvar org-execute-file-search-functions nil
10301 "List of functions to execute a file search triggered by a link.
10303 Functions added to this hook must accept a single argument, the
10304 search string that was part of the file link, the part after the
10305 double colon. The function must first check if it would like to
10306 handle this search, for example by checking the `major-mode' or
10307 the file extension. If it decides not to handle this search, it
10308 should just return nil to give other functions a chance. If it
10309 does handle the search, it must return a non-nil value to keep
10310 other functions from trying.
10312 Each function can access the current prefix argument through the
10313 variable `current-prefix-arg'. Note that a single prefix is used
10314 to force opening a link in Emacs, so it may be good to only use a
10315 numeric or double prefix to guide the search function.
10317 In case this is needed, a function in this hook can also restore
10318 the window configuration before `org-open-at-point' was called using:
10320 (set-window-configuration org-window-config-before-follow-link)")
10322 (defun org-search-radio-target (target)
10323 "Search a radio target matching TARGET in current buffer.
10324 White spaces are not significant."
10325 (let ((re (format "<<<%s>>>"
10326 (mapconcat #'regexp-quote
10327 (split-string target)
10328 "[ \t]+\\(?:\n[ \t]*\\)?")))
10329 (origin (point)))
10330 (goto-char (point-min))
10331 (catch :radio-match
10332 (while (re-search-forward re nil t)
10333 (backward-char)
10334 (let ((object (org-element-context)))
10335 (when (eq (org-element-type object) 'radio-target)
10336 (goto-char (org-element-property :begin object))
10337 (org-show-context 'link-search)
10338 (throw :radio-match nil))))
10339 (goto-char origin)
10340 (user-error "No match for radio target: %s" target))))
10342 (defun org-link-search (s &optional avoid-pos stealth)
10343 "Search for a search string S.
10345 If S starts with \"#\", it triggers a custom ID search.
10347 If S is enclosed within parenthesis, it initiates a coderef
10348 search.
10350 If S is surrounded by forward slashes, it is interpreted as
10351 a regular expression. In Org mode files, this will create an
10352 `org-occur' sparse tree. In ordinary files, `occur' will be used
10353 to list matches. If the current buffer is in `dired-mode', grep
10354 will be used to search in all files.
10356 When AVOID-POS is given, ignore matches near that position.
10358 When optional argument STEALTH is non-nil, do not modify
10359 visibility around point, thus ignoring `org-show-context-detail'
10360 variable.
10362 Search is case-insensitive and ignores white spaces. Return type
10363 of matched result, which is either `dedicated' or `fuzzy'."
10364 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10365 (let* ((case-fold-search t)
10366 (origin (point))
10367 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10368 (starred (eq (string-to-char normalized) ?*))
10369 (words (split-string (if starred (substring s 1) s)))
10370 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10371 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10372 type)
10373 (cond
10374 ;; Check if there are any special search functions.
10375 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10376 ((eq (string-to-char s) ?#)
10377 ;; Look for a custom ID S if S starts with "#".
10378 (let* ((id (substring normalized 1))
10379 (match (org-find-property "CUSTOM_ID" id)))
10380 (if match (progn (goto-char match) (setf type 'dedicated))
10381 (error "No match for custom ID: %s" id))))
10382 ((string-match "\\`(\\(.*\\))\\'" normalized)
10383 ;; Look for coderef targets if S is enclosed within parenthesis.
10384 (let ((coderef (match-string-no-properties 1 normalized))
10385 (re (substring s-single-re 1 -1)))
10386 (goto-char (point-min))
10387 (catch :coderef-match
10388 (while (re-search-forward re nil t)
10389 (let ((element (org-element-at-point)))
10390 (when (and (memq (org-element-type element)
10391 '(example-block src-block))
10392 ;; Build proper regexp according to current
10393 ;; block's label format.
10394 (let ((label-fmt
10395 (regexp-quote
10396 (or (org-element-property :label-fmt element)
10397 org-coderef-label-format))))
10398 (save-excursion
10399 (beginning-of-line)
10400 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10401 (format label-fmt coderef))))))
10402 (setq type 'dedicated)
10403 (goto-char (match-beginning 1))
10404 (throw :coderef-match nil))))
10405 (goto-char origin)
10406 (error "No match for coderef: %s" coderef))))
10407 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10408 ;; Look for a regular expression.
10409 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10410 (match-string 1 s)))
10411 ;; From here, we handle fuzzy links.
10413 ;; Look for targets, only if not in a headline search.
10414 ((and (not starred)
10415 (let ((target (format "<<%s>>" s-multi-re)))
10416 (catch :target-match
10417 (goto-char (point-min))
10418 (while (re-search-forward target nil t)
10419 (backward-char)
10420 (let ((context (org-element-context)))
10421 (when (eq (org-element-type context) 'target)
10422 (setq type 'dedicated)
10423 (goto-char (org-element-property :begin context))
10424 (throw :target-match t))))
10425 nil))))
10426 ;; Look for elements named after S, only if not in a headline
10427 ;; search.
10428 ((and (not starred)
10429 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10430 (catch :name-match
10431 (goto-char (point-min))
10432 (while (re-search-forward name nil t)
10433 (let ((element (org-element-at-point)))
10434 (when (equal words
10435 (split-string
10436 (org-element-property :name element)))
10437 (setq type 'dedicated)
10438 (beginning-of-line)
10439 (throw :name-match t))))
10440 nil))))
10441 ;; Regular text search. Prefer headlines in Org mode buffers.
10442 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10443 ;; statistics cookies and tags.
10444 ((and (derived-mode-p 'org-mode)
10445 (let ((title-re
10446 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10447 org-outline-regexp-bol
10448 org-comment-string
10449 (mapconcat #'regexp-quote words ".+")))
10450 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10451 (comment-re (eval-when-compile
10452 (format "\\`%s[ \t]+" org-comment-string))))
10453 (goto-char (point-min))
10454 (catch :found
10455 (while (re-search-forward title-re nil t)
10456 (when (equal words
10457 (split-string
10458 (replace-regexp-in-string
10459 cookie-re ""
10460 (replace-regexp-in-string
10461 comment-re "" (org-get-heading t t t)))))
10462 (throw :found t)))
10463 nil)))
10464 (beginning-of-line)
10465 (setq type 'dedicated))
10466 ;; Offer to create non-existent headline depending on
10467 ;; `org-link-search-must-match-exact-headline'.
10468 ((and (derived-mode-p 'org-mode)
10469 (not org-link-search-inhibit-query)
10470 (eq org-link-search-must-match-exact-headline 'query-to-create)
10471 (yes-or-no-p "No match - create this as a new heading? "))
10472 (goto-char (point-max))
10473 (unless (bolp) (newline))
10474 (org-insert-heading nil t t)
10475 (insert s "\n")
10476 (beginning-of-line 0))
10477 ;; Only headlines are looked after. No need to process
10478 ;; further: throw an error.
10479 ((and (derived-mode-p 'org-mode)
10480 (or starred org-link-search-must-match-exact-headline))
10481 (goto-char origin)
10482 (error "No match for fuzzy expression: %s" normalized))
10483 ;; Regular text search.
10484 ((catch :fuzzy-match
10485 (goto-char (point-min))
10486 (while (re-search-forward s-multi-re nil t)
10487 ;; Skip match if it contains AVOID-POS or it is included in
10488 ;; a link with a description but outside the description.
10489 (unless (or (and avoid-pos
10490 (<= (match-beginning 0) avoid-pos)
10491 (> (match-end 0) avoid-pos))
10492 (and (save-match-data
10493 (org-in-regexp org-bracket-link-regexp))
10494 (match-beginning 3)
10495 (or (> (match-beginning 3) (point))
10496 (<= (match-end 3) (point)))
10497 (org-element-lineage
10498 (save-match-data (org-element-context))
10499 '(link) t)))
10500 (goto-char (match-beginning 0))
10501 (setq type 'fuzzy)
10502 (throw :fuzzy-match t)))
10503 nil))
10504 ;; All failed. Throw an error.
10505 (t (goto-char origin)
10506 (error "No match for fuzzy expression: %s" normalized)))
10507 ;; Disclose surroundings of match, if appropriate.
10508 (when (and (derived-mode-p 'org-mode) (not stealth))
10509 (org-show-context 'link-search))
10510 type))
10512 (defun org-get-buffer-for-internal-link (buffer)
10513 "Return a buffer to be used for displaying the link target of internal links."
10514 (cond
10515 ((not org-display-internal-link-with-indirect-buffer)
10516 buffer)
10517 ((string-suffix-p "(Clone)" (buffer-name buffer))
10518 (message "Buffer is already a clone, not making another one")
10519 ;; we also do not modify visibility in this case
10520 buffer)
10521 (t ; make a new indirect buffer for displaying the link
10522 (let* ((bn (buffer-name buffer))
10523 (ibn (concat bn "(Clone)"))
10524 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10525 (with-current-buffer ib (org-overview))
10526 ib))))
10528 (defun org-do-occur (regexp &optional cleanup)
10529 "Call the Emacs command `occur'.
10530 If CLEANUP is non-nil, remove the printout of the regular expression
10531 in the *Occur* buffer. This is useful if the regex is long and not useful
10532 to read."
10533 (occur regexp)
10534 (when cleanup
10535 (let ((cwin (selected-window)) win beg end)
10536 (when (setq win (get-buffer-window "*Occur*"))
10537 (select-window win))
10538 (goto-char (point-min))
10539 (when (re-search-forward "match[a-z]+" nil t)
10540 (setq beg (match-end 0))
10541 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10542 (setq end (1- (match-beginning 0)))))
10543 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10544 (goto-char (point-min))
10545 (select-window cwin))))
10547 ;;; The mark ring for links jumps
10549 (defvar org-mark-ring nil
10550 "Mark ring for positions before jumps in Org mode.")
10551 (defvar org-mark-ring-last-goto nil
10552 "Last position in the mark ring used to go back.")
10553 ;; Fill and close the ring
10554 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10555 (dotimes (_ org-mark-ring-length)
10556 (push (make-marker) org-mark-ring))
10557 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10558 org-mark-ring)
10560 (defun org-mark-ring-push (&optional pos buffer)
10561 "Put the current position or POS into the mark ring and rotate it."
10562 (interactive)
10563 (setq pos (or pos (point)))
10564 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10565 (move-marker (car org-mark-ring)
10566 (or pos (point))
10567 (or buffer (current-buffer)))
10568 (message "%s"
10569 (substitute-command-keys
10570 "Position saved to mark ring, go back with \
10571 `\\[org-mark-ring-goto]'.")))
10573 (defun org-mark-ring-goto (&optional n)
10574 "Jump to the previous position in the mark ring.
10575 With prefix arg N, jump back that many stored positions. When
10576 called several times in succession, walk through the entire ring.
10577 Org mode commands jumping to a different position in the current file,
10578 or to another Org file, automatically push the old position onto the ring."
10579 (interactive "p")
10580 (let (p m)
10581 (if (eq last-command this-command)
10582 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10583 (setq p org-mark-ring))
10584 (setq org-mark-ring-last-goto p)
10585 (setq m (car p))
10586 (pop-to-buffer-same-window (marker-buffer m))
10587 (goto-char m)
10588 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10590 (defun org-add-angle-brackets (s)
10591 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10592 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10595 ;;; Following specific links
10597 (defvar org-agenda-buffer-tmp-name)
10598 (defvar org-agenda-start-on-weekday)
10599 (defun org-follow-timestamp-link ()
10600 "Open an agenda view for the time-stamp date/range at point."
10601 (cond
10602 ((org-at-date-range-p t)
10603 (let ((org-agenda-start-on-weekday)
10604 (t1 (match-string 1))
10605 (t2 (match-string 2)) tt1 tt2)
10606 (setq tt1 (time-to-days (org-time-string-to-time t1))
10607 tt2 (time-to-days (org-time-string-to-time t2)))
10608 (let ((org-agenda-buffer-tmp-name
10609 (format "*Org Agenda(a:%s)"
10610 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10611 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10612 ((org-at-timestamp-p 'lax)
10613 (let ((org-agenda-buffer-tmp-name
10614 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10615 (org-agenda-list nil (time-to-days (org-time-string-to-time
10616 (substring (match-string 1) 0 10)))
10617 1)))
10618 (t (error "This should not happen"))))
10621 ;;; Following file links
10622 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10623 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10624 (declare-function mailcap-mime-info
10625 "mailcap" (string &optional request no-decode))
10626 (defvar org-wait nil)
10627 (defun org-open-file (path &optional in-emacs line search)
10628 "Open the file at PATH.
10629 First, this expands any special file name abbreviations. Then the
10630 configuration variable `org-file-apps' is checked if it contains an
10631 entry for this file type, and if yes, the corresponding command is launched.
10633 If no application is found, Emacs simply visits the file.
10635 With optional prefix argument IN-EMACS, Emacs will visit the file.
10636 With a double \\[universal-argument] \\[universal-argument] \
10637 prefix arg, Org tries to avoid opening in Emacs
10638 and to use an external application to visit the file.
10640 Optional LINE specifies a line to go to, optional SEARCH a string
10641 to search for. If LINE or SEARCH is given, the file will be
10642 opened in Emacs, unless an entry from org-file-apps that makes
10643 use of groups in a regexp matches.
10645 If you want to change the way frames are used when following a
10646 link, please customize `org-link-frame-setup'.
10648 If the file does not exist, an error is thrown."
10649 (let* ((file (if (equal path "")
10650 buffer-file-name
10651 (substitute-in-file-name (expand-file-name path))))
10652 (file-apps (append org-file-apps (org-default-apps)))
10653 (apps (cl-remove-if
10654 'org-file-apps-entry-match-against-dlink-p file-apps))
10655 (apps-dlink (cl-remove-if-not
10656 'org-file-apps-entry-match-against-dlink-p file-apps))
10657 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10658 (dirp (unless remp (file-directory-p file)))
10659 (file (if (and dirp org-open-directory-means-index-dot-org)
10660 (concat (file-name-as-directory file) "index.org")
10661 file))
10662 (a-m-a-p (assq 'auto-mode apps))
10663 (dfile (downcase file))
10664 ;; Reconstruct the original link from the PATH, LINE and
10665 ;; SEARCH args.
10666 (link (cond (line (concat file "::" (number-to-string line)))
10667 (search (concat file "::" search))
10668 (t file)))
10669 (dlink (downcase link))
10670 (ext
10671 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10672 (match-string 1 dfile)))
10673 (save-position-maybe
10674 (let ((old-buffer (current-buffer))
10675 (old-pos (point))
10676 (old-mode major-mode))
10677 (lambda ()
10678 (and (derived-mode-p 'org-mode)
10679 (eq old-mode 'org-mode)
10680 (or (not (eq old-buffer (current-buffer)))
10681 (not (eq old-pos (point))))
10682 (org-mark-ring-push old-pos old-buffer)))))
10683 cmd link-match-data)
10684 (cond
10685 ((member in-emacs '((16) system))
10686 (setq cmd (cdr (assq 'system apps))))
10687 (in-emacs (setq cmd 'emacs))
10689 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10690 (and dirp (cdr (assq 'directory apps)))
10691 ;; First, try matching against apps-dlink if we
10692 ;; get a match here, store the match data for
10693 ;; later.
10694 (let ((match (assoc-default dlink apps-dlink
10695 'string-match)))
10696 (if match
10697 (progn (setq link-match-data (match-data))
10698 match)
10699 (progn (setq in-emacs (or in-emacs line search))
10700 nil))) ; if we have no match in apps-dlink,
10701 ; always open the file in emacs if line or search
10702 ; is given (for backwards compatibility)
10703 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10704 'string-match)
10705 (cdr (assoc ext apps))
10706 (cdr (assq t apps))))))
10707 (when (eq cmd 'system)
10708 (setq cmd (cdr (assq 'system apps))))
10709 (when (eq cmd 'default)
10710 (setq cmd (cdr (assoc t apps))))
10711 (when (eq cmd 'mailcap)
10712 (require 'mailcap)
10713 (mailcap-parse-mailcaps)
10714 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10715 (command (mailcap-mime-info mime-type)))
10716 (if (stringp command)
10717 (setq cmd command)
10718 (setq cmd 'emacs))))
10719 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10720 (not (file-exists-p file))
10721 (not org-open-non-existing-files))
10722 (user-error "No such file: %s" file))
10723 (cond
10724 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10725 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10726 (while (string-match "['\"]%s['\"]" cmd)
10727 (setq cmd (replace-match "%s" t t cmd)))
10728 (setq cmd (replace-regexp-in-string
10729 "%s"
10730 (shell-quote-argument (convert-standard-filename file))
10732 nil t))
10734 ;; Replace "%1", "%2" etc. in command with group matches from regex
10735 (save-match-data
10736 (let ((match-index 1)
10737 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10738 (set-match-data link-match-data)
10739 (while (<= match-index number-of-groups)
10740 (let ((regex (concat "%" (number-to-string match-index)))
10741 (replace-with (match-string match-index dlink)))
10742 (while (string-match regex cmd)
10743 (setq cmd (replace-match replace-with t t cmd))))
10744 (setq match-index (+ match-index 1)))))
10746 (save-window-excursion
10747 (message "Running %s...done" cmd)
10748 (start-process-shell-command cmd nil cmd)
10749 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10750 ((or (stringp cmd)
10751 (eq cmd 'emacs))
10752 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10753 (widen)
10754 (cond (line (org-goto-line line)
10755 (when (derived-mode-p 'org-mode) (org-reveal)))
10756 (search (condition-case err
10757 (org-link-search search)
10758 ;; Save position before error-ing out so user
10759 ;; can easily move back to the original buffer.
10760 (error (funcall save-position-maybe)
10761 (error (nth 1 err)))))))
10762 ((functionp cmd)
10763 (save-match-data
10764 (set-match-data link-match-data)
10765 (condition-case nil
10766 (funcall cmd file link)
10767 ;; FIXME: Remove this check when most default installations
10768 ;; of Emacs have at least Org 9.0.
10769 ((debug wrong-number-of-arguments wrong-type-argument
10770 invalid-function)
10771 (user-error "Please see Org News for version 9.0 about \
10772 `org-file-apps'--Lisp error: %S" cmd)))))
10773 ((consp cmd)
10774 ;; FIXME: Remove this check when most default installations of
10775 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10776 ;; fall back to `org-link-frame-setup' for an old usage of
10777 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10778 (user-error "Please see Org News for version 9.0 about \
10779 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10780 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10781 (funcall save-position-maybe)))
10783 (defun org-file-apps-entry-match-against-dlink-p (entry)
10784 "This function returns non-nil if `entry' uses a regular
10785 expression which should be matched against the whole link by
10786 org-open-file.
10788 It assumes that is the case when the entry uses a regular
10789 expression which has at least one grouping construct and the
10790 action is either a lisp form or a command string containing
10791 `%1', i.e. using at least one subexpression match as a
10792 parameter."
10793 (let ((selector (car entry))
10794 (action (cdr entry)))
10795 (if (stringp selector)
10796 (and (> (regexp-opt-depth selector) 0)
10797 (or (and (stringp action)
10798 (string-match "%[0-9]" action))
10799 (consp action)))
10800 nil)))
10802 (defun org-default-apps ()
10803 "Return the default applications for this operating system."
10804 (cond
10805 ((eq system-type 'darwin)
10806 org-file-apps-defaults-macosx)
10807 ((eq system-type 'windows-nt)
10808 org-file-apps-defaults-windowsnt)
10809 (t org-file-apps-defaults-gnu)))
10811 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10812 "Convert extensions to regular expressions in the cars of LIST.
10813 Also, weed out any non-string entries, because the return value is used
10814 only for regexp matching.
10815 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10816 point to the symbol `emacs', indicating that the file should
10817 be opened in Emacs."
10818 (append
10819 (delq nil
10820 (mapcar (lambda (x)
10821 (unless (not (stringp (car x)))
10822 (if (string-match "\\W" (car x))
10824 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10825 list))
10826 (when add-auto-mode
10827 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10829 (defvar ange-ftp-name-format)
10830 (defun org-file-remote-p (file)
10831 "Test whether FILE specifies a location on a remote system.
10832 Return non-nil if the location is indeed remote.
10834 For example, the filename \"/user@host:/foo\" specifies a location
10835 on the system \"/user@host:\"."
10836 (cond ((fboundp 'file-remote-p)
10837 (file-remote-p file))
10838 ((fboundp 'tramp-handle-file-remote-p)
10839 (tramp-handle-file-remote-p file))
10840 ((and (boundp 'ange-ftp-name-format)
10841 (string-match (car ange-ftp-name-format) file))
10842 t)))
10845 ;;;; Refiling
10847 (defun org-get-org-file ()
10848 "Read a filename, with default directory `org-directory'."
10849 (let ((default (or org-default-notes-file remember-data-file)))
10850 (read-file-name (format "File name [%s]: " default)
10851 (file-name-as-directory org-directory)
10852 default)))
10854 (defun org-notes-order-reversed-p ()
10855 "Check if the current file should receive notes in reversed order."
10856 (cond
10857 ((not org-reverse-note-order) nil)
10858 ((eq t org-reverse-note-order) t)
10859 ((not (listp org-reverse-note-order)) nil)
10860 (t (catch 'exit
10861 (dolist (entry org-reverse-note-order)
10862 (when (string-match (car entry) buffer-file-name)
10863 (throw 'exit (cdr entry))))))))
10865 (defvar org-refile-target-table nil
10866 "The list of refile targets, created by `org-refile'.")
10868 (defvar org-agenda-new-buffers nil
10869 "Buffers created to visit agenda files.")
10871 (defvar org-refile-cache nil
10872 "Cache for refile targets.")
10874 (defvar org-refile-markers nil
10875 "All the markers used for caching refile locations.")
10877 (defun org-refile-marker (pos)
10878 "Get a new refile marker, but only if caching is in use."
10879 (if (not org-refile-use-cache)
10881 (let ((m (make-marker)))
10882 (move-marker m pos)
10883 (push m org-refile-markers)
10884 m)))
10886 (defun org-refile-cache-clear ()
10887 "Clear the refile cache and disable all the markers."
10888 (dolist (m org-refile-markers) (move-marker m nil))
10889 (setq org-refile-markers nil)
10890 (setq org-refile-cache nil)
10891 (message "Refile cache has been cleared"))
10893 (defun org-refile-cache-check-set (set)
10894 "Check if all the markers in the cache still have live buffers."
10895 (let (marker)
10896 (catch 'exit
10897 (while (and set (setq marker (nth 3 (pop set))))
10898 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10899 (when (and marker (null (marker-buffer marker)))
10900 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10901 (sit-for 3)
10902 (throw 'exit nil)))
10903 t)))
10905 (defun org-refile-cache-put (set &rest identifiers)
10906 "Push the refile targets SET into the cache, under IDENTIFIERS."
10907 (let* ((key (sha1 (prin1-to-string identifiers)))
10908 (entry (assoc key org-refile-cache)))
10909 (if entry
10910 (setcdr entry set)
10911 (push (cons key set) org-refile-cache))))
10913 (defun org-refile-cache-get (&rest identifiers)
10914 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10915 (cond
10916 ((not org-refile-cache) nil)
10917 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10919 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10920 org-refile-cache))))
10921 (and set (org-refile-cache-check-set set) set)))))
10923 (defvar org-outline-path-cache nil
10924 "Alist between buffer positions and outline paths.
10925 It value is an alist (POSITION . PATH) where POSITION is the
10926 buffer position at the beginning of an entry and PATH is a list
10927 of strings describing the outline path for that entry, in reverse
10928 order.")
10930 (defun org-refile-get-targets (&optional default-buffer)
10931 "Produce a table with refile targets."
10932 (let ((case-fold-search nil)
10933 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10934 (entries (or org-refile-targets '((nil . (:level . 1)))))
10935 targets tgs files desc descre)
10936 (message "Getting targets...")
10937 (with-current-buffer (or default-buffer (current-buffer))
10938 (dolist (entry entries)
10939 (setq files (car entry) desc (cdr entry))
10940 (cond
10941 ((null files) (setq files (list (current-buffer))))
10942 ((eq files 'org-agenda-files)
10943 (setq files (org-agenda-files 'unrestricted)))
10944 ((and (symbolp files) (fboundp files))
10945 (setq files (funcall files)))
10946 ((and (symbolp files) (boundp files))
10947 (setq files (symbol-value files))))
10948 (when (stringp files) (setq files (list files)))
10949 (cond
10950 ((eq (car desc) :tag)
10951 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10952 ((eq (car desc) :todo)
10953 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10954 ((eq (car desc) :regexp)
10955 (setq descre (cdr desc)))
10956 ((eq (car desc) :level)
10957 (setq descre (concat "^\\*\\{" (number-to-string
10958 (if org-odd-levels-only
10959 (1- (* 2 (cdr desc)))
10960 (cdr desc)))
10961 "\\}[ \t]")))
10962 ((eq (car desc) :maxlevel)
10963 (setq descre (concat "^\\*\\{1," (number-to-string
10964 (if org-odd-levels-only
10965 (1- (* 2 (cdr desc)))
10966 (cdr desc)))
10967 "\\}[ \t]")))
10968 (t (error "Bad refiling target description %s" desc)))
10969 (dolist (f files)
10970 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10972 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10973 (progn
10974 (when (bufferp f)
10975 (setq f (buffer-file-name (buffer-base-buffer f))))
10976 (setq f (and f (expand-file-name f)))
10977 (when (eq org-refile-use-outline-path 'file)
10978 (push (list (file-name-nondirectory f) f nil nil) tgs))
10979 (when (eq org-refile-use-outline-path 'buffer-name)
10980 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10981 (when (eq org-refile-use-outline-path 'full-file-path)
10982 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10983 (org-with-wide-buffer
10984 (goto-char (point-min))
10985 (setq org-outline-path-cache nil)
10986 (while (re-search-forward descre nil t)
10987 (beginning-of-line)
10988 (let ((case-fold-search nil))
10989 (looking-at org-complex-heading-regexp))
10990 (let ((begin (point))
10991 (heading (match-string-no-properties 4)))
10992 (unless (or (and
10993 org-refile-target-verify-function
10994 (not
10995 (funcall org-refile-target-verify-function)))
10996 (not heading))
10997 (let ((re (format org-complex-heading-regexp-format
10998 (regexp-quote heading)))
10999 (target
11000 (if (not org-refile-use-outline-path) heading
11001 (mapconcat
11002 #'identity
11003 (append
11004 (pcase org-refile-use-outline-path
11005 (`file (list (file-name-nondirectory
11006 (buffer-file-name
11007 (buffer-base-buffer)))))
11008 (`full-file-path
11009 (list (buffer-file-name
11010 (buffer-base-buffer))))
11011 (`buffer-name
11012 (list (buffer-name
11013 (buffer-base-buffer))))
11014 (_ nil))
11015 (mapcar (lambda (s) (replace-regexp-in-string
11016 "/" "\\/" s nil t))
11017 (org-get-outline-path t t)))
11018 "/"))))
11019 (push (list target f re (org-refile-marker (point)))
11020 tgs)))
11021 (when (= (point) begin)
11022 ;; Verification function has not moved point.
11023 (end-of-line)))))))
11024 (when org-refile-use-cache
11025 (org-refile-cache-put tgs (buffer-file-name) descre))
11026 (setq targets (append tgs targets))))))
11027 (message "Getting targets...done")
11028 (delete-dups (nreverse targets))))
11030 (defun org--get-outline-path-1 (&optional use-cache)
11031 "Return outline path to current headline.
11033 Outline path is a list of strings, in reverse order. When
11034 optional argument USE-CACHE is non-nil, make use of a cache. See
11035 `org-get-outline-path' for details.
11037 Assume buffer is widened and point is on a headline."
11038 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11039 (let ((p (point))
11040 (heading (let ((case-fold-search nil))
11041 (looking-at org-complex-heading-regexp)
11042 (if (not (match-end 4)) ""
11043 ;; Remove statistics cookies.
11044 (org-trim
11045 (org-link-display-format
11046 (replace-regexp-in-string
11047 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11048 (match-string-no-properties 4))))))))
11049 (if (org-up-heading-safe)
11050 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11051 (when use-cache
11052 (push (cons p path) org-outline-path-cache))
11053 path)
11054 ;; This is a new root node. Since we assume we are moving
11055 ;; forward, we can drop previous cache so as to limit number
11056 ;; of associations there.
11057 (let ((path (list heading)))
11058 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11059 path)))))
11061 (defun org-get-outline-path (&optional with-self use-cache)
11062 "Return the outline path to the current entry.
11064 An outline path is a list of ancestors for current headline, as
11065 a list of strings. Statistics cookies are removed and links are
11066 replaced with their description, if any, or their path otherwise.
11068 When optional argument WITH-SELF is non-nil, the path also
11069 includes the current headline.
11071 When optional argument USE-CACHE is non-nil, cache outline paths
11072 between calls to this function so as to avoid backtracking. This
11073 argument is useful when planning to find more than one outline
11074 path in the same document. In that case, there are two
11075 conditions to satisfy:
11076 - `org-outline-path-cache' is set to nil before starting the
11077 process;
11078 - outline paths are computed by increasing buffer positions."
11079 (org-with-wide-buffer
11080 (and (or (and with-self (org-back-to-heading t))
11081 (org-up-heading-safe))
11082 (reverse (org--get-outline-path-1 use-cache)))))
11084 (defun org-format-outline-path (path &optional width prefix separator)
11085 "Format the outline path PATH for display.
11086 WIDTH is the maximum number of characters that is available.
11087 PREFIX is a prefix to be included in the returned string,
11088 such as the file name.
11089 SEPARATOR is inserted between the different parts of the path,
11090 the default is \"/\"."
11091 (setq width (or width 79))
11092 (setq path (delq nil path))
11093 (unless (> width 0)
11094 (user-error "Argument `width' must be positive"))
11095 (setq separator (or separator "/"))
11096 (let* ((org-odd-levels-only nil)
11097 (fpath (concat
11098 prefix (and prefix path separator)
11099 (mapconcat
11100 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11101 (cl-loop for head in path
11102 for n from 0
11103 collect (org-add-props
11104 head nil 'face
11105 (nth (% n org-n-level-faces) org-level-faces)))
11106 separator))))
11107 (when (> (length fpath) width)
11108 (if (< width 7)
11109 ;; It's unlikely that `width' will be this small, but don't
11110 ;; waste characters by adding ".." if it is.
11111 (setq fpath (substring fpath 0 width))
11112 (setf (substring fpath (- width 2)) "..")))
11113 fpath))
11115 (defun org-display-outline-path (&optional file current separator just-return-string)
11116 "Display the current outline path in the echo area.
11118 If FILE is non-nil, prepend the output with the file name.
11119 If CURRENT is non-nil, append the current heading to the output.
11120 SEPARATOR is passed through to `org-format-outline-path'. It separates
11121 the different parts of the path and defaults to \"/\".
11122 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11123 (interactive "P")
11124 (let* (case-fold-search
11125 (bfn (buffer-file-name (buffer-base-buffer)))
11126 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11127 res)
11128 (when current (setq path (append path
11129 (save-excursion
11130 (org-back-to-heading t)
11131 (when (looking-at org-complex-heading-regexp)
11132 (list (match-string 4)))))))
11133 (setq res
11134 (org-format-outline-path
11135 path
11136 (1- (frame-width))
11137 (and file bfn (concat (file-name-nondirectory bfn) separator))
11138 separator))
11139 (if just-return-string
11140 (org-no-properties res)
11141 (org-unlogged-message "%s" res))))
11143 (defvar org-refile-history nil
11144 "History for refiling operations.")
11146 (defvar org-after-refile-insert-hook nil
11147 "Hook run after `org-refile' has inserted its stuff at the new location.
11148 Note that this is still *before* the stuff will be removed from
11149 the *old* location.")
11151 (defvar org-capture-last-stored-marker)
11152 (defvar org-refile-keep nil
11153 "Non-nil means `org-refile' will copy instead of refile.")
11155 (defun org-copy ()
11156 "Like `org-refile', but copy."
11157 (interactive)
11158 (let ((org-refile-keep t))
11159 (funcall 'org-refile nil nil nil "Copy")))
11161 (defun org-refile (&optional arg default-buffer rfloc msg)
11162 "Move the entry or entries at point to another heading.
11164 The list of target headings is compiled using the information in
11165 `org-refile-targets', which see.
11167 At the target location, the entry is filed as a subitem of the
11168 target heading. Depending on `org-reverse-note-order', the new
11169 subitem will either be the first or the last subitem.
11171 If there is an active region, all entries in that region will be
11172 refiled. However, the region must fulfill the requirement that
11173 the first heading sets the top-level of the moved text.
11175 With a `\\[universal-argument]' ARG, the command will only visit the target \
11176 location
11177 and not actually move anything.
11179 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11180 location where the last
11181 refiling operation has put the subtree.
11183 With a numeric prefix argument of `2', refile to the running clock.
11185 With a numeric prefix argument of `3', emulate `org-refile-keep'
11186 being set to t and copy to the target location, don't move it.
11187 Beware that keeping refiled entries may result in duplicated ID
11188 properties.
11190 RFLOC can be a refile location obtained in a different way.
11192 MSG is a string to replace \"Refile\" in the default prompt with
11193 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11195 See also `org-refile-use-outline-path'.
11197 If you are using target caching (see `org-refile-use-cache'), you
11198 have to clear the target cache in order to find new targets.
11199 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11200 prefix argument (`C-u C-u C-u C-c C-w')."
11201 (interactive "P")
11202 (if (member arg '(0 (64)))
11203 (org-refile-cache-clear)
11204 (let* ((actionmsg (cond (msg msg)
11205 ((equal arg 3) "Refile (and keep)")
11206 (t "Refile")))
11207 (regionp (org-region-active-p))
11208 (region-start (and regionp (region-beginning)))
11209 (region-end (and regionp (region-end)))
11210 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11211 pos it nbuf file level reversed)
11212 (setq last-command nil)
11213 (when regionp
11214 (goto-char region-start)
11215 (or (bolp) (goto-char (point-at-bol)))
11216 (setq region-start (point))
11217 (unless (or (org-kill-is-subtree-p
11218 (buffer-substring region-start region-end))
11219 (prog1 org-refile-active-region-within-subtree
11220 (let ((s (point-at-eol)))
11221 (org-toggle-heading)
11222 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11223 (user-error "The region is not a (sequence of) subtree(s)")))
11224 (if (equal arg '(16))
11225 (org-refile-goto-last-stored)
11226 (when (or
11227 (and (equal arg 2)
11228 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11229 (prog1
11230 (setq it (list (or org-clock-heading "running clock")
11231 (buffer-file-name
11232 (marker-buffer org-clock-hd-marker))
11234 (marker-position org-clock-hd-marker)))
11235 (setq arg nil)))
11236 (setq it
11237 (or rfloc
11238 (let (heading-text)
11239 (save-excursion
11240 (unless (and arg (listp arg))
11241 (org-back-to-heading t)
11242 (setq heading-text
11243 (replace-regexp-in-string
11244 org-bracket-link-regexp
11245 "\\3"
11246 (or (nth 4 (org-heading-components))
11247 ""))))
11248 (org-refile-get-location
11249 (cond ((and arg (listp arg)) "Goto")
11250 (regionp (concat actionmsg " region to"))
11251 (t (concat actionmsg " subtree \""
11252 heading-text "\" to")))
11253 default-buffer
11254 (and (not (equal '(4) arg))
11255 org-refile-allow-creating-parent-nodes)))))))
11256 (setq file (nth 1 it)
11257 pos (nth 3 it))
11258 (when (and (not arg)
11260 (equal (buffer-file-name) file)
11261 (if regionp
11262 (and (>= pos region-start)
11263 (<= pos region-end))
11264 (and (>= pos (point))
11265 (< pos (save-excursion
11266 (org-end-of-subtree t t))))))
11267 (error "Cannot refile to position inside the tree or region"))
11268 (setq nbuf (or (find-buffer-visiting file)
11269 (find-file-noselect file)))
11270 (if (and arg (not (equal arg 3)))
11271 (progn
11272 (pop-to-buffer-same-window nbuf)
11273 (goto-char (cond (pos)
11274 ((org-notes-order-reversed-p) (point-min))
11275 (t (point-max))))
11276 (org-show-context 'org-goto))
11277 (if regionp
11278 (progn
11279 (org-kill-new (buffer-substring region-start region-end))
11280 (org-save-markers-in-region region-start region-end))
11281 (org-copy-subtree 1 nil t))
11282 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11283 (find-file-noselect file)))
11284 (setq reversed (org-notes-order-reversed-p))
11285 (org-with-wide-buffer
11286 (if pos
11287 (progn
11288 (goto-char pos)
11289 (setq level (org-get-valid-level (funcall outline-level) 1))
11290 (goto-char
11291 (if reversed
11292 (or (outline-next-heading) (point-max))
11293 (or (save-excursion (org-get-next-sibling))
11294 (org-end-of-subtree t t)
11295 (point-max)))))
11296 (setq level 1)
11297 (if (not reversed)
11298 (goto-char (point-max))
11299 (goto-char (point-min))
11300 (or (outline-next-heading) (goto-char (point-max)))))
11301 (unless (bolp) (newline))
11302 (org-paste-subtree level nil nil t)
11303 (when org-log-refile
11304 (org-add-log-setup 'refile nil nil org-log-refile)
11305 (unless (eq org-log-refile 'note)
11306 (save-excursion (org-add-log-note))))
11307 (and org-auto-align-tags
11308 (let ((org-loop-over-headlines-in-active-region nil))
11309 (org-set-tags nil t)))
11310 (let ((bookmark-name (plist-get org-bookmark-names-plist
11311 :last-refile)))
11312 (when bookmark-name
11313 (with-demoted-errors
11314 (bookmark-set bookmark-name))))
11315 ;; If we are refiling for capture, make sure that the
11316 ;; last-capture pointers point here
11317 (when (bound-and-true-p org-capture-is-refiling)
11318 (let ((bookmark-name (plist-get org-bookmark-names-plist
11319 :last-capture-marker)))
11320 (when bookmark-name
11321 (with-demoted-errors
11322 (bookmark-set bookmark-name))))
11323 (move-marker org-capture-last-stored-marker (point)))
11324 (when (fboundp 'deactivate-mark) (deactivate-mark))
11325 (run-hooks 'org-after-refile-insert-hook)))
11326 (unless org-refile-keep
11327 (if regionp
11328 (delete-region (point) (+ (point) (- region-end region-start)))
11329 (org-preserve-local-variables
11330 (delete-region
11331 (and (org-back-to-heading t) (point))
11332 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11333 (when (featurep 'org-inlinetask)
11334 (org-inlinetask-remove-END-maybe))
11335 (setq org-markers-to-move nil)
11336 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11338 (defun org-refile-goto-last-stored ()
11339 "Go to the location where the last refile was stored."
11340 (interactive)
11341 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11342 (message "This is the location of the last refile"))
11344 (defun org-refile--get-location (refloc tbl)
11345 "When user refile to REFLOC, find the associated target in TBL.
11346 Also check `org-refile-target-table'."
11347 (car (delq
11349 (mapcar
11350 (lambda (r) (or (assoc r tbl)
11351 (assoc r org-refile-target-table)))
11352 (list (replace-regexp-in-string "/$" "" refloc)
11353 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11355 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11356 "Prompt the user for a refile location, using PROMPT.
11357 PROMPT should not be suffixed with a colon and a space, because
11358 this function appends the default value from
11359 `org-refile-history' automatically, if that is not empty."
11360 (let ((org-refile-targets org-refile-targets)
11361 (org-refile-use-outline-path org-refile-use-outline-path))
11362 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11363 (unless org-refile-target-table
11364 (user-error "No refile targets"))
11365 (let* ((cbuf (current-buffer))
11366 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11367 (cfunc (if (and org-refile-use-outline-path
11368 org-outline-path-complete-in-steps)
11369 #'org-olpath-completing-read
11370 #'completing-read))
11371 (extra (if org-refile-use-outline-path "/" ""))
11372 (cbnex (concat (buffer-name) extra))
11373 (filename (and cfn (expand-file-name cfn)))
11374 (tbl (mapcar
11375 (lambda (x)
11376 (if (and (not (member org-refile-use-outline-path
11377 '(file full-file-path)))
11378 (not (equal filename (nth 1 x))))
11379 (cons (concat (car x) extra " ("
11380 (file-name-nondirectory (nth 1 x)) ")")
11381 (cdr x))
11382 (cons (concat (car x) extra) (cdr x))))
11383 org-refile-target-table))
11384 (completion-ignore-case t)
11385 cdef
11386 (prompt (concat prompt
11387 (or (and (car org-refile-history)
11388 (concat " (default " (car org-refile-history) ")"))
11389 (and (assoc cbnex tbl) (setq cdef cbnex)
11390 (concat " (default " cbnex ")"))) ": "))
11391 pa answ parent-target child parent old-hist)
11392 (setq old-hist org-refile-history)
11393 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11394 nil 'org-refile-history (or cdef (car org-refile-history))))
11395 (if (setq pa (org-refile--get-location answ tbl))
11396 (progn
11397 (org-refile-check-position pa)
11398 (when (or (not org-refile-history)
11399 (not (eq old-hist org-refile-history))
11400 (not (equal (car pa) (car org-refile-history))))
11401 (setq org-refile-history
11402 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11403 org-refile-history
11404 (cdr org-refile-history))))
11405 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11406 (pop org-refile-history)))
11408 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11409 (progn
11410 (setq parent (match-string 1 answ)
11411 child (match-string 2 answ))
11412 (setq parent-target (org-refile--get-location parent tbl))
11413 (when (and parent-target
11414 (or (eq new-nodes t)
11415 (and (eq new-nodes 'confirm)
11416 (y-or-n-p (format "Create new node \"%s\"? "
11417 child)))))
11418 (org-refile-new-child parent-target child)))
11419 (user-error "Invalid target location")))))
11421 (declare-function org-string-nw-p "org-macs" (s))
11422 (defun org-refile-check-position (refile-pointer)
11423 "Check if the refile pointer matches the headline to which it points."
11424 (let* ((file (nth 1 refile-pointer))
11425 (re (nth 2 refile-pointer))
11426 (pos (nth 3 refile-pointer))
11427 buffer)
11428 (if (and (not (markerp pos)) (not file))
11429 (user-error "Please indicate a target file in the refile path")
11430 (when (org-string-nw-p re)
11431 (setq buffer (if (markerp pos)
11432 (marker-buffer pos)
11433 (or (find-buffer-visiting file)
11434 (find-file-noselect file))))
11435 (with-current-buffer buffer
11436 (org-with-wide-buffer
11437 (goto-char pos)
11438 (beginning-of-line 1)
11439 (unless (looking-at-p re)
11440 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11442 (defun org-refile-new-child (parent-target child)
11443 "Use refile target PARENT-TARGET to add new CHILD below it."
11444 (unless parent-target
11445 (error "Cannot find parent for new node"))
11446 (let ((file (nth 1 parent-target))
11447 (pos (nth 3 parent-target))
11448 level)
11449 (with-current-buffer (or (find-buffer-visiting file)
11450 (find-file-noselect file))
11451 (org-with-wide-buffer
11452 (if pos
11453 (goto-char pos)
11454 (goto-char (point-max))
11455 (unless (bolp) (newline)))
11456 (when (looking-at org-outline-regexp)
11457 (setq level (funcall outline-level))
11458 (org-end-of-subtree t t))
11459 (org-back-over-empty-lines)
11460 (insert "\n" (make-string
11461 (if pos (org-get-valid-level level 1) 1) ?*)
11462 " " child "\n")
11463 (beginning-of-line 0)
11464 (list (concat (car parent-target) "/" child) file "" (point))))))
11466 (defun org-olpath-completing-read (prompt collection &rest args)
11467 "Read an outline path like a file name."
11468 (let ((thetable collection))
11469 (apply #'completing-read
11470 prompt
11471 (lambda (string predicate &optional flag)
11472 (cond
11473 ((eq flag nil) (try-completion string thetable))
11474 ((eq flag t)
11475 (let ((l (length string)))
11476 (mapcar (lambda (x)
11477 (let ((r (substring x l))
11478 (f (if (string-match " ([^)]*)$" x)
11479 (match-string 0 x)
11480 "")))
11481 (if (string-match "/" r)
11482 (concat string (substring r 0 (match-end 0)) f)
11483 x)))
11484 (all-completions string thetable predicate))))
11485 ;; Exact match?
11486 ((eq flag 'lambda) (assoc string thetable))))
11487 args)))
11489 ;;;; Dynamic blocks
11491 (defun org-find-dblock (name)
11492 "Find the first dynamic block with name NAME in the buffer.
11493 If not found, stay at current position and return nil."
11494 (let ((case-fold-search t) pos)
11495 (save-excursion
11496 (goto-char (point-min))
11497 (setq pos (and (re-search-forward
11498 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11499 (match-beginning 0))))
11500 (when pos (goto-char pos))
11501 pos))
11503 (defun org-create-dblock (plist)
11504 "Create a dynamic block section, with parameters taken from PLIST.
11505 PLIST must contain a :name entry which is used as the name of the block."
11506 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11507 (end-of-line 1)
11508 (newline))
11509 (let ((col (current-column))
11510 (name (plist-get plist :name)))
11511 (insert "#+BEGIN: " name)
11512 (while plist
11513 (if (eq (car plist) :name)
11514 (setq plist (cddr plist))
11515 (insert " " (prin1-to-string (pop plist)))))
11516 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11517 (beginning-of-line -2)))
11519 (defun org-prepare-dblock ()
11520 "Prepare dynamic block for refresh.
11521 This empties the block, puts the cursor at the insert position and returns
11522 the property list including an extra property :name with the block name."
11523 (unless (looking-at org-dblock-start-re)
11524 (user-error "Not at a dynamic block"))
11525 (let* ((begdel (1+ (match-end 0)))
11526 (name (org-no-properties (match-string 1)))
11527 (params (append (list :name name)
11528 (read (concat "(" (match-string 3) ")")))))
11529 (save-excursion
11530 (beginning-of-line 1)
11531 (skip-chars-forward " \t")
11532 (setq params (plist-put params :indentation-column (current-column))))
11533 (unless (re-search-forward org-dblock-end-re nil t)
11534 (error "Dynamic block not terminated"))
11535 (setq params
11536 (append params
11537 (list :content (buffer-substring
11538 begdel (match-beginning 0)))))
11539 (delete-region begdel (match-beginning 0))
11540 (goto-char begdel)
11541 (open-line 1)
11542 params))
11544 (defun org-map-dblocks (&optional command)
11545 "Apply COMMAND to all dynamic blocks in the current buffer.
11546 If COMMAND is not given, use `org-update-dblock'."
11547 (let ((cmd (or command 'org-update-dblock)))
11548 (save-excursion
11549 (goto-char (point-min))
11550 (while (re-search-forward org-dblock-start-re nil t)
11551 (goto-char (match-beginning 0))
11552 (save-excursion
11553 (condition-case nil
11554 (funcall cmd)
11555 (error (message "Error during update of dynamic block"))))
11556 (unless (re-search-forward org-dblock-end-re nil t)
11557 (error "Dynamic block not terminated"))))))
11559 (defun org-dblock-update (&optional arg)
11560 "User command for updating dynamic blocks.
11561 Update the dynamic block at point. With prefix ARG, update all dynamic
11562 blocks in the buffer."
11563 (interactive "P")
11564 (if arg
11565 (org-update-all-dblocks)
11566 (or (looking-at org-dblock-start-re)
11567 (org-beginning-of-dblock))
11568 (org-update-dblock)))
11570 (defun org-update-dblock ()
11571 "Update the dynamic block at point.
11572 This means to empty the block, parse for parameters and then call
11573 the correct writing function."
11574 (interactive)
11575 (save-excursion
11576 (let* ((win (selected-window))
11577 (pos (point))
11578 (line (org-current-line))
11579 (params (org-prepare-dblock))
11580 (name (plist-get params :name))
11581 (indent (plist-get params :indentation-column))
11582 (cmd (intern (concat "org-dblock-write:" name))))
11583 (message "Updating dynamic block `%s' at line %d..." name line)
11584 (funcall cmd params)
11585 (message "Updating dynamic block `%s' at line %d...done" name line)
11586 (goto-char pos)
11587 (when (and indent (> indent 0))
11588 (setq indent (make-string indent ?\ ))
11589 (save-excursion
11590 (select-window win)
11591 (org-beginning-of-dblock)
11592 (forward-line 1)
11593 (while (not (looking-at org-dblock-end-re))
11594 (insert indent)
11595 (beginning-of-line 2))
11596 (when (looking-at org-dblock-end-re)
11597 (and (looking-at "[ \t]+")
11598 (replace-match ""))
11599 (insert indent)))))))
11601 (defun org-beginning-of-dblock ()
11602 "Find the beginning of the dynamic block at point.
11603 Error if there is no such block at point."
11604 (let ((pos (point))
11605 beg)
11606 (end-of-line 1)
11607 (if (and (re-search-backward org-dblock-start-re nil t)
11608 (setq beg (match-beginning 0))
11609 (re-search-forward org-dblock-end-re nil t)
11610 (> (match-end 0) pos))
11611 (goto-char beg)
11612 (goto-char pos)
11613 (error "Not in a dynamic block"))))
11615 (defun org-update-all-dblocks ()
11616 "Update all dynamic blocks in the buffer.
11617 This function can be used in a hook."
11618 (interactive)
11619 (when (derived-mode-p 'org-mode)
11620 (org-map-dblocks 'org-update-dblock)))
11623 ;;;; Completion
11625 (declare-function org-export-backend-options "ox" (cl-x) t)
11626 (defun org-get-export-keywords ()
11627 "Return a list of all currently understood export keywords.
11628 Export keywords include options, block names, attributes and
11629 keywords relative to each registered export back-end."
11630 (let (keywords)
11631 (dolist (backend
11632 (bound-and-true-p org-export-registered-backends)
11633 (delq nil keywords))
11634 ;; Back-end name (for keywords, like #+LATEX:)
11635 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11636 (dolist (option-entry (org-export-backend-options backend))
11637 ;; Back-end options.
11638 (push (nth 1 option-entry) keywords)))))
11640 (defconst org-options-keywords
11641 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11642 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11643 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11644 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11645 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11647 (defcustom org-structure-template-alist
11648 '((?a . "export ascii")
11649 (?c . "center")
11650 (?C . "comment")
11651 (?e . "example")
11652 (?E . "export")
11653 (?h . "export html")
11654 (?l . "export latex")
11655 (?q . "quote")
11656 (?s . "src")
11657 (?v . "verse"))
11658 "Structure completion elements.
11659 This is an alist of characters and values. When
11660 `org-insert-structure-template' is called, an additional key is
11661 read. The key is first looked up in this alist, and the
11662 corresponding structure is inserted, with \"#+BEGIN_\" and
11663 \"#+END_\" added automatically."
11664 :group 'org-edit-structure
11665 :type '(repeat
11666 (cons (character :tag "Key")
11667 (string :tag "Template")))
11668 :package-version '(Org . "9.2"))
11670 (defun org-insert-structure-template (type)
11671 "Insert a block structure of the type #+begin_foo/#+end_foo.
11672 First read a character, which can be one of the keys in
11673 `org-structure-template-alist'. When it is <TAB>, prompt the
11674 user for a string to use. With an active region, wrap the region
11675 in the block. Otherwise, insert an empty block."
11676 (interactive
11677 (list
11678 (let* ((key (read-key "Key: "))
11679 (struct-string
11680 (or (cdr (assq key org-structure-template-alist))
11681 (and (= key ?\t)
11682 (read-string "Structure type: "))
11683 (user-error "`%c' has no structure definition" key))))
11684 struct-string)))
11685 (let* ((region? (use-region-p))
11686 (s (if region? (region-beginning) (point)))
11687 (e (copy-marker (if region? (region-end) (point)) t))
11688 column)
11689 (when (string-match-p
11690 (concat "\\`" (regexp-opt '("example" "export" "src")))
11691 type)
11692 (org-escape-code-in-region s e))
11693 (goto-char s)
11694 (setq column (current-indentation))
11695 (beginning-of-line)
11696 (indent-to column)
11697 (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
11698 (goto-char e)
11699 (if (bolp)
11700 (progn
11701 (skip-chars-backward " \n\t")
11702 (forward-line))
11703 (end-of-line)
11704 (insert "\n"))
11705 (indent-to column)
11706 (insert (format "#+end_%s\n"
11707 (car (split-string type))))
11708 (when (or (not region?)
11709 (string-match-p "src\\|\\`export\\'" type))
11710 (goto-char s)
11711 (end-of-line))
11712 (set-marker e nil)))
11714 ;;;; TODO, DEADLINE, Comments
11716 (defun org-toggle-comment ()
11717 "Change the COMMENT state of an entry."
11718 (interactive)
11719 (save-excursion
11720 (org-back-to-heading)
11721 (let ((case-fold-search nil))
11722 (looking-at org-complex-heading-regexp))
11723 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11724 (skip-chars-forward " \t")
11725 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11726 (if (org-in-commented-heading-p t)
11727 (delete-region (point)
11728 (progn (search-forward " " (line-end-position) 'move)
11729 (skip-chars-forward " \t")
11730 (point)))
11731 (insert org-comment-string)
11732 (unless (eolp) (insert " ")))))
11734 (defvar org-last-todo-state-is-todo nil
11735 "This is non-nil when the last TODO state change led to a TODO state.
11736 If the last change removed the TODO tag or switched to DONE, then
11737 this is nil.")
11739 (defvar org-setting-tags nil) ; dynamically skipped
11741 (defvar org-todo-setup-filter-hook nil
11742 "Hook for functions that pre-filter todo specs.
11743 Each function takes a todo spec and returns either nil or the spec
11744 transformed into canonical form." )
11746 (defvar org-todo-get-default-hook nil
11747 "Hook for functions that get a default item for todo.
11748 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11749 nil or a string to be used for the todo mark." )
11751 (defvar org-agenda-headline-snapshot-before-repeat)
11753 (defun org-current-effective-time ()
11754 "Return current time adjusted for `org-extend-today-until' variable."
11755 (let* ((ct (org-current-time))
11756 (dct (decode-time ct))
11757 (ct1
11758 (cond
11759 (org-use-last-clock-out-time-as-effective-time
11760 (or (org-clock-get-last-clock-out-time) ct))
11761 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11762 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11763 (t ct))))
11764 ct1))
11766 (defun org-todo-yesterday (&optional arg)
11767 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11768 (interactive "P")
11769 (if (eq major-mode 'org-agenda-mode)
11770 (apply 'org-agenda-todo-yesterday arg)
11771 (let* ((org-use-effective-time t)
11772 (hour (nth 2 (decode-time (org-current-time))))
11773 (org-extend-today-until (1+ hour)))
11774 (org-todo arg))))
11776 (defvar org-block-entry-blocking ""
11777 "First entry preventing the TODO state change.")
11779 (defun org-cancel-repeater ()
11780 "Cancel a repeater by setting its numeric value to zero."
11781 (interactive)
11782 (save-excursion
11783 (org-back-to-heading t)
11784 (let ((bound1 (point))
11785 (bound0 (save-excursion (outline-next-heading) (point))))
11786 (when (and (re-search-forward
11787 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11788 org-deadline-time-regexp "\\)\\|\\("
11789 org-ts-regexp "\\)")
11790 bound0 t)
11791 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11792 bound1 t))
11793 (replace-match "0" t nil nil 1)))))
11795 (defvar org-state)
11796 (defvar org-blocked-by-checkboxes)
11797 (defun org-todo (&optional arg)
11798 "Change the TODO state of an item.
11800 The state of an item is given by a keyword at the start of the heading,
11801 like
11802 *** TODO Write paper
11803 *** DONE Call mom
11805 The different keywords are specified in the variable `org-todo-keywords'.
11806 By default the available states are \"TODO\" and \"DONE\". So, for this
11807 example: when the item starts with TODO, it is changed to DONE.
11808 When it starts with DONE, the DONE is removed. And when neither TODO nor
11809 DONE are present, add TODO at the beginning of the heading.
11811 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11812 state.
11813 With numeric prefix ARG, switch to that state.
11814 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11815 next set of TODO \
11816 keywords (nextset).
11817 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11818 prefix, circumvent any state blocking.
11819 With a numeric prefix arg of 0, inhibit note taking for the change.
11820 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11822 When called through ELisp, arg is also interpreted in the following way:
11823 `none' -> empty state
11824 \"\" -> switch to empty state
11825 `done' -> switch to DONE
11826 `nextset' -> switch to the next set of keywords
11827 `previousset' -> switch to the previous set of keywords
11828 \"WAITING\" -> switch to the specified keyword, but only if it
11829 really is a member of `org-todo-keywords'."
11830 (interactive "P")
11831 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11832 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11833 'region-start-level 'region))
11834 org-loop-over-headlines-in-active-region)
11835 (org-map-entries
11836 `(org-todo ,arg)
11837 org-loop-over-headlines-in-active-region
11838 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11839 (when (equal arg '(16)) (setq arg 'nextset))
11840 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11841 (let ((org-blocker-hook org-blocker-hook)
11842 commentp
11843 case-fold-search)
11844 (when (equal arg '(64))
11845 (setq arg nil org-blocker-hook nil))
11846 (when (and org-blocker-hook
11847 (or org-inhibit-blocking
11848 (org-entry-get nil "NOBLOCKING")))
11849 (setq org-blocker-hook nil))
11850 (save-excursion
11851 (catch 'exit
11852 (org-back-to-heading t)
11853 (when (org-in-commented-heading-p t)
11854 (org-toggle-comment)
11855 (setq commentp t))
11856 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11857 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11858 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11859 (let* ((match-data (match-data))
11860 (startpos (copy-marker (line-beginning-position)))
11861 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11862 (org-log-done org-log-done)
11863 (org-log-repeat org-log-repeat)
11864 (org-todo-log-states org-todo-log-states)
11865 (org-inhibit-logging
11866 (if (equal arg 0)
11867 (progn (setq arg nil) 'note) org-inhibit-logging))
11868 (this (match-string 1))
11869 (hl-pos (match-beginning 0))
11870 (head (org-get-todo-sequence-head this))
11871 (ass (assoc head org-todo-kwd-alist))
11872 (interpret (nth 1 ass))
11873 (done-word (nth 3 ass))
11874 (final-done-word (nth 4 ass))
11875 (org-last-state (or this ""))
11876 (completion-ignore-case t)
11877 (member (member this org-todo-keywords-1))
11878 (tail (cdr member))
11879 (org-state (cond
11880 ((and org-todo-key-trigger
11881 (or (and (equal arg '(4))
11882 (eq org-use-fast-todo-selection 'prefix))
11883 (and (not arg) org-use-fast-todo-selection
11884 (not (eq org-use-fast-todo-selection
11885 'prefix)))))
11886 ;; Use fast selection.
11887 (org-fast-todo-selection))
11888 ((and (equal arg '(4))
11889 (or (not org-use-fast-todo-selection)
11890 (not org-todo-key-trigger)))
11891 ;; Read a state with completion.
11892 (completing-read
11893 "State: " (mapcar #'list org-todo-keywords-1)
11894 nil t))
11895 ((eq arg 'right)
11896 (if this
11897 (if tail (car tail) nil)
11898 (car org-todo-keywords-1)))
11899 ((eq arg 'left)
11900 (unless (equal member org-todo-keywords-1)
11901 (if this
11902 (nth (- (length org-todo-keywords-1)
11903 (length tail) 2)
11904 org-todo-keywords-1)
11905 (org-last org-todo-keywords-1))))
11906 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11907 (setq arg nil))) ;hack to fall back to cycling
11908 (arg
11909 ;; User or caller requests a specific state.
11910 (cond
11911 ((equal arg "") nil)
11912 ((eq arg 'none) nil)
11913 ((eq arg 'done) (or done-word (car org-done-keywords)))
11914 ((eq arg 'nextset)
11915 (or (car (cdr (member head org-todo-heads)))
11916 (car org-todo-heads)))
11917 ((eq arg 'previousset)
11918 (let ((org-todo-heads (reverse org-todo-heads)))
11919 (or (car (cdr (member head org-todo-heads)))
11920 (car org-todo-heads))))
11921 ((car (member arg org-todo-keywords-1)))
11922 ((stringp arg)
11923 (user-error "State `%s' not valid in this file" arg))
11924 ((nth (1- (prefix-numeric-value arg))
11925 org-todo-keywords-1))))
11926 ((null member) (or head (car org-todo-keywords-1)))
11927 ((equal this final-done-word) nil) ;-> make empty
11928 ((null tail) nil) ;-> first entry
11929 ((memq interpret '(type priority))
11930 (if (eq this-command last-command)
11931 (car tail)
11932 (if (> (length tail) 0)
11933 (or done-word (car org-done-keywords))
11934 nil)))
11936 (car tail))))
11937 (org-state (or
11938 (run-hook-with-args-until-success
11939 'org-todo-get-default-hook org-state org-last-state)
11940 org-state))
11941 (next (if org-state (concat " " org-state " ") " "))
11942 (change-plist (list :type 'todo-state-change :from this :to org-state
11943 :position startpos))
11944 dolog now-done-p)
11945 (when org-blocker-hook
11946 (let (org-blocked-by-checkboxes block-reason)
11947 (setq org-last-todo-state-is-todo
11948 (not (member this org-done-keywords)))
11949 (unless (save-excursion
11950 (save-match-data
11951 (org-with-wide-buffer
11952 (run-hook-with-args-until-failure
11953 'org-blocker-hook change-plist))))
11954 (setq block-reason (if org-blocked-by-checkboxes
11955 "contained checkboxes"
11956 (format "\"%s\"" org-block-entry-blocking)))
11957 (if (called-interactively-p 'interactive)
11958 (user-error "TODO state change from %s to %s blocked (by %s)"
11959 this org-state block-reason)
11960 ;; Fail silently.
11961 (message "TODO state change from %s to %s blocked (by %s)"
11962 this org-state block-reason)
11963 (throw 'exit nil)))))
11964 (store-match-data match-data)
11965 (replace-match next t t)
11966 (cond ((equal this org-state)
11967 (message "TODO state was already %s" (org-trim next)))
11968 ((not (pos-visible-in-window-p hl-pos))
11969 (message "TODO state changed to %s" (org-trim next))))
11970 (unless head
11971 (setq head (org-get-todo-sequence-head org-state)
11972 ass (assoc head org-todo-kwd-alist)
11973 interpret (nth 1 ass)
11974 done-word (nth 3 ass)
11975 final-done-word (nth 4 ass)))
11976 (when (memq arg '(nextset previousset))
11977 (message "Keyword-Set %d/%d: %s"
11978 (- (length org-todo-sets) -1
11979 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11980 (length org-todo-sets)
11981 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11982 (setq org-last-todo-state-is-todo
11983 (not (member org-state org-done-keywords)))
11984 (setq now-done-p (and (member org-state org-done-keywords)
11985 (not (member this org-done-keywords))))
11986 (and logging (org-local-logging logging))
11987 (when (and (or org-todo-log-states org-log-done)
11988 (not (eq org-inhibit-logging t))
11989 (not (memq arg '(nextset previousset))))
11990 ;; We need to look at recording a time and note.
11991 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11992 (nth 2 (assoc this org-todo-log-states))))
11993 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11994 (setq dolog 'time))
11995 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
11996 (and org-state
11997 (member org-state org-not-done-keywords)
11998 (not (member this org-not-done-keywords))))
11999 ;; This is now a todo state and was not one before
12000 ;; If there was a CLOSED time stamp, get rid of it.
12001 (org-add-planning-info nil nil 'closed))
12002 (when (and now-done-p org-log-done)
12003 ;; It is now done, and it was not done before.
12004 (org-add-planning-info 'closed (org-current-effective-time))
12005 (when (and (not dolog) (eq 'note org-log-done))
12006 (org-add-log-setup 'done org-state this 'note)))
12007 (when (and org-state dolog)
12008 ;; This is a non-nil state, and we need to log it.
12009 (org-add-log-setup 'state org-state this dolog)))
12010 ;; Fixup tag positioning.
12011 (org-todo-trigger-tag-changes org-state)
12012 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12013 (when org-provide-todo-statistics
12014 (org-update-parent-todo-statistics))
12015 (run-hooks 'org-after-todo-state-change-hook)
12016 (when (and arg (not (member org-state org-done-keywords)))
12017 (setq head (org-get-todo-sequence-head org-state)))
12018 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12019 ;; Do we need to trigger a repeat?
12020 (when now-done-p
12021 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12022 ;; This is for the agenda, take a snapshot of the headline.
12023 (save-match-data
12024 (setq org-agenda-headline-snapshot-before-repeat
12025 (org-get-heading))))
12026 (org-auto-repeat-maybe org-state))
12027 ;; Fixup cursor location if close to the keyword.
12028 (when (and (outline-on-heading-p)
12029 (not (bolp))
12030 (save-excursion (beginning-of-line 1)
12031 (looking-at org-todo-line-regexp))
12032 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12033 (goto-char (or (match-end 2) (match-end 1)))
12034 (and (looking-at " ") (just-one-space)))
12035 (when org-trigger-hook
12036 (save-excursion
12037 (run-hook-with-args 'org-trigger-hook change-plist)))
12038 (when commentp (org-toggle-comment))))))))
12040 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12041 "Block turning an entry into a TODO, using the hierarchy.
12042 This checks whether the current task should be blocked from state
12043 changes. Such blocking occurs when:
12045 1. The task has children which are not all in a completed state.
12047 2. A task has a parent with the property :ORDERED:, and there
12048 are siblings prior to the current task with incomplete
12049 status.
12051 3. The parent of the task is blocked because it has siblings that should
12052 be done first, or is child of a block grandparent TODO entry."
12054 (if (not org-enforce-todo-dependencies)
12055 t ; if locally turned off don't block
12056 (catch 'dont-block
12057 ;; If this is not a todo state change, or if this entry is already DONE,
12058 ;; do not block
12059 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12060 (member (plist-get change-plist :from)
12061 (cons 'done org-done-keywords))
12062 (member (plist-get change-plist :to)
12063 (cons 'todo org-not-done-keywords))
12064 (not (plist-get change-plist :to)))
12065 (throw 'dont-block t))
12066 ;; If this task has children, and any are undone, it's blocked
12067 (save-excursion
12068 (org-back-to-heading t)
12069 (let ((this-level (funcall outline-level)))
12070 (outline-next-heading)
12071 (let ((child-level (funcall outline-level)))
12072 (while (and (not (eobp))
12073 (> child-level this-level))
12074 ;; this todo has children, check whether they are all
12075 ;; completed
12076 (when (and (not (org-entry-is-done-p))
12077 (org-entry-is-todo-p))
12078 (setq org-block-entry-blocking (org-get-heading))
12079 (throw 'dont-block nil))
12080 (outline-next-heading)
12081 (setq child-level (funcall outline-level))))))
12082 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12083 ;; any previous siblings are undone, it's blocked
12084 (save-excursion
12085 (org-back-to-heading t)
12086 (let* ((pos (point))
12087 (parent-pos (and (org-up-heading-safe) (point)))
12088 (case-fold-search nil))
12089 (unless parent-pos (throw 'dont-block t)) ; no parent
12090 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12091 (forward-line 1)
12092 (re-search-forward org-not-done-heading-regexp pos t))
12093 (setq org-block-entry-blocking (match-string 0))
12094 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12095 ;; Search further up the hierarchy, to see if an ancestor is blocked
12096 (while t
12097 (goto-char parent-pos)
12098 (unless (looking-at org-not-done-heading-regexp)
12099 (throw 'dont-block t)) ; do not block, parent is not a TODO
12100 (setq pos (point))
12101 (setq parent-pos (and (org-up-heading-safe) (point)))
12102 (unless parent-pos (throw 'dont-block t)) ; no parent
12103 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12104 (forward-line 1)
12105 (re-search-forward org-not-done-heading-regexp pos t)
12106 (setq org-block-entry-blocking (org-get-heading)))
12107 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12109 (defcustom org-track-ordered-property-with-tag nil
12110 "Should the ORDERED property also be shown as a tag?
12111 The ORDERED property decides if an entry should require subtasks to be
12112 completed in sequence. Since a property is not very visible, setting
12113 this option means that toggling the ORDERED property with the command
12114 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12115 not relevant for the behavior, but it makes things more visible.
12117 Note that toggling the tag with tags commands will not change the property
12118 and therefore not influence behavior!
12120 This can be t, meaning the tag ORDERED should be used, It can also be a
12121 string to select a different tag for this task."
12122 :group 'org-todo
12123 :type '(choice
12124 (const :tag "No tracking" nil)
12125 (const :tag "Track with ORDERED tag" t)
12126 (string :tag "Use other tag")))
12128 (defun org-toggle-ordered-property ()
12129 "Toggle the ORDERED property of the current entry.
12130 For better visibility, you can track the value of this property with a tag.
12131 See variable `org-track-ordered-property-with-tag'."
12132 (interactive)
12133 (let* ((t1 org-track-ordered-property-with-tag)
12134 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12135 (save-excursion
12136 (org-back-to-heading)
12137 (if (org-entry-get nil "ORDERED")
12138 (progn
12139 (org-delete-property "ORDERED")
12140 (and tag (org-toggle-tag tag 'off))
12141 (message "Subtasks can be completed in arbitrary order"))
12142 (org-entry-put nil "ORDERED" "t")
12143 (and tag (org-toggle-tag tag 'on))
12144 (message "Subtasks must be completed in sequence")))))
12146 (defun org-block-todo-from-checkboxes (change-plist)
12147 "Block turning an entry into a TODO, using checkboxes.
12148 This checks whether the current task should be blocked from state
12149 changes because there are unchecked boxes in this entry."
12150 (if (not org-enforce-todo-checkbox-dependencies)
12151 t ; if locally turned off don't block
12152 (catch 'dont-block
12153 ;; If this is not a todo state change, or if this entry is already DONE,
12154 ;; do not block
12155 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12156 (member (plist-get change-plist :from)
12157 (cons 'done org-done-keywords))
12158 (member (plist-get change-plist :to)
12159 (cons 'todo org-not-done-keywords))
12160 (not (plist-get change-plist :to)))
12161 (throw 'dont-block t))
12162 ;; If this task has checkboxes that are not checked, it's blocked
12163 (save-excursion
12164 (org-back-to-heading t)
12165 (let ((beg (point)) end)
12166 (outline-next-heading)
12167 (setq end (point))
12168 (goto-char beg)
12169 (when (org-list-search-forward
12170 (concat (org-item-beginning-re)
12171 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12172 "\\[[- ]\\]")
12173 end t)
12174 (when (boundp 'org-blocked-by-checkboxes)
12175 (setq org-blocked-by-checkboxes t))
12176 (throw 'dont-block nil))))
12177 t))) ; do not block
12179 (defun org-entry-blocked-p ()
12180 "Non-nil if entry at point is blocked."
12181 (and (not (org-entry-get nil "NOBLOCKING"))
12182 (member (org-entry-get nil "TODO") org-not-done-keywords)
12183 (not (run-hook-with-args-until-failure
12184 'org-blocker-hook
12185 (list :type 'todo-state-change
12186 :position (point)
12187 :from 'todo
12188 :to 'done)))))
12190 (defun org-update-statistics-cookies (all)
12191 "Update the statistics cookie, either from TODO or from checkboxes.
12192 This should be called with the cursor in a line with a statistics
12193 cookie. When called with a \\[universal-argument] prefix, update
12194 all statistics cookies in the buffer."
12195 (interactive "P")
12196 (if all
12197 (progn
12198 (org-update-checkbox-count 'all)
12199 (org-map-entries 'org-update-parent-todo-statistics))
12200 (if (not (org-at-heading-p))
12201 (org-update-checkbox-count)
12202 (let ((pos (point-marker))
12203 end l1 l2)
12204 (ignore-errors (org-back-to-heading t))
12205 (if (not (org-at-heading-p))
12206 (org-update-checkbox-count)
12207 (setq l1 (org-outline-level))
12208 (setq end (save-excursion
12209 (outline-next-heading)
12210 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12211 (point)))
12212 (if (and (save-excursion
12213 (re-search-forward
12214 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12215 (not (save-excursion (re-search-forward
12216 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12217 (org-update-checkbox-count)
12218 (if (and l2 (> l2 l1))
12219 (progn
12220 (goto-char end)
12221 (org-update-parent-todo-statistics))
12222 (goto-char pos)
12223 (beginning-of-line 1)
12224 (while (re-search-forward
12225 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12226 (point-at-eol) t)
12227 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12228 (goto-char pos)
12229 (move-marker pos nil)))))
12231 (defvar org-entry-property-inherited-from) ;; defined below
12232 (defun org-update-parent-todo-statistics ()
12233 "Update any statistics cookie in the parent of the current headline.
12234 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12235 the entire subtree and this will travel up the hierarchy and update
12236 statistics everywhere."
12237 (let* ((prop (save-excursion (org-up-heading-safe)
12238 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12239 (recursive (or (not org-hierarchical-todo-statistics)
12240 (and prop (string-match "\\<recursive\\>" prop))))
12241 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12243 (first t)
12244 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12245 level ltoggle l1 new ndel
12246 (cnt-all 0) (cnt-done 0) is-percent kwd
12247 checkbox-beg cookie-present)
12248 (catch 'exit
12249 (save-excursion
12250 (beginning-of-line 1)
12251 (setq ltoggle (funcall outline-level))
12252 ;; Three situations are to consider:
12254 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12255 ;; to the top-level ancestor on the headline;
12257 ;; 2. If parent has "recursive" property, repeat up to the
12258 ;; headline setting that property, taking inheritance into
12259 ;; account;
12261 ;; 3. Else, move up to direct parent and proceed only once.
12262 (while (and (setq level (org-up-heading-safe))
12263 (or recursive first)
12264 (>= (point) lim))
12265 (setq first nil cookie-present nil)
12266 (unless (and level
12267 (not (string-match
12268 "\\<checkbox\\>"
12269 (downcase (or (org-entry-get nil "COOKIE_DATA")
12270 "")))))
12271 (throw 'exit nil))
12272 (while (re-search-forward box-re (point-at-eol) t)
12273 (setq cnt-all 0 cnt-done 0 cookie-present t)
12274 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12275 (save-match-data
12276 (unless (outline-next-heading) (throw 'exit nil))
12277 (while (and (looking-at org-complex-heading-regexp)
12278 (> (setq l1 (length (match-string 1))) level))
12279 (setq kwd (and (or recursive (= l1 ltoggle))
12280 (match-string 2)))
12281 (if (or (eq org-provide-todo-statistics 'all-headlines)
12282 (and (eq org-provide-todo-statistics t)
12283 (or (member kwd org-done-keywords)))
12284 (and (listp org-provide-todo-statistics)
12285 (stringp (car org-provide-todo-statistics))
12286 (or (member kwd org-provide-todo-statistics)
12287 (member kwd org-done-keywords)))
12288 (and (listp org-provide-todo-statistics)
12289 (listp (car org-provide-todo-statistics))
12290 (or (member kwd (car org-provide-todo-statistics))
12291 (and (member kwd org-done-keywords)
12292 (member kwd (cadr org-provide-todo-statistics))))))
12293 (setq cnt-all (1+ cnt-all))
12294 (and (eq org-provide-todo-statistics t)
12296 (setq cnt-all (1+ cnt-all))))
12297 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12298 (member kwd org-done-keywords))
12299 (and (listp org-provide-todo-statistics)
12300 (listp (car org-provide-todo-statistics))
12301 (member kwd org-done-keywords)
12302 (member kwd (cadr org-provide-todo-statistics)))
12303 (and (listp org-provide-todo-statistics)
12304 (stringp (car org-provide-todo-statistics))
12305 (member kwd org-done-keywords)))
12306 (setq cnt-done (1+ cnt-done)))
12307 (outline-next-heading)))
12308 (setq new
12309 (if is-percent
12310 (format "[%d%%]" (floor (* 100.0 cnt-done)
12311 (max 1 cnt-all)))
12312 (format "[%d/%d]" cnt-done cnt-all))
12313 ndel (- (match-end 0) checkbox-beg))
12314 (goto-char checkbox-beg)
12315 (insert new)
12316 (delete-region (point) (+ (point) ndel))
12317 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12318 (when cookie-present
12319 (run-hook-with-args 'org-after-todo-statistics-hook
12320 cnt-done (- cnt-all cnt-done))))))
12321 (run-hooks 'org-todo-statistics-hook)))
12323 (defvar org-after-todo-statistics-hook nil
12324 "Hook that is called after a TODO statistics cookie has been updated.
12325 Each function is called with two arguments: the number of not-done entries
12326 and the number of done entries.
12328 For example, the following function, when added to this hook, will switch
12329 an entry to DONE when all children are done, and back to TODO when new
12330 entries are set to a TODO status. Note that this hook is only called
12331 when there is a statistics cookie in the headline!
12333 (defun org-summary-todo (n-done n-not-done)
12334 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12335 (let (org-log-done org-log-states) ; turn off logging
12336 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12339 (defvar org-todo-statistics-hook nil
12340 "Hook that is run whenever Org thinks TODO statistics should be updated.
12341 This hook runs even if there is no statistics cookie present, in which case
12342 `org-after-todo-statistics-hook' would not run.")
12344 (defun org-todo-trigger-tag-changes (state)
12345 "Apply the changes defined in `org-todo-state-tags-triggers'."
12346 (let ((l org-todo-state-tags-triggers)
12347 changes)
12348 (when (or (not state) (equal state ""))
12349 (setq changes (append changes (cdr (assoc "" l)))))
12350 (when (and (stringp state) (> (length state) 0))
12351 (setq changes (append changes (cdr (assoc state l)))))
12352 (when (member state org-not-done-keywords)
12353 (setq changes (append changes (cdr (assq 'todo l)))))
12354 (when (member state org-done-keywords)
12355 (setq changes (append changes (cdr (assq 'done l)))))
12356 (dolist (c changes)
12357 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12359 (defun org-local-logging (value)
12360 "Get logging settings from a property VALUE."
12361 ;; Directly set the variables, they are already local.
12362 (setq org-log-done nil
12363 org-log-repeat nil
12364 org-todo-log-states nil)
12365 (dolist (w (split-string value))
12366 (let (a)
12367 (cond
12368 ((setq a (assoc w org-startup-options))
12369 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12370 (set (nth 1 a) (nth 2 a))))
12371 ((setq a (org-extract-log-state-settings w))
12372 (and (member (car a) org-todo-keywords-1)
12373 (push a org-todo-log-states)))))))
12375 (defun org-get-todo-sequence-head (kwd)
12376 "Return the head of the TODO sequence to which KWD belongs.
12377 If KWD is not set, check if there is a text property remembering the
12378 right sequence."
12379 (let (p)
12380 (cond
12381 ((not kwd)
12382 (or (get-text-property (point-at-bol) 'org-todo-head)
12383 (progn
12384 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12385 nil (point-at-eol)))
12386 (get-text-property p 'org-todo-head))))
12387 ((not (member kwd org-todo-keywords-1))
12388 (car org-todo-keywords-1))
12389 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12391 (defun org-fast-todo-selection ()
12392 "Fast TODO keyword selection with single keys.
12393 Returns the new TODO keyword, or nil if no state change should occur."
12394 (let* ((fulltable org-todo-key-alist)
12395 (done-keywords org-done-keywords) ;; needed for the faces.
12396 (maxlen (apply 'max (mapcar
12397 (lambda (x)
12398 (if (stringp (car x)) (string-width (car x)) 0))
12399 fulltable)))
12400 (expert nil)
12401 (fwidth (+ maxlen 3 1 3))
12402 (ncol (/ (- (window-width) 4) fwidth))
12403 tg cnt e c tbl
12404 groups ingroup)
12405 (save-excursion
12406 (save-window-excursion
12407 (if expert
12408 (set-buffer (get-buffer-create " *Org todo*"))
12409 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12410 (erase-buffer)
12411 (setq-local org-done-keywords done-keywords)
12412 (setq tbl fulltable cnt 0)
12413 (while (setq e (pop tbl))
12414 (cond
12415 ((equal e '(:startgroup))
12416 (push '() groups) (setq ingroup t)
12417 (unless (= cnt 0)
12418 (setq cnt 0)
12419 (insert "\n"))
12420 (insert "{ "))
12421 ((equal e '(:endgroup))
12422 (setq ingroup nil cnt 0)
12423 (insert "}\n"))
12424 ((equal e '(:newline))
12425 (unless (= cnt 0)
12426 (setq cnt 0)
12427 (insert "\n")
12428 (setq e (car tbl))
12429 (while (equal (car tbl) '(:newline))
12430 (insert "\n")
12431 (setq tbl (cdr tbl)))))
12433 (setq tg (car e) c (cdr e))
12434 (when ingroup (push tg (car groups)))
12435 (setq tg (org-add-props tg nil 'face
12436 (org-get-todo-face tg)))
12437 (when (and (= cnt 0) (not ingroup)) (insert " "))
12438 (insert "[" c "] " tg (make-string
12439 (- fwidth 4 (length tg)) ?\ ))
12440 (when (= (setq cnt (1+ cnt)) ncol)
12441 (insert "\n")
12442 (when ingroup (insert " "))
12443 (setq cnt 0)))))
12444 (insert "\n")
12445 (goto-char (point-min))
12446 (unless expert (org-fit-window-to-buffer))
12447 (message "[a-z..]:Set [SPC]:clear")
12448 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12449 (cond
12450 ((or (= c ?\C-g)
12451 (and (= c ?q) (not (rassoc c fulltable))))
12452 (setq quit-flag t))
12453 ((= c ?\ ) nil)
12454 ((setq e (rassoc c fulltable) tg (car e))
12456 (t (setq quit-flag t)))))))
12458 (defun org-entry-is-todo-p ()
12459 (member (org-get-todo-state) org-not-done-keywords))
12461 (defun org-entry-is-done-p ()
12462 (member (org-get-todo-state) org-done-keywords))
12464 (defun org-get-todo-state ()
12465 "Return the TODO keyword of the current subtree."
12466 (save-excursion
12467 (org-back-to-heading t)
12468 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12469 (match-end 2)
12470 (match-string 2))))
12472 (defun org-at-date-range-p (&optional inactive-ok)
12473 "Non-nil if point is inside a date range.
12475 When optional argument INACTIVE-OK is non-nil, also consider
12476 inactive time ranges.
12478 When this function returns a non-nil value, match data is set
12479 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12480 on INACTIVE-OK."
12481 (interactive)
12482 (save-excursion
12483 (catch 'exit
12484 (let ((pos (point)))
12485 (skip-chars-backward "^[<\r\n")
12486 (skip-chars-backward "<[")
12487 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12488 (>= (match-end 0) pos)
12489 (throw 'exit t))
12490 (skip-chars-backward "^<[\r\n")
12491 (skip-chars-backward "<[")
12492 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12493 (>= (match-end 0) pos)
12494 (throw 'exit t)))
12495 nil)))
12497 (defun org-get-repeat (&optional timestamp)
12498 "Check if there is a time-stamp with repeater in this entry.
12500 Return the repeater, as a string, or nil. Also return nil when
12501 this function is called before first heading.
12503 When optional argument TIMESTAMP is a string, extract the
12504 repeater from there instead."
12505 (save-match-data
12506 (cond (timestamp
12507 (and (string-match org-repeat-re timestamp)
12508 (match-string-no-properties 1 timestamp)))
12509 ((org-before-first-heading-p) nil)
12511 (save-excursion
12512 (org-back-to-heading t)
12513 (let ((end (org-entry-end-position)))
12514 (catch :repeat
12515 (while (re-search-forward org-repeat-re end t)
12516 (when (save-match-data (org-at-timestamp-p 'agenda))
12517 (throw :repeat (match-string-no-properties 1)))))))))))
12519 (defvar org-last-changed-timestamp)
12520 (defvar org-last-inserted-timestamp)
12521 (defvar org-log-post-message)
12522 (defvar org-log-note-purpose)
12523 (defvar org-log-note-how nil)
12524 (defvar org-log-note-extra)
12525 (defun org-auto-repeat-maybe (done-word)
12526 "Check if the current headline contains a repeated time-stamp.
12528 If yes, set TODO state back to what it was and change the base date
12529 of repeating deadline/scheduled time stamps to new date.
12531 This function is run automatically after each state change to a DONE state."
12532 (let* ((repeat (org-get-repeat))
12533 (aa (assoc org-last-state org-todo-kwd-alist))
12534 (interpret (nth 1 aa))
12535 (head (nth 2 aa))
12536 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12537 (msg "Entry repeats: ")
12538 (org-log-done nil)
12539 (org-todo-log-states nil)
12540 (end (copy-marker (org-entry-end-position))))
12541 (unwind-protect
12542 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12543 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12544 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12545 (and (stringp org-todo-repeat-to-state)
12546 org-todo-repeat-to-state)
12547 (and org-todo-repeat-to-state org-last-state))))
12548 (org-todo (cond
12549 ((and to-state (member to-state org-todo-keywords-1))
12550 to-state)
12551 ((eq interpret 'type) org-last-state)
12552 (head)
12553 (t 'none))))
12554 (org-back-to-heading t)
12555 (org-add-planning-info nil nil 'closed)
12556 ;; When `org-log-repeat' is non-nil or entry contains
12557 ;; a clock, set LAST_REPEAT property.
12558 (when (or org-log-repeat
12559 (catch :clock
12560 (save-excursion
12561 (while (re-search-forward org-clock-line-re end t)
12562 (when (org-at-clock-log-p) (throw :clock t))))))
12563 (org-entry-put nil "LAST_REPEAT" (format-time-string
12564 (org-time-stamp-format t t)
12565 (current-time))))
12566 (when org-log-repeat
12567 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12568 (memq 'org-add-log-note post-command-hook))
12569 ;; We are already setup for some record.
12570 (when (eq org-log-repeat 'note)
12571 ;; Make sure we take a note, not only a time stamp.
12572 (setq org-log-note-how 'note))
12573 ;; Set up for taking a record.
12574 (org-add-log-setup 'state
12575 (or done-word (car org-done-keywords))
12576 org-last-state
12577 org-log-repeat)))
12578 (let ((planning-re (regexp-opt
12579 (list org-scheduled-string org-deadline-string))))
12580 (while (re-search-forward org-ts-regexp end t)
12581 (let* ((ts (match-string 0))
12582 (planning? (org-at-planning-p))
12583 (type (if (not planning?) "Plain:"
12584 (save-excursion
12585 (re-search-backward
12586 planning-re (line-beginning-position) t)
12587 (match-string 0)))))
12588 (cond
12589 ;; Ignore fake time-stamps (e.g., within comments).
12590 ((not (org-at-timestamp-p 'agenda)))
12591 ;; Time-stamps without a repeater are usually
12592 ;; skipped. However, a SCHEDULED time-stamp without
12593 ;; one is removed, as they are no longer relevant.
12594 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12595 ts))
12596 (when (equal type org-scheduled-string)
12597 (org-remove-timestamp-with-keyword type)))
12599 (let ((n (string-to-number (match-string 2 ts)))
12600 (what (match-string 3 ts)))
12601 (when (equal what "w") (setq n (* n 7) what "d"))
12602 (when (and (equal what "h")
12603 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12604 ts)))
12605 (user-error
12606 "Cannot repeat in Repeat in %d hour(s) because no hour \
12607 has been set"
12609 ;; Preparation, see if we need to modify the start
12610 ;; date for the change.
12611 (when (match-end 1)
12612 (let ((time (save-match-data
12613 (org-time-string-to-time ts))))
12614 (cond
12615 ((equal (match-string 1 ts) ".")
12616 ;; Shift starting date to today
12617 (org-timestamp-change
12618 (- (org-today) (time-to-days time))
12619 'day))
12620 ((equal (match-string 1 ts) "+")
12621 (let ((nshiftmax 10)
12622 (nshift 0))
12623 (while (or (= nshift 0)
12624 (not (time-less-p (current-time) time)))
12625 (when (= (cl-incf nshift) nshiftmax)
12626 (or (y-or-n-p
12627 (format "%d repeater intervals were not \
12628 enough to shift date past today. Continue? "
12629 nshift))
12630 (user-error "Abort")))
12631 (org-timestamp-change n (cdr (assoc what whata)))
12632 (org-in-regexp org-ts-regexp3)
12633 (setq ts (match-string 1))
12634 (setq time
12635 (save-match-data
12636 (org-time-string-to-time ts)))))
12637 (org-timestamp-change (- n) (cdr (assoc what whata)))
12638 ;; Rematch, so that we have everything in place
12639 ;; for the real shift.
12640 (org-in-regexp org-ts-regexp3)
12641 (setq ts (match-string 1))
12642 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12643 ts)))))
12644 (save-excursion
12645 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12646 (setq msg
12647 (concat
12648 msg type " " org-last-changed-timestamp " "))))))))
12649 (setq org-log-post-message msg)
12650 (message "%s" msg))
12651 (set-marker end nil))))
12653 (defun org-show-todo-tree (arg)
12654 "Make a compact tree which shows all headlines marked with TODO.
12655 The tree will show the lines where the regexp matches, and all higher
12656 headlines above the match.
12657 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12658 With a numeric prefix N, construct a sparse tree for the Nth element
12659 of `org-todo-keywords-1'."
12660 (interactive "P")
12661 (let ((case-fold-search nil)
12662 (kwd-re
12663 (cond ((null arg) org-not-done-regexp)
12664 ((equal arg '(4))
12665 (let ((kwd
12666 (completing-read "Keyword (or KWD1|KWD2|...): "
12667 (mapcar #'list org-todo-keywords-1))))
12668 (concat "\\("
12669 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12670 "\\)\\>")))
12671 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12672 (regexp-quote (nth (1- (prefix-numeric-value arg))
12673 org-todo-keywords-1)))
12674 (t (user-error "Invalid prefix argument: %s" arg)))))
12675 (message "%d TODO entries found"
12676 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12678 (defun org--deadline-or-schedule (arg type time)
12679 "Insert DEADLINE or SCHEDULE information in current entry.
12680 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12681 `org-schedule' for information about ARG and TIME arguments."
12682 (let* ((deadline? (eq type 'deadline))
12683 (keyword (if deadline? org-deadline-string org-scheduled-string))
12684 (log (if deadline? org-log-redeadline org-log-reschedule))
12685 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12686 (old-date-time (and old-date (org-time-string-to-time old-date)))
12687 ;; Save repeater cookie from either TIME or current scheduled
12688 ;; time stamp. We are going to insert it back at the end of
12689 ;; the process.
12690 (repeater (or (and (org-string-nw-p time)
12691 ;; We use `org-repeat-re' because we need
12692 ;; to tell the difference between a real
12693 ;; repeater and a time delta, e.g. "+2d".
12694 (string-match org-repeat-re time)
12695 (match-string 1 time))
12696 (and (org-string-nw-p old-date)
12697 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12698 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12699 old-date)
12700 (match-string 1 old-date)))))
12701 (pcase arg
12702 (`(4)
12703 (when (and old-date log)
12704 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12705 nil old-date log))
12706 (org-remove-timestamp-with-keyword keyword)
12707 (message (if deadline? "Item no longer has a deadline."
12708 "Item is no longer scheduled.")))
12709 (`(16)
12710 (save-excursion
12711 (org-back-to-heading t)
12712 (let ((regexp (if deadline? org-deadline-time-regexp
12713 org-scheduled-time-regexp)))
12714 (if (not (re-search-forward regexp (line-end-position 2) t))
12715 (user-error (if deadline? "No deadline information to update"
12716 "No scheduled information to update"))
12717 (let* ((rpl0 (match-string 1))
12718 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12719 (msg (if deadline? "Warn starting from" "Delay until")))
12720 (replace-match
12721 (concat keyword
12722 " <" rpl
12723 (format " -%dd"
12724 (abs (- (time-to-days
12725 (save-match-data
12726 (org-read-date
12727 nil t nil msg old-date-time)))
12728 (time-to-days old-date-time))))
12729 ">") t t))))))
12731 (org-add-planning-info type time 'closed)
12732 (when (and old-date
12734 (not (equal old-date org-last-inserted-timestamp)))
12735 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12736 org-last-inserted-timestamp
12737 old-date
12738 log))
12739 (when repeater
12740 (save-excursion
12741 (org-back-to-heading t)
12742 (when (re-search-forward
12743 (concat keyword " " org-last-inserted-timestamp)
12744 (line-end-position 2)
12746 (goto-char (1- (match-end 0)))
12747 (insert " " repeater)
12748 (setq org-last-inserted-timestamp
12749 (concat (substring org-last-inserted-timestamp 0 -1)
12750 " " repeater
12751 (substring org-last-inserted-timestamp -1))))))
12752 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12753 org-last-inserted-timestamp)))))
12755 (defun org-deadline (arg &optional time)
12756 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12757 With one universal prefix argument, remove any deadline from the item.
12758 With two universal prefix arguments, prompt for a warning delay.
12759 With argument TIME, set the deadline at the corresponding date. TIME
12760 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12761 (interactive "P")
12762 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12763 (org-map-entries
12764 (lambda () (org--deadline-or-schedule arg 'deadline time))
12766 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12767 'region-start-level
12768 'region)
12769 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12770 (org--deadline-or-schedule arg 'deadline time)))
12772 (defun org-schedule (arg &optional time)
12773 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12774 With one universal prefix argument, remove any scheduling date from the item.
12775 With two universal prefix arguments, prompt for a delay cookie.
12776 With argument TIME, scheduled at the corresponding date. TIME can
12777 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12778 (interactive "P")
12779 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12780 (org-map-entries
12781 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12783 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12784 'region-start-level
12785 'region)
12786 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12787 (org--deadline-or-schedule arg 'scheduled time)))
12789 (defun org-get-scheduled-time (pom &optional inherit)
12790 "Get the scheduled time as a time tuple, of a format suitable
12791 for calling org-schedule with, or if there is no scheduling,
12792 returns nil."
12793 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12794 (when time
12795 (apply 'encode-time (org-parse-time-string time)))))
12797 (defun org-get-deadline-time (pom &optional inherit)
12798 "Get the deadline as a time tuple, of a format suitable for
12799 calling org-deadline with, or if there is no scheduling, returns
12800 nil."
12801 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12802 (when time
12803 (apply 'encode-time (org-parse-time-string time)))))
12805 (defun org-remove-timestamp-with-keyword (keyword)
12806 "Remove all time stamps with KEYWORD in the current entry."
12807 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12808 beg)
12809 (save-excursion
12810 (org-back-to-heading t)
12811 (setq beg (point))
12812 (outline-next-heading)
12813 (while (re-search-backward re beg t)
12814 (replace-match "")
12815 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12816 (equal (char-before) ?\ ))
12817 (backward-delete-char 1)
12818 (when (string-match "^[ \t]*$" (buffer-substring
12819 (point-at-bol) (point-at-eol)))
12820 (delete-region (point-at-bol)
12821 (min (point-max) (1+ (point-at-eol))))))))))
12823 (defvar org-time-was-given) ; dynamically scoped parameter
12824 (defvar org-end-time-was-given) ; dynamically scoped parameter
12826 (defun org-at-planning-p ()
12827 "Non-nil when point is on a planning info line."
12828 ;; This is as accurate and faster than `org-element-at-point' since
12829 ;; planning info location is fixed in the section.
12830 (org-with-wide-buffer
12831 (beginning-of-line)
12832 (and (looking-at-p org-planning-line-re)
12833 (eq (point)
12834 (ignore-errors
12835 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12836 (org-back-to-heading t)
12837 (org-with-limited-levels (org-back-to-heading t)))
12838 (line-beginning-position 2))))))
12840 (defun org-add-planning-info (what &optional time &rest remove)
12841 "Insert new timestamp with keyword in the planning line.
12842 WHAT indicates what kind of time stamp to add. It is a symbol
12843 among `closed', `deadline', `scheduled' and nil. TIME indicates
12844 the time to use. If none is given, the user is prompted for
12845 a date. REMOVE indicates what kind of entries to remove. An old
12846 WHAT entry will also be removed."
12847 (let (org-time-was-given org-end-time-was-given default-time default-input)
12848 (catch 'exit
12849 (when (and (memq what '(scheduled deadline))
12850 (or (not time)
12851 (and (stringp time)
12852 (string-match "^[-+]+[0-9]" time))))
12853 ;; Try to get a default date/time from existing timestamp
12854 (save-excursion
12855 (org-back-to-heading t)
12856 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12857 (when (re-search-forward (if (eq what 'scheduled)
12858 org-scheduled-time-regexp
12859 org-deadline-time-regexp)
12860 end t)
12861 (setq ts (match-string 1)
12862 default-time (apply 'encode-time (org-parse-time-string ts))
12863 default-input (and ts (org-get-compact-tod ts)))))))
12864 (when what
12865 (setq time
12866 (if (stringp time)
12867 ;; This is a string (relative or absolute), set
12868 ;; proper date.
12869 (apply #'encode-time
12870 (org-read-date-analyze
12871 time default-time (decode-time default-time)))
12872 ;; If necessary, get the time from the user
12873 (or time (org-read-date nil 'to-time nil nil
12874 default-time default-input)))))
12876 (org-with-wide-buffer
12877 (org-back-to-heading t)
12878 (forward-line)
12879 (unless (bolp) (insert "\n"))
12880 (cond ((looking-at-p org-planning-line-re)
12881 ;; Move to current indentation.
12882 (skip-chars-forward " \t")
12883 ;; Check if we have to remove something.
12884 (dolist (type (if what (cons what remove) remove))
12885 (save-excursion
12886 (when (re-search-forward
12887 (cl-case type
12888 (closed org-closed-time-regexp)
12889 (deadline org-deadline-time-regexp)
12890 (scheduled org-scheduled-time-regexp)
12891 (otherwise
12892 (error "Invalid planning type: %s" type)))
12893 (line-end-position) t)
12894 ;; Delete until next keyword or end of line.
12895 (delete-region
12896 (match-beginning 0)
12897 (if (re-search-forward org-keyword-time-not-clock-regexp
12898 (line-end-position)
12900 (match-beginning 0)
12901 (line-end-position))))))
12902 ;; If there is nothing more to add and no more keyword
12903 ;; is left, remove the line completely.
12904 (if (and (looking-at-p "[ \t]*$") (not what))
12905 (delete-region (line-beginning-position)
12906 (line-beginning-position 2))
12907 ;; If we removed last keyword, do not leave trailing
12908 ;; white space at the end of line.
12909 (let ((p (point)))
12910 (save-excursion
12911 (end-of-line)
12912 (unless (= (skip-chars-backward " \t" p) 0)
12913 (delete-region (point) (line-end-position)))))))
12914 ((not what) (throw 'exit nil)) ; Nothing to do.
12915 (t (insert-before-markers "\n")
12916 (backward-char 1)
12917 (when org-adapt-indentation
12918 (indent-to-column (1+ (org-outline-level))))))
12919 (when what
12920 ;; Insert planning keyword.
12921 (insert (cl-case what
12922 (closed org-closed-string)
12923 (deadline org-deadline-string)
12924 (scheduled org-scheduled-string)
12925 (otherwise (error "Invalid planning type: %s" what)))
12926 " ")
12927 ;; Insert associated timestamp.
12928 (let ((ts (org-insert-time-stamp
12929 time
12930 (or org-time-was-given
12931 (and (eq what 'closed) org-log-done-with-time))
12932 (eq what 'closed)
12933 nil nil (list org-end-time-was-given))))
12934 (unless (eolp) (insert " "))
12935 ts))))))
12937 (defvar org-log-note-marker (make-marker)
12938 "Marker pointing at the entry where the note is to be inserted.")
12939 (defvar org-log-note-purpose nil)
12940 (defvar org-log-note-state nil)
12941 (defvar org-log-note-previous-state nil)
12942 (defvar org-log-note-extra nil)
12943 (defvar org-log-note-window-configuration nil)
12944 (defvar org-log-note-return-to (make-marker))
12945 (defvar org-log-note-effective-time nil
12946 "Remembered current time so that dynamically scoped
12947 `org-extend-today-until' affects timestamps in state change log")
12949 (defvar org-log-post-message nil
12950 "Message to be displayed after a log note has been stored.
12951 The auto-repeater uses this.")
12953 (defun org-add-note ()
12954 "Add a note to the current entry.
12955 This is done in the same way as adding a state change note."
12956 (interactive)
12957 (org-add-log-setup 'note))
12959 (defun org-log-beginning (&optional create)
12960 "Return expected start of log notes in current entry.
12961 When optional argument CREATE is non-nil, the function creates
12962 a drawer to store notes, if necessary. Returned position ignores
12963 narrowing."
12964 (org-with-wide-buffer
12965 (let ((drawer (org-log-into-drawer)))
12966 (cond
12967 (drawer
12968 (org-end-of-meta-data)
12969 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
12970 (end (if (org-at-heading-p) (point)
12971 (save-excursion (outline-next-heading) (point))))
12972 (case-fold-search t))
12973 (catch 'exit
12974 ;; Try to find existing drawer.
12975 (while (re-search-forward regexp end t)
12976 (let ((element (org-element-at-point)))
12977 (when (eq (org-element-type element) 'drawer)
12978 (let ((cend (org-element-property :contents-end element)))
12979 (when (and (not org-log-states-order-reversed) cend)
12980 (goto-char cend)))
12981 (throw 'exit nil))))
12982 ;; No drawer found. Create one, if permitted.
12983 (when create
12984 (unless (bolp) (insert "\n"))
12985 (let ((beg (point)))
12986 (insert ":" drawer ":\n:END:\n")
12987 (org-indent-region beg (point))
12988 (org-flag-region
12989 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
12990 (end-of-line -1)))))
12992 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
12993 (skip-chars-forward " \t\n")
12994 (beginning-of-line)
12995 (unless org-log-states-order-reversed
12996 (org-skip-over-state-notes)
12997 (skip-chars-backward " \t\n")
12998 (forward-line)))))
12999 (if (bolp) (point) (line-beginning-position 2))))
13001 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13002 "Set up the post command hook to take a note.
13003 If this is about to TODO state change, the new state is expected in STATE.
13004 HOW is an indicator what kind of note should be created.
13005 EXTRA is additional text that will be inserted into the notes buffer."
13006 (move-marker org-log-note-marker (point))
13007 (setq org-log-note-purpose purpose
13008 org-log-note-state state
13009 org-log-note-previous-state prev-state
13010 org-log-note-how how
13011 org-log-note-extra extra
13012 org-log-note-effective-time (org-current-effective-time))
13013 (add-hook 'post-command-hook 'org-add-log-note 'append))
13015 (defun org-skip-over-state-notes ()
13016 "Skip past the list of State notes in an entry."
13017 (when (ignore-errors (goto-char (org-in-item-p)))
13018 (let* ((struct (org-list-struct))
13019 (prevs (org-list-prevs-alist struct))
13020 (regexp
13021 (concat "[ \t]*- +"
13022 (replace-regexp-in-string
13023 " +" " +"
13024 (org-replace-escapes
13025 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13026 `(("%d" . ,org-ts-regexp-inactive)
13027 ("%D" . ,org-ts-regexp)
13028 ("%s" . "\"\\S-+\"")
13029 ("%S" . "\"\\S-+\"")
13030 ("%t" . ,org-ts-regexp-inactive)
13031 ("%T" . ,org-ts-regexp)
13032 ("%u" . ".*?")
13033 ("%U" . ".*?")))))))
13034 (while (looking-at-p regexp)
13035 (goto-char (or (org-list-get-next-item (point) struct prevs)
13036 (org-list-get-item-end (point) struct)))))))
13038 (defun org-add-log-note (&optional _purpose)
13039 "Pop up a window for taking a note, and add this note later."
13040 (remove-hook 'post-command-hook 'org-add-log-note)
13041 (setq org-log-note-window-configuration (current-window-configuration))
13042 (delete-other-windows)
13043 (move-marker org-log-note-return-to (point))
13044 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13045 (goto-char org-log-note-marker)
13046 (org-switch-to-buffer-other-window "*Org Note*")
13047 (erase-buffer)
13048 (if (memq org-log-note-how '(time state))
13049 (org-store-log-note)
13050 (let ((org-inhibit-startup t)) (org-mode))
13051 (insert (format "# Insert note for %s.
13052 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13053 (cond
13054 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13055 ((eq org-log-note-purpose 'done) "closed todo item")
13056 ((eq org-log-note-purpose 'state)
13057 (format "state change from \"%s\" to \"%s\""
13058 (or org-log-note-previous-state "")
13059 (or org-log-note-state "")))
13060 ((eq org-log-note-purpose 'reschedule)
13061 "rescheduling")
13062 ((eq org-log-note-purpose 'delschedule)
13063 "no longer scheduled")
13064 ((eq org-log-note-purpose 'redeadline)
13065 "changing deadline")
13066 ((eq org-log-note-purpose 'deldeadline)
13067 "removing deadline")
13068 ((eq org-log-note-purpose 'refile)
13069 "refiling")
13070 ((eq org-log-note-purpose 'note)
13071 "this entry")
13072 (t (error "This should not happen")))))
13073 (when org-log-note-extra (insert org-log-note-extra))
13074 (setq-local org-finish-function 'org-store-log-note)
13075 (run-hooks 'org-log-buffer-setup-hook)))
13077 (defvar org-note-abort nil) ; dynamically scoped
13078 (defun org-store-log-note ()
13079 "Finish taking a log note, and insert it to where it belongs."
13080 (let ((txt (prog1 (buffer-string)
13081 (kill-buffer)))
13082 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13083 lines)
13084 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13085 (setq txt (replace-match "" t t txt)))
13086 (when (string-match "\\s-+\\'" txt)
13087 (setq txt (replace-match "" t t txt)))
13088 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13089 (when (org-string-nw-p note)
13090 (setq note
13091 (org-replace-escapes
13092 note
13093 (list (cons "%u" (user-login-name))
13094 (cons "%U" user-full-name)
13095 (cons "%t" (format-time-string
13096 (org-time-stamp-format 'long 'inactive)
13097 org-log-note-effective-time))
13098 (cons "%T" (format-time-string
13099 (org-time-stamp-format 'long nil)
13100 org-log-note-effective-time))
13101 (cons "%d" (format-time-string
13102 (org-time-stamp-format nil 'inactive)
13103 org-log-note-effective-time))
13104 (cons "%D" (format-time-string
13105 (org-time-stamp-format nil nil)
13106 org-log-note-effective-time))
13107 (cons "%s" (cond
13108 ((not org-log-note-state) "")
13109 ((string-match-p org-ts-regexp
13110 org-log-note-state)
13111 (format "\"[%s]\""
13112 (substring org-log-note-state 1 -1)))
13113 (t (format "\"%s\"" org-log-note-state))))
13114 (cons "%S"
13115 (cond
13116 ((not org-log-note-previous-state) "")
13117 ((string-match-p org-ts-regexp
13118 org-log-note-previous-state)
13119 (format "\"[%s]\""
13120 (substring
13121 org-log-note-previous-state 1 -1)))
13122 (t (format "\"%s\""
13123 org-log-note-previous-state)))))))
13124 (when lines (setq note (concat note " \\\\")))
13125 (push note lines))
13126 (when (and lines (not org-note-abort))
13127 (with-current-buffer (marker-buffer org-log-note-marker)
13128 (org-with-wide-buffer
13129 ;; Find location for the new note.
13130 (goto-char org-log-note-marker)
13131 (set-marker org-log-note-marker nil)
13132 ;; Note associated to a clock is to be located right after
13133 ;; the clock. Do not move point.
13134 (unless (eq org-log-note-purpose 'clock-out)
13135 (goto-char (org-log-beginning t)))
13136 ;; Make sure point is at the beginning of an empty line.
13137 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13138 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13139 ;; In an existing list, add a new item at the top level.
13140 ;; Otherwise, indent line like a regular one.
13141 (let ((itemp (org-in-item-p)))
13142 (if itemp
13143 (indent-line-to
13144 (let ((struct (save-excursion
13145 (goto-char itemp) (org-list-struct))))
13146 (org-list-get-ind (org-list-get-top-point struct) struct)))
13147 (org-indent-line)))
13148 (insert (org-list-bullet-string "-") (pop lines))
13149 (let ((ind (org-list-item-body-column (line-beginning-position))))
13150 (dolist (line lines)
13151 (insert "\n")
13152 (indent-line-to ind)
13153 (insert line)))
13154 (message "Note stored")
13155 (org-back-to-heading t))
13156 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13157 ;; from within `org-add-log-note' because `buffer-undo-list'
13158 ;; is then modified outside of `org-with-remote-undo'.
13159 (when (eq this-command 'org-agenda-todo)
13160 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13161 ;; Don't add undo information when called from `org-agenda-todo'.
13162 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13163 (set-window-configuration org-log-note-window-configuration)
13164 (with-current-buffer (marker-buffer org-log-note-return-to)
13165 (goto-char org-log-note-return-to))
13166 (move-marker org-log-note-return-to nil)
13167 (when org-log-post-message (message "%s" org-log-post-message))))
13169 (defun org-remove-empty-drawer-at (pos)
13170 "Remove an empty drawer at position POS.
13171 POS may also be a marker."
13172 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13173 (org-with-wide-buffer
13174 (goto-char pos)
13175 (let ((drawer (org-element-at-point)))
13176 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13177 (not (org-element-property :contents-begin drawer)))
13178 (delete-region (org-element-property :begin drawer)
13179 (progn (goto-char (org-element-property :end drawer))
13180 (skip-chars-backward " \r\t\n")
13181 (forward-line)
13182 (point))))))))
13184 (defvar org-ts-type nil)
13185 (defun org-sparse-tree (&optional arg type)
13186 "Create a sparse tree, prompt for the details.
13187 This command can create sparse trees. You first need to select the type
13188 of match used to create the tree:
13190 t Show all TODO entries.
13191 T Show entries with a specific TODO keyword.
13192 m Show entries selected by a tags/property match.
13193 p Enter a property name and its value (both with completion on existing
13194 names/values) and show entries with that property.
13195 r Show entries matching a regular expression (`/' can be used as well).
13196 b Show deadlines and scheduled items before a date.
13197 a Show deadlines and scheduled items after a date.
13198 d Show deadlines due within `org-deadline-warning-days'.
13199 D Show deadlines and scheduled items between a date range."
13200 (interactive "P")
13201 (setq type (or type org-sparse-tree-default-date-type))
13202 (setq org-ts-type type)
13203 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13204 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13205 \[c]ycle through date types: %s"
13206 (cl-case type
13207 (all "all timestamps")
13208 (scheduled "only scheduled")
13209 (deadline "only deadline")
13210 (active "only active timestamps")
13211 (inactive "only inactive timestamps")
13212 (closed "with a closed time-stamp")
13213 (otherwise "scheduled/deadline")))
13214 (let ((answer (read-char-exclusive)))
13215 (cl-case answer
13217 (org-sparse-tree
13219 (cadr
13220 (memq type '(nil all scheduled deadline active inactive closed)))))
13221 (?d (call-interactively 'org-check-deadlines))
13222 (?b (call-interactively 'org-check-before-date))
13223 (?a (call-interactively 'org-check-after-date))
13224 (?D (call-interactively 'org-check-dates-range))
13225 (?t (call-interactively 'org-show-todo-tree))
13226 (?T (org-show-todo-tree '(4)))
13227 (?m (call-interactively 'org-match-sparse-tree))
13228 ((?p ?P)
13229 (let* ((kwd (completing-read
13230 "Property: " (mapcar #'list (org-buffer-property-keys))))
13231 (value (completing-read
13232 "Value: " (mapcar #'list (org-property-values kwd)))))
13233 (unless (string-match "\\`{.*}\\'" value)
13234 (setq value (concat "\"" value "\"")))
13235 (org-match-sparse-tree arg (concat kwd "=" value))))
13236 ((?r ?R ?/) (call-interactively 'org-occur))
13237 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13239 (defvar-local org-occur-highlights nil
13240 "List of overlays used for occur matches.")
13241 (defvar-local org-occur-parameters nil
13242 "Parameters of the active org-occur calls.
13243 This is a list, each call to org-occur pushes as cons cell,
13244 containing the regular expression and the callback, onto the list.
13245 The list can contain several entries if `org-occur' has been called
13246 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13247 will only contain one set of parameters. When the highlights are
13248 removed (for example with `C-c C-c', or with the next edit (depending
13249 on `org-remove-highlights-with-change'), this variable is emptied
13250 as well.")
13252 (defun org-occur (regexp &optional keep-previous callback)
13253 "Make a compact tree which shows all matches of REGEXP.
13255 The tree will show the lines where the regexp matches, and any other context
13256 defined in `org-show-context-detail', which see.
13258 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13259 done by a previous call to `org-occur' will be kept, to allow stacking of
13260 calls to this command.
13262 Optional argument CALLBACK can be a function of no argument. In this case,
13263 it is called with point at the end of the match, match data being set
13264 accordingly. Current match is shown only if the return value is non-nil.
13265 The function must neither move point nor alter narrowing."
13266 (interactive "sRegexp: \nP")
13267 (when (equal regexp "")
13268 (user-error "Regexp cannot be empty"))
13269 (unless keep-previous
13270 (org-remove-occur-highlights nil nil t))
13271 (push (cons regexp callback) org-occur-parameters)
13272 (let ((cnt 0))
13273 (save-excursion
13274 (goto-char (point-min))
13275 (when (or (not keep-previous) ; do not want to keep
13276 (not org-occur-highlights)) ; no previous matches
13277 ;; hide everything
13278 (org-overview))
13279 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13280 (isearch-no-upper-case-p regexp t)
13281 org-occur-case-fold-search)))
13282 (while (re-search-forward regexp nil t)
13283 (when (or (not callback)
13284 (save-match-data (funcall callback)))
13285 (setq cnt (1+ cnt))
13286 (when org-highlight-sparse-tree-matches
13287 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13288 (org-show-context 'occur-tree)))))
13289 (when org-remove-highlights-with-change
13290 (add-hook 'before-change-functions 'org-remove-occur-highlights
13291 nil 'local))
13292 (unless org-sparse-tree-open-archived-trees
13293 (org-hide-archived-subtrees (point-min) (point-max)))
13294 (run-hooks 'org-occur-hook)
13295 (when (called-interactively-p 'interactive)
13296 (message "%d match(es) for regexp %s" cnt regexp))
13297 cnt))
13299 (defun org-occur-next-match (&optional n _reset)
13300 "Function for `next-error-function' to find sparse tree matches.
13301 N is the number of matches to move, when negative move backwards.
13302 This function always goes back to the starting point when no
13303 match is found."
13304 (let* ((limit (if (< n 0) (point-min) (point-max)))
13305 (search-func (if (< n 0)
13306 'previous-single-char-property-change
13307 'next-single-char-property-change))
13308 (n (abs n))
13309 (pos (point))
13311 (catch 'exit
13312 (while (setq p1 (funcall search-func (point) 'org-type))
13313 (when (equal p1 limit)
13314 (goto-char pos)
13315 (user-error "No more matches"))
13316 (when (equal (get-char-property p1 'org-type) 'org-occur)
13317 (setq n (1- n))
13318 (when (= n 0)
13319 (goto-char p1)
13320 (throw 'exit (point))))
13321 (goto-char p1))
13322 (goto-char p1)
13323 (user-error "No more matches"))))
13325 (defun org-highlight-new-match (beg end)
13326 "Highlight from BEG to END and mark the highlight is an occur headline."
13327 (let ((ov (make-overlay beg end)))
13328 (overlay-put ov 'face 'secondary-selection)
13329 (overlay-put ov 'org-type 'org-occur)
13330 (push ov org-occur-highlights)))
13332 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13333 "Remove the occur highlights from the buffer.
13334 BEG and END are ignored. If NOREMOVE is nil, remove this function
13335 from the `before-change-functions' in the current buffer."
13336 (interactive)
13337 (unless org-inhibit-highlight-removal
13338 (mapc #'delete-overlay org-occur-highlights)
13339 (setq org-occur-highlights nil)
13340 (setq org-occur-parameters nil)
13341 (unless noremove
13342 (remove-hook 'before-change-functions
13343 'org-remove-occur-highlights 'local))))
13345 ;;;; Priorities
13347 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13348 "Regular expression matching the priority indicator.")
13350 (defvar org-remove-priority-next-time nil)
13352 (defun org-priority-up ()
13353 "Increase the priority of the current item."
13354 (interactive)
13355 (org-priority 'up))
13357 (defun org-priority-down ()
13358 "Decrease the priority of the current item."
13359 (interactive)
13360 (org-priority 'down))
13362 (defun org-priority (&optional action _show)
13363 "Change the priority of an item.
13364 ACTION can be `set', `up', `down', or a character."
13365 (interactive "P")
13366 (if (equal action '(4))
13367 (org-show-priority)
13368 (unless org-enable-priority-commands
13369 (user-error "Priority commands are disabled"))
13370 (setq action (or action 'set))
13371 (let (current new news have remove)
13372 (save-excursion
13373 (org-back-to-heading t)
13374 (when (looking-at org-priority-regexp)
13375 (setq current (string-to-char (match-string 2))
13376 have t))
13377 (cond
13378 ((eq action 'remove)
13379 (setq remove t new ?\ ))
13380 ((or (eq action 'set)
13381 (integerp action))
13382 (if (not (eq action 'set))
13383 (setq new action)
13384 (message "Priority %c-%c, SPC to remove: "
13385 org-highest-priority org-lowest-priority)
13386 (save-match-data
13387 (setq new (read-char-exclusive))))
13388 (when (and (= (upcase org-highest-priority) org-highest-priority)
13389 (= (upcase org-lowest-priority) org-lowest-priority))
13390 (setq new (upcase new)))
13391 (cond ((equal new ?\ ) (setq remove t))
13392 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13393 (user-error "Priority must be between `%c' and `%c'"
13394 org-highest-priority org-lowest-priority))))
13395 ((eq action 'up)
13396 (setq new (if have
13397 (1- current) ; normal cycling
13398 ;; last priority was empty
13399 (if (eq last-command this-command)
13400 org-lowest-priority ; wrap around empty to lowest
13401 ;; default
13402 (if org-priority-start-cycle-with-default
13403 org-default-priority
13404 (1- org-default-priority))))))
13405 ((eq action 'down)
13406 (setq new (if have
13407 (1+ current) ; normal cycling
13408 ;; last priority was empty
13409 (if (eq last-command this-command)
13410 org-highest-priority ; wrap around empty to highest
13411 ;; default
13412 (if org-priority-start-cycle-with-default
13413 org-default-priority
13414 (1+ org-default-priority))))))
13415 (t (user-error "Invalid action")))
13416 (when (or (< (upcase new) org-highest-priority)
13417 (> (upcase new) org-lowest-priority))
13418 (if (and (memq action '(up down))
13419 (not have) (not (eq last-command this-command)))
13420 ;; `new' is from default priority
13421 (error
13422 "The default can not be set, see `org-default-priority' why")
13423 ;; normal cycling: `new' is beyond highest/lowest priority
13424 ;; and is wrapped around to the empty priority
13425 (setq remove t)))
13426 (setq news (format "%c" new))
13427 (if have
13428 (if remove
13429 (replace-match "" t t nil 1)
13430 (replace-match news t t nil 2))
13431 (if remove
13432 (user-error "No priority cookie found in line")
13433 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13434 (if (match-end 2)
13435 (progn
13436 (goto-char (match-end 2))
13437 (insert " [#" news "]"))
13438 (goto-char (match-beginning 3))
13439 (insert "[#" news "] "))))
13440 (org-set-tags nil 'align))
13441 (if remove
13442 (message "Priority removed")
13443 (message "Priority of current item set to %s" news)))))
13445 (defun org-show-priority ()
13446 "Show the priority of the current item.
13447 This priority is composed of the main priority given with the [#A] cookies,
13448 and by additional input from the age of a schedules or deadline entry."
13449 (interactive)
13450 (let ((pri (if (eq major-mode 'org-agenda-mode)
13451 (org-get-at-bol 'priority)
13452 (save-excursion
13453 (save-match-data
13454 (beginning-of-line)
13455 (and (looking-at org-heading-regexp)
13456 (org-get-priority (match-string 0))))))))
13457 (message "Priority is %d" (if pri pri -1000))))
13459 (defun org-get-priority (s)
13460 "Find priority cookie and return priority."
13461 (save-match-data
13462 (if (functionp org-get-priority-function)
13463 (funcall org-get-priority-function)
13464 (if (not (string-match org-priority-regexp s))
13465 (* 1000 (- org-lowest-priority org-default-priority))
13466 (* 1000 (- org-lowest-priority
13467 (string-to-char (match-string 2 s))))))))
13469 ;;;; Tags
13471 (defvar org-agenda-archives-mode)
13472 (defvar org-map-continue-from nil
13473 "Position from where mapping should continue.
13474 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13476 (defvar org-scanner-tags nil
13477 "The current tag list while the tags scanner is running.")
13479 (defvar org-trust-scanner-tags nil
13480 "Should `org-get-tags-at' use the tags for the scanner.
13481 This is for internal dynamical scoping only.
13482 When this is non-nil, the function `org-get-tags-at' will return the value
13483 of `org-scanner-tags' instead of building the list by itself. This
13484 can lead to large speed-ups when the tags scanner is used in a file with
13485 many entries, and when the list of tags is retrieved, for example to
13486 obtain a list of properties. Building the tags list for each entry in such
13487 a file becomes an N^2 operation - but with this variable set, it scales
13488 as N.")
13490 (defvar org--matcher-tags-todo-only nil)
13492 (defun org-scan-tags (action matcher todo-only &optional start-level)
13493 "Scan headline tags with inheritance and produce output ACTION.
13495 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13496 or `agenda' to produce an entry list for an agenda view. It can also be
13497 a Lisp form or a function that should be called at each matched headline, in
13498 this case the return value is a list of all return values from these calls.
13500 MATCHER is a function accepting three arguments, returning
13501 a non-nil value whenever a given set of tags qualifies a headline
13502 for inclusion. See `org-make-tags-matcher' for more information.
13503 As a special case, it can also be set to t (respectively nil) in
13504 order to match all (respectively none) headline.
13506 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13507 included in the output.
13509 START-LEVEL can be a string with asterisks, reducing the scope to
13510 headlines matching this string."
13511 (require 'org-agenda)
13512 (let* ((re (concat "^"
13513 (if start-level
13514 ;; Get the correct level to match
13515 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13516 org-outline-regexp)
13517 " *\\(\\<\\("
13518 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13519 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13520 (props (list 'face 'default
13521 'done-face 'org-agenda-done
13522 'undone-face 'default
13523 'mouse-face 'highlight
13524 'org-not-done-regexp org-not-done-regexp
13525 'org-todo-regexp org-todo-regexp
13526 'org-complex-heading-regexp org-complex-heading-regexp
13527 'help-echo
13528 (format "mouse-2 or RET jump to Org file %S"
13529 (abbreviate-file-name
13530 (or (buffer-file-name (buffer-base-buffer))
13531 (buffer-name (buffer-base-buffer)))))))
13532 (org-map-continue-from nil)
13533 lspos tags tags-list
13534 (tags-alist (list (cons 0 org-file-tags)))
13535 (llast 0) rtn rtn1 level category i txt
13536 todo marker entry priority
13537 ts-date ts-date-type ts-date-pair)
13538 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13539 (setq action (list 'lambda nil action)))
13540 (save-excursion
13541 (goto-char (point-min))
13542 (when (eq action 'sparse-tree)
13543 (org-overview)
13544 (org-remove-occur-highlights))
13545 (while (let (case-fold-search)
13546 (re-search-forward re nil t))
13547 (setq org-map-continue-from nil)
13548 (catch :skip
13549 (setq todo
13550 ;; TODO: is the 1-2 difference a bug?
13551 (when (match-end 1) (match-string-no-properties 2))
13552 tags (when (match-end 4) (match-string-no-properties 4)))
13553 (goto-char (setq lspos (match-beginning 0)))
13554 (setq level (org-reduced-level (org-outline-level))
13555 category (org-get-category))
13556 (when (eq action 'agenda)
13557 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13558 ts-date (car ts-date-pair)
13559 ts-date-type (cdr ts-date-pair)))
13560 (setq i llast llast level)
13561 ;; remove tag lists from same and sublevels
13562 (while (>= i level)
13563 (when (setq entry (assoc i tags-alist))
13564 (setq tags-alist (delete entry tags-alist)))
13565 (setq i (1- i)))
13566 ;; add the next tags
13567 (when tags
13568 (setq tags (org-split-string tags ":")
13569 tags-alist
13570 (cons (cons level tags) tags-alist)))
13571 ;; compile tags for current headline
13572 (setq tags-list
13573 (if org-use-tag-inheritance
13574 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13575 tags)
13576 org-scanner-tags tags-list)
13577 (when org-use-tag-inheritance
13578 (setcdr (car tags-alist)
13579 (mapcar (lambda (x)
13580 (setq x (copy-sequence x))
13581 (org-add-prop-inherited x))
13582 (cdar tags-alist))))
13583 (when (and tags org-use-tag-inheritance
13584 (or (not (eq t org-use-tag-inheritance))
13585 org-tags-exclude-from-inheritance))
13586 ;; Selective inheritance, remove uninherited ones.
13587 (setcdr (car tags-alist)
13588 (org-remove-uninherited-tags (cdar tags-alist))))
13589 (when (and
13591 ;; eval matcher only when the todo condition is OK
13592 (and (or (not todo-only) (member todo org-todo-keywords-1))
13593 (if (functionp matcher)
13594 (let ((case-fold-search t) (org-trust-scanner-tags t))
13595 (funcall matcher todo tags-list level))
13596 matcher))
13598 ;; Call the skipper, but return t if it does not
13599 ;; skip, so that the `and' form continues evaluating.
13600 (progn
13601 (unless (eq action 'sparse-tree) (org-agenda-skip))
13604 ;; Check if timestamps are deselecting this entry
13605 (or (not todo-only)
13606 (and (member todo org-todo-keywords-1)
13607 (or (not org-agenda-tags-todo-honor-ignore-options)
13608 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13610 ;; select this headline
13611 (cond
13612 ((eq action 'sparse-tree)
13613 (and org-highlight-sparse-tree-matches
13614 (org-get-heading) (match-end 0)
13615 (org-highlight-new-match
13616 (match-beginning 1) (match-end 1)))
13617 (org-show-context 'tags-tree))
13618 ((eq action 'agenda)
13619 (setq txt (org-agenda-format-item
13621 (concat
13622 (if (eq org-tags-match-list-sublevels 'indented)
13623 (make-string (1- level) ?.) "")
13624 (org-get-heading))
13625 (make-string level ?\s)
13626 category
13627 tags-list)
13628 priority (org-get-priority txt))
13629 (goto-char lspos)
13630 (setq marker (org-agenda-new-marker))
13631 (org-add-props txt props
13632 'org-marker marker 'org-hd-marker marker 'org-category category
13633 'todo-state todo
13634 'ts-date ts-date
13635 'priority priority
13636 'type (concat "tagsmatch" ts-date-type))
13637 (push txt rtn))
13638 ((functionp action)
13639 (setq org-map-continue-from nil)
13640 (save-excursion
13641 (setq rtn1 (funcall action))
13642 (push rtn1 rtn)))
13643 (t (user-error "Invalid action")))
13645 ;; if we are to skip sublevels, jump to end of subtree
13646 (unless org-tags-match-list-sublevels
13647 (org-end-of-subtree t)
13648 (backward-char 1))))
13649 ;; Get the correct position from where to continue
13650 (if org-map-continue-from
13651 (goto-char org-map-continue-from)
13652 (and (= (point) lspos) (end-of-line 1)))))
13653 (when (and (eq action 'sparse-tree)
13654 (not org-sparse-tree-open-archived-trees))
13655 (org-hide-archived-subtrees (point-min) (point-max)))
13656 (nreverse rtn)))
13658 (defun org-remove-uninherited-tags (tags)
13659 "Remove all tags that are not inherited from the list TAGS."
13660 (cond
13661 ((eq org-use-tag-inheritance t)
13662 (if org-tags-exclude-from-inheritance
13663 (org-delete-all org-tags-exclude-from-inheritance tags)
13664 tags))
13665 ((not org-use-tag-inheritance) nil)
13666 ((stringp org-use-tag-inheritance)
13667 (delq nil (mapcar
13668 (lambda (x)
13669 (if (and (string-match org-use-tag-inheritance x)
13670 (not (member x org-tags-exclude-from-inheritance)))
13671 x nil))
13672 tags)))
13673 ((listp org-use-tag-inheritance)
13674 (delq nil (mapcar
13675 (lambda (x)
13676 (if (member x org-use-tag-inheritance) x nil))
13677 tags)))))
13679 (defun org-match-sparse-tree (&optional todo-only match)
13680 "Create a sparse tree according to tags string MATCH.
13682 MATCH is a string with match syntax. It can contain a selection
13683 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13684 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13685 those. See the manual for details.
13687 If optional argument TODO-ONLY is non-nil, only select lines that
13688 are also TODO tasks."
13689 (interactive "P")
13690 (org-agenda-prepare-buffers (list (current-buffer)))
13691 (let ((org--matcher-tags-todo-only todo-only))
13692 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13693 org--matcher-tags-todo-only)))
13695 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13697 (defvar org-cached-props nil)
13698 (defun org-cached-entry-get (pom property)
13699 (if (or (eq t org-use-property-inheritance)
13700 (and (stringp org-use-property-inheritance)
13701 (let ((case-fold-search t))
13702 (string-match-p org-use-property-inheritance property)))
13703 (and (listp org-use-property-inheritance)
13704 (member-ignore-case property org-use-property-inheritance)))
13705 ;; Caching is not possible, check it directly.
13706 (org-entry-get pom property 'inherit)
13707 ;; Get all properties, so we can do complicated checks easily.
13708 (cdr (assoc-string property
13709 (or org-cached-props
13710 (setq org-cached-props (org-entry-properties pom)))
13711 t))))
13713 (defun org-global-tags-completion-table (&optional files)
13714 "Return the list of all tags in all agenda buffer/files.
13715 Optional FILES argument is a list of files which can be used
13716 instead of the agenda files."
13717 (save-excursion
13718 (org-uniquify
13719 (delq nil
13720 (apply #'append
13721 (mapcar
13722 (lambda (file)
13723 (set-buffer (find-file-noselect file))
13724 (mapcar (lambda (x)
13725 (and (stringp (car-safe x))
13726 (list (car-safe x))))
13727 (or org-current-tag-alist (org-get-buffer-tags))))
13728 (if (car-safe files) files
13729 (org-agenda-files))))))))
13731 (defun org-make-tags-matcher (match)
13732 "Create the TAGS/TODO matcher form for the selection string MATCH.
13734 Returns a cons of the selection string MATCH and a function
13735 implementing the matcher.
13737 The matcher is to be called at an Org entry, with point on the
13738 headline, and returns non-nil if the entry matches the selection
13739 string MATCH. It must be called with three arguments: the TODO
13740 keyword at the entry (or nil if none), the list of all tags at
13741 the entry including inherited ones and the reduced level of the
13742 headline. Additionally, the category of the entry, if any, must
13743 be specified as the text property `org-category' on the headline.
13745 This function sets the variable `org--matcher-tags-todo-only' to
13746 a non-nil value if the matcher restricts matching to TODO
13747 entries, otherwise it is not touched.
13749 See also `org-scan-tags'."
13750 (unless match
13751 ;; Get a new match request, with completion against the global
13752 ;; tags table and the local tags in current buffer.
13753 (let ((org-last-tags-completion-table
13754 (org-uniquify
13755 (delq nil (append (org-get-buffer-tags)
13756 (org-global-tags-completion-table))))))
13757 (setq match
13758 (completing-read
13759 "Match: "
13760 'org-tags-completion-function nil nil nil 'org-tags-history))))
13762 (let ((match0 match)
13763 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
13764 (start 0)
13765 tagsmatch todomatch tagsmatcher todomatcher)
13767 ;; Expand group tags.
13768 (setq match (org-tags-expand match))
13770 ;; Check if there is a TODO part of this match, which would be the
13771 ;; part after a "/". To make sure that this slash is not part of
13772 ;; a property value to be matched against, we also check that
13773 ;; there is no / after that slash. First, find the last slash.
13774 (let ((s 0))
13775 (while (string-match "/+" match s)
13776 (setq start (match-beginning 0))
13777 (setq s (match-end 0))))
13778 (if (and (string-match "/+" match start)
13779 (not (string-match-p "\"" match start)))
13780 ;; Match contains also a TODO-matching request.
13781 (progn
13782 (setq tagsmatch (substring match 0 (match-beginning 0)))
13783 (setq todomatch (substring match (match-end 0)))
13784 (when (string-prefix-p "!" todomatch)
13785 (setq org--matcher-tags-todo-only t)
13786 (setq todomatch (substring todomatch 1)))
13787 (when (string-match "\\`\\s-*\\'" todomatch)
13788 (setq todomatch nil)))
13789 ;; Only matching tags.
13790 (setq tagsmatch match)
13791 (setq todomatch nil))
13793 ;; Make the tags matcher.
13794 (when (org-string-nw-p tagsmatch)
13795 (let ((orlist nil)
13796 (orterms (org-split-string tagsmatch "|"))
13797 term)
13798 (while (setq term (pop orterms))
13799 (while (and (equal (substring term -1) "\\") orterms)
13800 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13801 (while (string-match re term)
13802 (let* ((rest (substring term (match-end 0)))
13803 (minus (and (match-end 1)
13804 (equal (match-string 1 term) "-")))
13805 (tag (save-match-data
13806 (replace-regexp-in-string
13807 "\\\\-" "-" (match-string 2 term))))
13808 (regexp (eq (string-to-char tag) ?{))
13809 (levelp (match-end 4))
13810 (propp (match-end 5))
13812 (cond
13813 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13814 (levelp
13815 `(,(org-op-to-function (match-string 3 term))
13816 level
13817 ,(string-to-number (match-string 4 term))))
13818 (propp
13819 (let* ((gv (pcase (upcase (match-string 5 term))
13820 ("CATEGORY"
13821 '(get-text-property (point) 'org-category))
13822 ("TODO" 'todo)
13823 (p `(org-cached-entry-get nil ,p))))
13824 (pv (match-string 7 term))
13825 (regexp (eq (string-to-char pv) ?{))
13826 (strp (eq (string-to-char pv) ?\"))
13827 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13828 (po (org-op-to-function (match-string 6 term)
13829 (if timep 'time strp))))
13830 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13831 (when timep (setq pv (org-matcher-time pv)))
13832 (cond ((and regexp (eq po 'org<>))
13833 `(not (string-match ,pv (or ,gv ""))))
13834 (regexp `(string-match ,pv (or ,gv "")))
13835 (strp `(,po (or ,gv "") ,pv))
13837 `(,po
13838 (string-to-number (or ,gv ""))
13839 ,(string-to-number pv))))))
13840 (t `(member ,tag tags-list)))))
13841 (push (if minus `(not ,mm) mm) tagsmatcher)
13842 (setq term rest)))
13843 (push `(and ,@tagsmatcher) orlist)
13844 (setq tagsmatcher nil))
13845 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13847 ;; Make the TODO matcher.
13848 (when (org-string-nw-p todomatch)
13849 (let ((orlist nil))
13850 (dolist (term (org-split-string todomatch "|"))
13851 (while (string-match re term)
13852 (let* ((minus (and (match-end 1)
13853 (equal (match-string 1 term) "-")))
13854 (kwd (match-string 2 term))
13855 (regexp (eq (string-to-char kwd) ?{))
13856 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13857 `(equal todo ,kwd))))
13858 (push (if minus `(not ,mm) mm) todomatcher))
13859 (setq term (substring term (match-end 0))))
13860 (push (if (> (length todomatcher) 1)
13861 (cons 'and todomatcher)
13862 (car todomatcher))
13863 orlist)
13864 (setq todomatcher nil))
13865 (setq todomatcher (cons 'or orlist))))
13867 ;; Return the string and function of the matcher. If no
13868 ;; tags-specific or todo-specific matcher exists, match
13869 ;; everything.
13870 (let ((matcher (if (and tagsmatcher todomatcher)
13871 `(and ,tagsmatcher ,todomatcher)
13872 (or tagsmatcher todomatcher t))))
13873 (when org--matcher-tags-todo-only
13874 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
13875 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
13877 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
13878 "Expand group tags in MATCH.
13880 This replaces every group tag in MATCH with a regexp tag search.
13881 For example, a group tag \"Work\" defined as { Work : Lab Conf }
13882 will be replaced like this:
13884 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13885 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13886 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13888 Replacing by a regexp preserves the structure of the match.
13889 E.g., this expansion
13891 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
13893 will match anything tagged with \"Lab\" and \"Home\", or tagged
13894 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
13896 A group tag in MATCH can contain regular expressions of its own.
13897 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
13898 will be replaced like this:
13900 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
13902 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
13903 assumed to be a single group tag, and the function will return
13904 the list of tags in this group.
13906 When DOWNCASE is non-nil, expand downcased TAGS."
13907 (if org-group-tags
13908 (let* ((case-fold-search t)
13909 (stable org-mode-syntax-table)
13910 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
13911 (taggroups (if downcased
13912 (mapcar (lambda (tg) (mapcar #'downcase tg))
13913 taggroups)
13914 taggroups))
13915 (taggroups-keys (mapcar #'car taggroups))
13916 (return-match (if downcased (downcase match) match))
13917 (count 0)
13918 (work-already-expanded tags-already-expanded)
13919 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
13920 ;; @ and _ are allowed as word-components in tags.
13921 (modify-syntax-entry ?@ "w" stable)
13922 (modify-syntax-entry ?_ "w" stable)
13923 ;; Temporarily replace regexp-expressions in the match-expression.
13924 (while (string-match "{.+?}" return-match)
13925 (cl-incf count)
13926 (push (match-string 0 return-match) regexps-in-match)
13927 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
13928 (while (and taggroups-keys
13929 (with-syntax-table stable
13930 (string-match
13931 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
13932 (regexp-opt taggroups-keys) "\\>\\)")
13933 return-match)))
13934 (let* ((dir (match-string 1 return-match))
13935 (tag (match-string 2 return-match))
13936 (tag (if downcased (downcase tag) tag)))
13937 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
13938 (member tag work-already-expanded))
13939 (setq tags-in-group (assoc tag taggroups))
13940 (push tag work-already-expanded)
13941 ;; Recursively expand each tag in the group, if the tag hasn't
13942 ;; already been expanded. Restore the match-data after all recursive calls.
13943 (save-match-data
13944 (let (tags-expanded)
13945 (dolist (x (cdr tags-in-group))
13946 (if (and (member x taggroups-keys)
13947 (not (member x work-already-expanded)))
13948 (setq tags-expanded
13949 (delete-dups
13950 (append
13951 (org-tags-expand x t downcased
13952 work-already-expanded)
13953 tags-expanded)))
13954 (setq tags-expanded
13955 (append (list x) tags-expanded)))
13956 (setq work-already-expanded
13957 (delete-dups
13958 (append tags-expanded
13959 work-already-expanded))))
13960 (setq tags-in-group
13961 (delete-dups (cons (car tags-in-group)
13962 tags-expanded)))))
13963 ;; Filter tag-regexps from tags.
13964 (setq regexp-in-group-escaped
13965 (delq nil (mapcar (lambda (x)
13966 (if (stringp x)
13967 (and (equal "{" (substring x 0 1))
13968 (equal "}" (substring x -1))
13971 tags-in-group))
13972 regexp-in-group
13973 (mapcar (lambda (x)
13974 (substring x 1 -1))
13975 regexp-in-group-escaped)
13976 tags-in-group
13977 (delq nil (mapcar (lambda (x)
13978 (if (stringp x)
13979 (and (not (equal "{" (substring x 0 1)))
13980 (not (equal "}" (substring x -1)))
13983 tags-in-group)))
13984 ;; If single-as-list, do no more in the while-loop.
13985 (if (not single-as-list)
13986 (progn
13987 (when regexp-in-group
13988 (setq regexp-in-group
13989 (concat "\\|"
13990 (mapconcat 'identity regexp-in-group
13991 "\\|"))))
13992 (setq tags-in-group
13993 (concat dir
13994 "{\\<"
13995 (regexp-opt tags-in-group)
13996 "\\>"
13997 regexp-in-group
13998 "}"))
13999 (when (stringp tags-in-group)
14000 (org-add-props tags-in-group '(grouptag t)))
14001 (setq return-match
14002 (replace-match tags-in-group t t return-match)))
14003 (setq tags-in-group
14004 (append regexp-in-group-escaped tags-in-group))))
14005 (setq taggroups-keys (delete tag taggroups-keys))))
14006 ;; Add the regular expressions back into the match-expression again.
14007 (while regexps-in-match
14008 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14009 (pop regexps-in-match)
14010 return-match t t))
14011 (cl-decf count))
14012 (if single-as-list
14013 (if tags-in-group tags-in-group (list return-match))
14014 return-match))
14015 (if single-as-list
14016 (list (if downcased (downcase match) match))
14017 match)))
14019 (defun org-op-to-function (op &optional stringp)
14020 "Turn an operator into the appropriate function."
14021 (setq op
14022 (cond
14023 ((equal op "<" ) '(< string< org-time<))
14024 ((equal op ">" ) '(> org-string> org-time>))
14025 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14026 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14027 ((member op '("=" "==")) '(= string= org-time=))
14028 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14029 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14031 (defun org<> (a b) (not (= a b)))
14032 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14033 (defun org-string>= (a b) (not (string< a b)))
14034 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14035 (defun org-string<> (a b) (not (string= a b)))
14036 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14037 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14038 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14039 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14040 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14041 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14042 (defun org-2ft (s)
14043 "Convert S to a floating point time.
14044 If S is already a number, just return it. If it is a string, parse
14045 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14046 (cond
14047 ((numberp s) s)
14048 ((stringp s)
14049 (condition-case nil
14050 (float-time (apply #'encode-time (org-parse-time-string s)))
14051 (error 0.)))
14052 (t 0.)))
14054 (defun org-time-today ()
14055 "Time in seconds today at 0:00.
14056 Returns the float number of seconds since the beginning of the
14057 epoch to the beginning of today (00:00)."
14058 (float-time (apply 'encode-time
14059 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14061 (defun org-matcher-time (s)
14062 "Interpret a time comparison value."
14063 (save-match-data
14064 (cond
14065 ((string= s "<now>") (float-time))
14066 ((string= s "<today>") (org-time-today))
14067 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14068 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14069 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14070 (+ (org-time-today)
14071 (* (string-to-number (match-string 1 s))
14072 (cdr (assoc (match-string 2 s)
14073 '(("d" . 86400.0) ("w" . 604800.0)
14074 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14075 (t (org-2ft s)))))
14077 (defun org-match-any-p (re list)
14078 "Does re match any element of list?"
14079 (setq list (mapcar (lambda (x) (string-match re x)) list))
14080 (delq nil list))
14082 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14083 (defvar org-tags-overlay (make-overlay 1 1))
14084 (delete-overlay org-tags-overlay)
14086 (defun org-get-local-tags-at (&optional pos)
14087 "Get a list of tags defined in the current headline."
14088 (org-get-tags-at pos 'local))
14090 (defun org-get-local-tags ()
14091 "Get a list of tags defined in the current headline."
14092 (org-get-tags-at nil 'local))
14094 (defun org-get-tags-at (&optional pos local)
14095 "Get a list of all headline tags applicable at POS.
14096 POS defaults to point. If tags are inherited, the list contains
14097 the targets in the same sequence as the headlines appear, i.e.
14098 the tags of the current headline come last.
14099 When LOCAL is non-nil, only return tags from the current headline,
14100 ignore inherited ones."
14101 (interactive)
14102 (if (and org-trust-scanner-tags
14103 (or (not pos) (equal pos (point)))
14104 (not local))
14105 org-scanner-tags
14106 (let (tags ltags lastpos parent)
14107 (save-excursion
14108 (save-restriction
14109 (widen)
14110 (goto-char (or pos (point)))
14111 (save-match-data
14112 (catch 'done
14113 (condition-case nil
14114 (progn
14115 (org-back-to-heading t)
14116 (while (not (equal lastpos (point)))
14117 (setq lastpos (point))
14118 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14119 (setq ltags (org-split-string
14120 (match-string-no-properties 1) ":"))
14121 (when parent
14122 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14123 (setq tags (append
14124 (if parent
14125 (org-remove-uninherited-tags ltags)
14126 ltags)
14127 tags)))
14128 (or org-use-tag-inheritance (throw 'done t))
14129 (when local (throw 'done t))
14130 (or (org-up-heading-safe) (error nil))
14131 (setq parent t)))
14132 (error nil)))))
14133 (if local
14134 tags
14135 (reverse (delete-dups
14136 (reverse (append
14137 (org-remove-uninherited-tags
14138 org-file-tags)
14139 tags)))))))))
14141 (defun org-add-prop-inherited (s)
14142 (add-text-properties 0 (length s) '(inherited t) s)
14145 (defun org-toggle-tag (tag &optional onoff)
14146 "Toggle the tag TAG for the current line.
14147 If ONOFF is `on' or `off', don't toggle but set to this state."
14148 (save-excursion
14149 (org-back-to-heading t)
14150 (let ((current
14151 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14152 (line-end-position) t)
14153 (let ((tags (match-string 1)))
14154 ;; Clear current tags.
14155 (replace-match "")
14156 ;; Reverse the tags list so any new tag is appended to
14157 ;; the current list of tags.
14158 (nreverse (org-split-string tags ":")))))
14159 res)
14160 (pcase onoff
14161 (`off (setq current (delete tag current)))
14162 ((or `on (guard (not (member tag current))))
14163 (setq res t)
14164 (cl-pushnew tag current :test #'equal))
14165 (_ (setq current (delete tag current))))
14166 (end-of-line)
14167 (if current
14168 (progn
14169 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14170 (org-set-tags nil t))
14171 (delete-horizontal-space))
14172 (run-hooks 'org-after-tags-change-hook)
14173 res)))
14175 (defun org--align-tags-here (to-col)
14176 "Align tags on the current headline to TO-COL.
14177 Assume point is on a headline."
14178 (let ((pos (point)))
14179 (beginning-of-line)
14180 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14181 (>= pos (match-beginning 2)))
14182 ;; No tags or point within tags: do not align.
14183 (goto-char pos)
14184 (goto-char (match-beginning 1))
14185 (let ((shift (max (- (if (>= to-col 0) to-col
14186 (- (abs to-col) (string-width (match-string 2))))
14187 (current-column))
14188 1)))
14189 (replace-match (make-string shift ?\s) nil nil nil 1)
14190 ;; Preserve initial position, if possible. In any case, stop
14191 ;; before tags.
14192 (when (< pos (point)) (goto-char pos))))))
14194 (defun org-set-tags-command (&optional arg just-align)
14195 "Call the set-tags command for the current entry."
14196 (interactive "P")
14197 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14198 (org-set-tags arg just-align)
14199 (save-excursion
14200 (unless (and (org-region-active-p)
14201 org-loop-over-headlines-in-active-region)
14202 (org-back-to-heading t))
14203 (org-set-tags arg just-align))))
14205 (defun org-set-tags-to (data)
14206 "Set the tags of the current entry to DATA, replacing the current tags.
14207 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14208 If DATA is nil or the empty string, any tags will be removed."
14209 (interactive "sTags: ")
14210 (setq data
14211 (cond
14212 ((eq data nil) "")
14213 ((equal data "") "")
14214 ((stringp data)
14215 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14216 ":"))
14217 ((listp data)
14218 (concat ":" (mapconcat 'identity data ":") ":"))))
14219 (when data
14220 (save-excursion
14221 (org-back-to-heading t)
14222 (when (let ((case-fold-search nil))
14223 (looking-at org-complex-heading-regexp))
14224 (if (match-end 5)
14225 (progn
14226 (goto-char (match-beginning 5))
14227 (insert data)
14228 (delete-region (point) (point-at-eol))
14229 (org-set-tags nil 'align))
14230 (goto-char (point-at-eol))
14231 (insert " " data)
14232 (org-set-tags nil 'align)))
14233 (beginning-of-line 1)
14234 (when (looking-at ".*?\\([ \t]+\\)$")
14235 (delete-region (match-beginning 1) (match-end 1))))))
14237 (defun org-align-all-tags ()
14238 "Align the tags in all headings."
14239 (interactive)
14240 (save-excursion
14241 (or (ignore-errors (org-back-to-heading t))
14242 (outline-next-heading))
14243 (if (org-at-heading-p)
14244 (org-set-tags t)
14245 (message "No headings"))))
14247 (defvar org-indent-indentation-per-level)
14248 (defun org-set-tags (&optional arg just-align)
14249 "Set the tags for the current headline.
14250 With prefix ARG, realign all tags in headings in the current buffer.
14251 When JUST-ALIGN is non-nil, only align tags."
14252 (interactive "P")
14253 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14254 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14255 'region-start-level
14256 'region))
14257 org-loop-over-headlines-in-active-region)
14258 (org-map-entries
14259 ;; We don't use ARG and JUST-ALIGN here because these args
14260 ;; are not useful when looping over headlines.
14261 #'org-set-tags
14262 org-loop-over-headlines-in-active-region
14264 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14265 (let ((org-setting-tags t))
14266 (if arg
14267 (save-excursion
14268 (goto-char (point-min))
14269 (while (re-search-forward org-outline-regexp-bol nil t)
14270 (org-set-tags nil t)
14271 (end-of-line))
14272 (message "All tags realigned to column %d" org-tags-column))
14273 (let* ((current (org-get-tags-string))
14274 (tags
14275 (if just-align current
14276 ;; Get a new set of tags from the user.
14277 (save-excursion
14278 (let* ((seen)
14279 (table
14280 (setq
14281 org-last-tags-completion-table
14282 ;; Uniquify tags in alists, yet preserve
14283 ;; structure (i.e., keywords).
14284 (delq nil
14285 (mapcar
14286 (lambda (pair)
14287 (let ((head (car pair)))
14288 (cond ((symbolp head) pair)
14289 ((member head seen) nil)
14290 (t (push head seen)
14291 pair))))
14292 (append
14293 (or org-current-tag-alist
14294 (org-get-buffer-tags))
14295 (and
14296 org-complete-tags-always-offer-all-agenda-tags
14297 (org-global-tags-completion-table
14298 (org-agenda-files))))))))
14299 (current-tags (org-split-string current ":"))
14300 (inherited-tags
14301 (nreverse (nthcdr (length current-tags)
14302 (nreverse (org-get-tags-at))))))
14303 (replace-regexp-in-string
14304 "\\([-+&]+\\|,\\)"
14306 (if (or (eq t org-use-fast-tag-selection)
14307 (and org-use-fast-tag-selection
14308 (delq nil (mapcar #'cdr table))))
14309 (org-fast-tag-selection
14310 current-tags inherited-tags table
14311 (and org-fast-tag-selection-include-todo
14312 org-todo-key-alist))
14313 (let ((org-add-colon-after-tag-completion
14314 (< 1 (length table))))
14315 (org-trim
14316 (completing-read
14317 "Tags: "
14318 #'org-tags-completion-function
14319 nil nil current 'org-tags-history))))))))))
14321 (when org-tags-sort-function
14322 (setq tags
14323 (mapconcat
14324 #'identity
14325 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14326 org-tags-sort-function)
14327 ":")))
14329 (if (or (string= ":" tags)
14330 (string= "::" tags))
14331 (setq tags ""))
14332 (if (not (org-string-nw-p tags)) (setq tags "")
14333 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14334 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14336 ;; Insert new tags at the correct column.
14337 (unless (equal current tags)
14338 (save-excursion
14339 (beginning-of-line)
14340 (let ((case-fold-search nil))
14341 (looking-at org-complex-heading-regexp))
14342 ;; Remove current tags, if any.
14343 (when (match-end 5) (replace-match "" nil nil nil 5))
14344 ;; Insert new tags, if any. Otherwise, remove trailing
14345 ;; white spaces.
14346 (end-of-line)
14347 (if (not (equal tags ""))
14348 ;; When text is being inserted on an invisible
14349 ;; region boundary, it can be inadvertently sucked
14350 ;; into invisibility.
14351 (org-flag-region (point) (progn (insert " " tags) (point))
14353 'outline)
14354 (skip-chars-backward " \t")
14355 (delete-region (point) (line-end-position)))))
14356 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14357 ;; is on.
14358 (unless (equal tags "")
14359 (let* ((level (save-excursion
14360 (beginning-of-line)
14361 (skip-chars-forward "\\*")))
14362 (offset (if (bound-and-true-p org-indent-mode)
14363 (* (1- org-indent-indentation-per-level)
14364 (1- level))
14366 (tags-column
14367 (+ org-tags-column
14368 (if (> org-tags-column 0) (- offset) offset))))
14369 (org--align-tags-here tags-column))))
14370 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14372 (defun org-change-tag-in-region (beg end tag off)
14373 "Add or remove TAG for each entry in the region.
14374 This works in the agenda, and also in an Org buffer."
14375 (interactive
14376 (list (region-beginning) (region-end)
14377 (let ((org-last-tags-completion-table
14378 (if (derived-mode-p 'org-mode)
14379 (org-uniquify
14380 (delq nil (append (org-get-buffer-tags)
14381 (org-global-tags-completion-table))))
14382 (org-global-tags-completion-table))))
14383 (completing-read
14384 "Tag: " 'org-tags-completion-function nil nil nil
14385 'org-tags-history))
14386 (progn
14387 (message "[s]et or [r]emove? ")
14388 (equal (read-char-exclusive) ?r))))
14389 (when (fboundp 'deactivate-mark) (deactivate-mark))
14390 (let ((agendap (equal major-mode 'org-agenda-mode))
14391 l1 l2 m buf pos newhead (cnt 0))
14392 (goto-char end)
14393 (setq l2 (1- (org-current-line)))
14394 (goto-char beg)
14395 (setq l1 (org-current-line))
14396 (cl-loop for l from l1 to l2 do
14397 (org-goto-line l)
14398 (setq m (get-text-property (point) 'org-hd-marker))
14399 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14400 (and agendap m))
14401 (setq buf (if agendap (marker-buffer m) (current-buffer))
14402 pos (if agendap m (point)))
14403 (with-current-buffer buf
14404 (save-excursion
14405 (save-restriction
14406 (goto-char pos)
14407 (setq cnt (1+ cnt))
14408 (org-toggle-tag tag (if off 'off 'on))
14409 (setq newhead (org-get-heading)))))
14410 (and agendap (org-agenda-change-all-lines newhead m))))
14411 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14413 (defun org-tags-completion-function (string _predicate &optional flag)
14414 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14415 (confirm (lambda (x) (stringp (car x)))))
14416 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14417 (setq s1 (match-string 1 string)
14418 s2 (match-string 2 string))
14419 (setq s1 "" s2 string))
14420 (cond
14421 ((eq flag nil)
14422 ;; try completion
14423 (setq rtn (try-completion s2 ctable confirm))
14424 (when (stringp rtn)
14425 (setq rtn
14426 (concat s1 s2 (substring rtn (length s2))
14427 (if (and org-add-colon-after-tag-completion
14428 (assoc rtn ctable))
14429 ":" ""))))
14430 rtn)
14431 ((eq flag t)
14432 ;; all-completions
14433 (all-completions s2 ctable confirm))
14434 ((eq flag 'lambda)
14435 ;; exact match?
14436 (assoc s2 ctable)))))
14438 (defun org-fast-tag-insert (kwd tags face &optional end)
14439 "Insert KDW, and the TAGS, the latter with face FACE.
14440 Also insert END."
14441 (insert (format "%-12s" (concat kwd ":"))
14442 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14443 (or end "")))
14445 (defun org-fast-tag-show-exit (flag)
14446 (save-excursion
14447 (org-goto-line 3)
14448 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14449 (replace-match ""))
14450 (when flag
14451 (end-of-line 1)
14452 (org-move-to-column (- (window-width) 19) t)
14453 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14455 (defun org-set-current-tags-overlay (current prefix)
14456 "Add an overlay to CURRENT tag with PREFIX."
14457 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14458 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14459 (org-overlay-display org-tags-overlay (concat prefix s))))
14461 (defvar org-last-tag-selection-key nil)
14462 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14463 "Fast tag selection with single keys.
14464 CURRENT is the current list of tags in the headline, INHERITED is the
14465 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14466 possibly with grouping information. TODO-TABLE is a similar table with
14467 TODO keywords, should these have keys assigned to them.
14468 If the keys are nil, a-z are automatically assigned.
14469 Returns the new tags string, or nil to not change the current settings."
14470 (let* ((fulltable (append table todo-table))
14471 (maxlen (apply 'max (mapcar
14472 (lambda (x)
14473 (if (stringp (car x)) (string-width (car x)) 0))
14474 fulltable)))
14475 (buf (current-buffer))
14476 (expert (eq org-fast-tag-selection-single-key 'expert))
14477 (buffer-tags nil)
14478 (fwidth (+ maxlen 3 1 3))
14479 (ncol (/ (- (window-width) 4) fwidth))
14480 (i-face 'org-done)
14481 (c-face 'org-todo)
14482 tg cnt e c char c1 c2 ntable tbl rtn
14483 ov-start ov-end ov-prefix
14484 (exit-after-next org-fast-tag-selection-single-key)
14485 (done-keywords org-done-keywords)
14486 groups ingroup intaggroup)
14487 (save-excursion
14488 (beginning-of-line 1)
14489 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14490 (setq ov-start (match-beginning 1)
14491 ov-end (match-end 1)
14492 ov-prefix "")
14493 (setq ov-start (1- (point-at-eol))
14494 ov-end (1+ ov-start))
14495 (skip-chars-forward "^\n\r")
14496 (setq ov-prefix
14497 (concat
14498 (buffer-substring (1- (point)) (point))
14499 (if (> (current-column) org-tags-column)
14501 (make-string (- org-tags-column (current-column)) ?\ ))))))
14502 (move-overlay org-tags-overlay ov-start ov-end)
14503 (save-window-excursion
14504 (if expert
14505 (set-buffer (get-buffer-create " *Org tags*"))
14506 (delete-other-windows)
14507 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14508 (org-switch-to-buffer-other-window " *Org tags*"))
14509 (erase-buffer)
14510 (setq-local org-done-keywords done-keywords)
14511 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14512 (org-fast-tag-insert "Current" current c-face "\n\n")
14513 (org-fast-tag-show-exit exit-after-next)
14514 (org-set-current-tags-overlay current ov-prefix)
14515 (setq tbl fulltable char ?a cnt 0)
14516 (while (setq e (pop tbl))
14517 (cond
14518 ((eq (car e) :startgroup)
14519 (push '() groups) (setq ingroup t)
14520 (unless (zerop cnt)
14521 (setq cnt 0)
14522 (insert "\n"))
14523 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14524 ((eq (car e) :endgroup)
14525 (setq ingroup nil cnt 0)
14526 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14527 ((eq (car e) :startgrouptag)
14528 (setq intaggroup t)
14529 (unless (zerop cnt)
14530 (setq cnt 0)
14531 (insert "\n"))
14532 (insert "[ "))
14533 ((eq (car e) :endgrouptag)
14534 (setq intaggroup nil cnt 0)
14535 (insert "]\n"))
14536 ((equal e '(:newline))
14537 (unless (zerop cnt)
14538 (setq cnt 0)
14539 (insert "\n")
14540 (setq e (car tbl))
14541 (while (equal (car tbl) '(:newline))
14542 (insert "\n")
14543 (setq tbl (cdr tbl)))))
14544 ((equal e '(:grouptags)) (insert " : "))
14546 (setq tg (copy-sequence (car e)) c2 nil)
14547 (if (cdr e)
14548 (setq c (cdr e))
14549 ;; automatically assign a character.
14550 (setq c1 (string-to-char
14551 (downcase (substring
14552 tg (if (= (string-to-char tg) ?@) 1 0)))))
14553 (if (or (rassoc c1 ntable) (rassoc c1 table))
14554 (while (or (rassoc char ntable) (rassoc char table))
14555 (setq char (1+ char)))
14556 (setq c2 c1))
14557 (setq c (or c2 char)))
14558 (when ingroup (push tg (car groups)))
14559 (setq tg (org-add-props tg nil 'face
14560 (cond
14561 ((not (assoc tg table))
14562 (org-get-todo-face tg))
14563 ((member tg current) c-face)
14564 ((member tg inherited) i-face))))
14565 (when (equal (caar tbl) :grouptags)
14566 (org-add-props tg nil 'face 'org-tag-group))
14567 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14568 (insert "[" c "] " tg (make-string
14569 (- fwidth 4 (length tg)) ?\ ))
14570 (push (cons tg c) ntable)
14571 (when (= (cl-incf cnt) ncol)
14572 (insert "\n")
14573 (when (or ingroup intaggroup) (insert " "))
14574 (setq cnt 0)))))
14575 (setq ntable (nreverse ntable))
14576 (insert "\n")
14577 (goto-char (point-min))
14578 (unless expert (org-fit-window-to-buffer))
14579 (setq rtn
14580 (catch 'exit
14581 (while t
14582 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14583 (if (not groups) "no " "")
14584 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14585 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14586 (setq org-last-tag-selection-key c)
14587 (cond
14588 ((= c ?\r) (throw 'exit t))
14589 ((= c ?!)
14590 (setq groups (not groups))
14591 (goto-char (point-min))
14592 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14593 ((= c ?\C-c)
14594 (if (not expert)
14595 (org-fast-tag-show-exit
14596 (setq exit-after-next (not exit-after-next)))
14597 (setq expert nil)
14598 (delete-other-windows)
14599 (set-window-buffer (split-window-vertically) " *Org tags*")
14600 (org-switch-to-buffer-other-window " *Org tags*")
14601 (org-fit-window-to-buffer)))
14602 ((or (= c ?\C-g)
14603 (and (= c ?q) (not (rassoc c ntable))))
14604 (delete-overlay org-tags-overlay)
14605 (setq quit-flag t))
14606 ((= c ?\ )
14607 (setq current nil)
14608 (when exit-after-next (setq exit-after-next 'now)))
14609 ((= c ?\t)
14610 (condition-case nil
14611 (setq tg (completing-read
14612 "Tag: "
14613 (or buffer-tags
14614 (with-current-buffer buf
14615 (setq buffer-tags
14616 (org-get-buffer-tags))))))
14617 (quit (setq tg "")))
14618 (when (string-match "\\S-" tg)
14619 (cl-pushnew (list tg) buffer-tags :test #'equal)
14620 (if (member tg current)
14621 (setq current (delete tg current))
14622 (push tg current)))
14623 (when exit-after-next (setq exit-after-next 'now)))
14624 ((setq e (rassoc c todo-table) tg (car e))
14625 (with-current-buffer buf
14626 (save-excursion (org-todo tg)))
14627 (when exit-after-next (setq exit-after-next 'now)))
14628 ((setq e (rassoc c ntable) tg (car e))
14629 (if (member tg current)
14630 (setq current (delete tg current))
14631 (cl-loop for g in groups do
14632 (when (member tg g)
14633 (dolist (x g) (setq current (delete x current)))))
14634 (push tg current))
14635 (when exit-after-next (setq exit-after-next 'now))))
14637 ;; Create a sorted list
14638 (setq current
14639 (sort current
14640 (lambda (a b)
14641 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14642 (when (eq exit-after-next 'now) (throw 'exit t))
14643 (goto-char (point-min))
14644 (beginning-of-line 2)
14645 (delete-region (point) (point-at-eol))
14646 (org-fast-tag-insert "Current" current c-face)
14647 (org-set-current-tags-overlay current ov-prefix)
14648 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14649 (setq tg (match-string 1))
14650 (add-text-properties
14651 (match-beginning 1) (match-end 1)
14652 (list 'face
14653 (cond
14654 ((member tg current) c-face)
14655 ((member tg inherited) i-face)
14656 (t (get-text-property (match-beginning 1) 'face))))))
14657 (goto-char (point-min)))))
14658 (delete-overlay org-tags-overlay)
14659 (if rtn
14660 (mapconcat 'identity current ":")
14661 nil))))
14663 (defun org-get-tags-string ()
14664 "Get the TAGS string in the current headline."
14665 (unless (org-at-heading-p t)
14666 (user-error "Not on a heading"))
14667 (save-excursion
14668 (beginning-of-line 1)
14669 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14670 (match-string-no-properties 1)
14671 "")))
14673 (defun org-get-tags ()
14674 "Get the list of tags specified in the current headline."
14675 (org-split-string (org-get-tags-string) ":"))
14677 (defun org-get-buffer-tags ()
14678 "Get a table of all tags used in the buffer, for completion."
14679 (org-with-wide-buffer
14680 (goto-char (point-min))
14681 (let ((tag-re (concat org-outline-regexp-bol
14682 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14683 tags)
14684 (while (re-search-forward tag-re nil t)
14685 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14686 (push tag tags)))
14687 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14689 ;;;; The mapping API
14691 (defvar org-agenda-skip-comment-trees)
14692 (defvar org-agenda-skip-function)
14693 (defun org-map-entries (func &optional match scope &rest skip)
14694 "Call FUNC at each headline selected by MATCH in SCOPE.
14696 FUNC is a function or a lisp form. The function will be called without
14697 arguments, with the cursor positioned at the beginning of the headline.
14698 The return values of all calls to the function will be collected and
14699 returned as a list.
14701 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14702 does not need to preserve point. After evaluation, the cursor will be
14703 moved to the end of the line (presumably of the headline of the
14704 processed entry) and search continues from there. Under some
14705 circumstances, this may not produce the wanted results. For example,
14706 if you have removed (e.g. archived) the current (sub)tree it could
14707 mean that the next entry will be skipped entirely. In such cases, you
14708 can specify the position from where search should continue by making
14709 FUNC set the variable `org-map-continue-from' to the desired buffer
14710 position.
14712 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14713 Only headlines that are matched by this query will be considered during
14714 the iteration. When MATCH is nil or t, all headlines will be
14715 visited by the iteration.
14717 SCOPE determines the scope of this command. It can be any of:
14719 nil The current buffer, respecting the restriction if any
14720 tree The subtree started with the entry at point
14721 region The entries within the active region, if any
14722 region-start-level
14723 The entries within the active region, but only those at
14724 the same level than the first one.
14725 file The current buffer, without restriction
14726 file-with-archives
14727 The current buffer, and any archives associated with it
14728 agenda All agenda files
14729 agenda-with-archives
14730 All agenda files with any archive files associated with them
14731 \(file1 file2 ...)
14732 If this is a list, all files in the list will be scanned
14734 The remaining args are treated as settings for the skipping facilities of
14735 the scanner. The following items can be given here:
14737 archive skip trees with the archive tag
14738 comment skip trees with the COMMENT keyword
14739 function or Emacs Lisp form:
14740 will be used as value for `org-agenda-skip-function', so
14741 whenever the function returns a position, FUNC will not be
14742 called for that entry and search will continue from the
14743 position returned
14745 If your function needs to retrieve the tags including inherited tags
14746 at the *current* entry, you can use the value of the variable
14747 `org-scanner-tags' which will be much faster than getting the value
14748 with `org-get-tags-at'. If your function gets properties with
14749 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14750 to t around the call to `org-entry-properties' to get the same speedup.
14751 Note that if your function moves around to retrieve tags and properties at
14752 a *different* entry, you cannot use these techniques."
14753 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14754 (not (org-region-active-p)))
14755 (let* ((org-agenda-archives-mode nil) ; just to make sure
14756 (org-agenda-skip-archived-trees (memq 'archive skip))
14757 (org-agenda-skip-comment-trees (memq 'comment skip))
14758 (org-agenda-skip-function
14759 (car (org-delete-all '(comment archive) skip)))
14760 (org-tags-match-list-sublevels t)
14761 (start-level (eq scope 'region-start-level))
14762 matcher res
14763 org-todo-keywords-for-agenda
14764 org-done-keywords-for-agenda
14765 org-todo-keyword-alist-for-agenda
14766 org-tag-alist-for-agenda
14767 org--matcher-tags-todo-only)
14769 (cond
14770 ((eq match t) (setq matcher t))
14771 ((eq match nil) (setq matcher t))
14772 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14774 (save-excursion
14775 (save-restriction
14776 (cond ((eq scope 'tree)
14777 (org-back-to-heading t)
14778 (org-narrow-to-subtree)
14779 (setq scope nil))
14780 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14781 (org-region-active-p))
14782 ;; If needed, set start-level to a string like "2"
14783 (when start-level
14784 (save-excursion
14785 (goto-char (region-beginning))
14786 (unless (org-at-heading-p) (outline-next-heading))
14787 (setq start-level (org-current-level))))
14788 (narrow-to-region (region-beginning)
14789 (save-excursion
14790 (goto-char (region-end))
14791 (unless (and (bolp) (org-at-heading-p))
14792 (outline-next-heading))
14793 (point)))
14794 (setq scope nil)))
14796 (if (not scope)
14797 (progn
14798 (org-agenda-prepare-buffers
14799 (and buffer-file-name (list buffer-file-name)))
14800 (setq res
14801 (org-scan-tags
14802 func matcher org--matcher-tags-todo-only start-level)))
14803 ;; Get the right scope
14804 (cond
14805 ((and scope (listp scope) (symbolp (car scope)))
14806 (setq scope (eval scope)))
14807 ((eq scope 'agenda)
14808 (setq scope (org-agenda-files t)))
14809 ((eq scope 'agenda-with-archives)
14810 (setq scope (org-agenda-files t))
14811 (setq scope (org-add-archive-files scope)))
14812 ((eq scope 'file)
14813 (setq scope (and buffer-file-name (list buffer-file-name))))
14814 ((eq scope 'file-with-archives)
14815 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14816 (org-agenda-prepare-buffers scope)
14817 (dolist (file scope)
14818 (with-current-buffer (org-find-base-buffer-visiting file)
14819 (org-with-wide-buffer
14820 (goto-char (point-min))
14821 (setq res
14822 (append
14824 (org-scan-tags
14825 func matcher org--matcher-tags-todo-only)))))))))
14826 res)))
14828 ;;; Properties API
14830 (defconst org-special-properties
14831 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14832 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14833 "The special properties valid in Org mode.
14834 These are properties that are not defined in the property drawer,
14835 but in some other way.")
14837 (defconst org-default-properties
14838 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14839 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14840 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14841 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14842 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14843 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14844 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14845 "Some properties that are used by Org mode for various purposes.
14846 Being in this list makes sure that they are offered for completion.")
14848 (defun org--valid-property-p (property)
14849 "Non nil when string PROPERTY is a valid property name."
14850 (not
14851 (or (equal property "")
14852 (string-match-p "\\s-" property))))
14854 (defun org--update-property-plist (key val props)
14855 "Associate KEY to VAL in alist PROPS.
14856 Modifications are made by side-effect. Return new alist."
14857 (let* ((appending (string= (substring key -1) "+"))
14858 (key (if appending (substring key 0 -1) key))
14859 (old (assoc-string key props t)))
14860 (if (not old) (cons (cons key val) props)
14861 (setcdr old (if appending (concat (cdr old) " " val) val))
14862 props)))
14864 (defun org-get-property-block (&optional beg force)
14865 "Return the (beg . end) range of the body of the property drawer.
14866 BEG is the beginning of the current subtree, or of the part
14867 before the first headline. If it is not given, it will be found.
14868 If the drawer does not exist, create it if FORCE is non-nil, or
14869 return nil."
14870 (org-with-wide-buffer
14871 (when beg (goto-char beg))
14872 (unless (org-before-first-heading-p)
14873 (let ((beg (cond (beg)
14874 ((or (not (featurep 'org-inlinetask))
14875 (org-inlinetask-in-task-p))
14876 (org-back-to-heading t))
14877 (t (org-with-limited-levels (org-back-to-heading t))))))
14878 (forward-line)
14879 (when (looking-at-p org-planning-line-re) (forward-line))
14880 (cond ((looking-at org-property-drawer-re)
14881 (forward-line)
14882 (cons (point) (progn (goto-char (match-end 0))
14883 (line-beginning-position))))
14884 (force
14885 (goto-char beg)
14886 (org-insert-property-drawer)
14887 (let ((pos (save-excursion (search-forward ":END:")
14888 (line-beginning-position))))
14889 (cons pos pos))))))))
14891 (defun org-at-property-p ()
14892 "Non-nil when point is inside a property drawer.
14893 See `org-property-re' for match data, if applicable."
14894 (save-excursion
14895 (beginning-of-line)
14896 (and (looking-at org-property-re)
14897 (let ((property-drawer (save-match-data (org-get-property-block))))
14898 (and property-drawer
14899 (>= (point) (car property-drawer))
14900 (< (point) (cdr property-drawer)))))))
14902 (defun org-property-action ()
14903 "Do an action on properties."
14904 (interactive)
14905 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14906 (let ((c (read-char-exclusive)))
14907 (cl-case c
14908 (?s (call-interactively #'org-set-property))
14909 (?d (call-interactively #'org-delete-property))
14910 (?D (call-interactively #'org-delete-property-globally))
14911 (?c (call-interactively #'org-compute-property-at-point))
14912 (otherwise (user-error "No such property action %c" c)))))
14914 (defun org-inc-effort ()
14915 "Increment the value of the effort property in the current entry."
14916 (interactive)
14917 (org-set-effort t))
14919 (defvar org-clock-effort) ; Defined in org-clock.el.
14920 (defvar org-clock-current-task) ; Defined in org-clock.el.
14921 (defun org-set-effort (&optional increment value)
14922 "Set the effort property of the current entry.
14923 If INCREMENT is non-nil, set the property to the next allowed
14924 value. Otherwise, if optional argument VALUE is provided, use
14925 it. Eventually, prompt for the new value if none of the previous
14926 variables is set."
14927 (interactive "P")
14928 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14929 (current (org-entry-get nil org-effort-property))
14930 (value
14931 (cond
14932 (increment
14933 (unless allowed (user-error "Allowed effort values are not set"))
14934 (or (cl-caadr (member (list current) allowed))
14935 (user-error "Unknown value %S among allowed values" current)))
14936 (value
14937 (if (stringp value) value
14938 (error "Invalid effort value: %S" value)))
14940 (let ((must-match
14941 (and allowed
14942 (not (get-text-property 0 'org-unrestricted
14943 (caar allowed))))))
14944 (completing-read "Effort: " allowed nil must-match))))))
14945 (unless (equal current value)
14946 (org-entry-put nil org-effort-property value))
14947 (org-refresh-property '((effort . identity)
14948 (effort-minutes . org-duration-to-minutes))
14949 value)
14950 (when (equal (org-get-heading t t t t)
14951 (bound-and-true-p org-clock-current-task))
14952 (setq org-clock-effort (org-get-at-bol 'effort))
14953 (org-clock-update-mode-line))
14954 (message "%s is now %s" org-effort-property value)))
14956 (defun org-entry-properties (&optional pom which)
14957 "Get all properties of the current entry.
14959 When POM is a buffer position, get all properties from the entry
14960 there instead.
14962 This includes the TODO keyword, the tags, time strings for
14963 deadline, scheduled, and clocking, and any additional properties
14964 defined in the entry.
14966 If WHICH is nil or `all', get all properties. If WHICH is
14967 `special' or `standard', only get that subclass. If WHICH is
14968 a string, only get that property.
14970 Return value is an alist. Keys are properties, as upcased
14971 strings."
14972 (org-with-point-at pom
14973 (when (and (derived-mode-p 'org-mode)
14974 (ignore-errors (org-back-to-heading t)))
14975 (catch 'exit
14976 (let* ((beg (point))
14977 (specific (and (stringp which) (upcase which)))
14978 (which (cond ((not specific) which)
14979 ((member specific org-special-properties) 'special)
14980 (t 'standard)))
14981 props)
14982 ;; Get the special properties, like TODO and TAGS.
14983 (when (memq which '(nil all special))
14984 (when (or (not specific) (string= specific "CLOCKSUM"))
14985 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
14986 (when clocksum
14987 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
14988 props)))
14989 (when specific (throw 'exit props)))
14990 (when (or (not specific) (string= specific "CLOCKSUM_T"))
14991 (let ((clocksumt (get-text-property (point)
14992 :org-clock-minutes-today)))
14993 (when clocksumt
14994 (push (cons "CLOCKSUM_T"
14995 (org-duration-from-minutes clocksumt))
14996 props)))
14997 (when specific (throw 'exit props)))
14998 (when (or (not specific) (string= specific "ITEM"))
14999 (let ((case-fold-search nil))
15000 (when (looking-at org-complex-heading-regexp)
15001 (push (cons "ITEM"
15002 (let ((title (match-string-no-properties 4)))
15003 (if (org-string-nw-p title)
15004 (org-remove-tabs title)
15005 "")))
15006 props)))
15007 (when specific (throw 'exit props)))
15008 (when (or (not specific) (string= specific "TODO"))
15009 (let ((case-fold-search nil))
15010 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15011 (push (cons "TODO" (match-string-no-properties 2)) props)))
15012 (when specific (throw 'exit props)))
15013 (when (or (not specific) (string= specific "PRIORITY"))
15014 (push (cons "PRIORITY"
15015 (if (looking-at org-priority-regexp)
15016 (match-string-no-properties 2)
15017 (char-to-string org-default-priority)))
15018 props)
15019 (when specific (throw 'exit props)))
15020 (when (or (not specific) (string= specific "FILE"))
15021 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15022 props)
15023 (when specific (throw 'exit props)))
15024 (when (or (not specific) (string= specific "TAGS"))
15025 (let ((value (org-string-nw-p (org-get-tags-string))))
15026 (when value (push (cons "TAGS" value) props)))
15027 (when specific (throw 'exit props)))
15028 (when (or (not specific) (string= specific "ALLTAGS"))
15029 (let ((value (org-get-tags-at)))
15030 (when value
15031 (push (cons "ALLTAGS"
15032 (format ":%s:" (mapconcat #'identity value ":")))
15033 props)))
15034 (when specific (throw 'exit props)))
15035 (when (or (not specific) (string= specific "BLOCKED"))
15036 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15037 (when specific (throw 'exit props)))
15038 (when (or (not specific)
15039 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15040 (forward-line)
15041 (when (looking-at-p org-planning-line-re)
15042 (end-of-line)
15043 (let ((bol (line-beginning-position))
15044 ;; Backward compatibility: time keywords used to
15045 ;; be configurable (before 8.3). Make sure we
15046 ;; get the correct keyword.
15047 (key-assoc `(("CLOSED" . ,org-closed-string)
15048 ("DEADLINE" . ,org-deadline-string)
15049 ("SCHEDULED" . ,org-scheduled-string))))
15050 (dolist (pair (if specific (list (assoc specific key-assoc))
15051 key-assoc))
15052 (save-excursion
15053 (when (search-backward (cdr pair) bol t)
15054 (goto-char (match-end 0))
15055 (skip-chars-forward " \t")
15056 (and (looking-at org-ts-regexp-both)
15057 (push (cons (car pair)
15058 (match-string-no-properties 0))
15059 props)))))))
15060 (when specific (throw 'exit props)))
15061 (when (or (not specific)
15062 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15063 (let ((find-ts
15064 (lambda (end ts)
15065 ;; Fix next time-stamp before END. TS is the
15066 ;; list of time-stamps found so far.
15067 (let ((ts ts)
15068 (regexp (cond
15069 ((string= specific "TIMESTAMP")
15070 org-ts-regexp)
15071 ((string= specific "TIMESTAMP_IA")
15072 org-ts-regexp-inactive)
15073 ((assoc "TIMESTAMP_IA" ts)
15074 org-ts-regexp)
15075 ((assoc "TIMESTAMP" ts)
15076 org-ts-regexp-inactive)
15077 (t org-ts-regexp-both))))
15078 (catch 'next
15079 (while (re-search-forward regexp end t)
15080 (backward-char)
15081 (let ((object (org-element-context)))
15082 ;; Accept to match timestamps in node
15083 ;; properties, too.
15084 (when (memq (org-element-type object)
15085 '(node-property timestamp))
15086 (let ((type
15087 (org-element-property :type object)))
15088 (cond
15089 ((and (memq type '(active active-range))
15090 (not (equal specific "TIMESTAMP_IA")))
15091 (unless (assoc "TIMESTAMP" ts)
15092 (push (cons "TIMESTAMP"
15093 (org-element-property
15094 :raw-value object))
15096 (when specific (throw 'exit ts))))
15097 ((and (memq type '(inactive inactive-range))
15098 (not (string= specific "TIMESTAMP")))
15099 (unless (assoc "TIMESTAMP_IA" ts)
15100 (push (cons "TIMESTAMP_IA"
15101 (org-element-property
15102 :raw-value object))
15104 (when specific (throw 'exit ts))))))
15105 ;; Both timestamp types are found,
15106 ;; move to next part.
15107 (when (= (length ts) 2) (throw 'next ts)))))
15108 ts)))))
15109 (goto-char beg)
15110 ;; First look for timestamps within headline.
15111 (let ((ts (funcall find-ts (line-end-position) nil)))
15112 (if (= (length ts) 2) (setq props (nconc ts props))
15113 ;; Then find timestamps in the section, skipping
15114 ;; planning line.
15115 (let ((end (save-excursion (outline-next-heading))))
15116 (forward-line)
15117 (when (looking-at-p org-planning-line-re) (forward-line))
15118 (setq props (nconc (funcall find-ts end ts) props))))))))
15119 ;; Get the standard properties, like :PROP:.
15120 (when (memq which '(nil all standard))
15121 ;; If we are looking after a specific property, delegate
15122 ;; to `org-entry-get', which is faster. However, make an
15123 ;; exception for "CATEGORY", since it can be also set
15124 ;; through keywords (i.e. #+CATEGORY).
15125 (if (and specific (not (equal specific "CATEGORY")))
15126 (let ((value (org-entry-get beg specific nil t)))
15127 (throw 'exit (and value (list (cons specific value)))))
15128 (let ((range (org-get-property-block beg)))
15129 (when range
15130 (let ((end (cdr range)) seen-base)
15131 (goto-char (car range))
15132 ;; Unlike to `org--update-property-plist', we
15133 ;; handle the case where base values is found
15134 ;; after its extension. We also forbid standard
15135 ;; properties to be named as special properties.
15136 (while (re-search-forward org-property-re end t)
15137 (let* ((key (upcase (match-string-no-properties 2)))
15138 (extendp (string-match-p "\\+\\'" key))
15139 (key-base (if extendp (substring key 0 -1) key))
15140 (value (match-string-no-properties 3)))
15141 (cond
15142 ((member-ignore-case key-base org-special-properties))
15143 (extendp
15144 (setq props
15145 (org--update-property-plist key value props)))
15146 ((member key seen-base))
15147 (t (push key seen-base)
15148 (let ((p (assoc-string key props t)))
15149 (if p (setcdr p (concat value " " (cdr p)))
15150 (push (cons key value) props))))))))))))
15151 (unless (assoc "CATEGORY" props)
15152 (push (cons "CATEGORY" (org-get-category beg)) props)
15153 (when (string= specific "CATEGORY") (throw 'exit props)))
15154 ;; Return value.
15155 props)))))
15157 (defun org--property-local-values (property literal-nil)
15158 "Return value for PROPERTY in current entry.
15159 Value is a list whose car is the base value for PROPERTY and cdr
15160 a list of accumulated values. Return nil if neither is found in
15161 the entry. Also return nil when PROPERTY is set to \"nil\",
15162 unless LITERAL-NIL is non-nil."
15163 (let ((range (org-get-property-block)))
15164 (when range
15165 (goto-char (car range))
15166 (let* ((case-fold-search t)
15167 (end (cdr range))
15168 (value
15169 ;; Base value.
15170 (save-excursion
15171 (let ((v (and (re-search-forward
15172 (org-re-property property nil t) end t)
15173 (match-string-no-properties 3))))
15174 (list (if literal-nil v (org-not-nil v)))))))
15175 ;; Find additional values.
15176 (let* ((property+ (org-re-property (concat property "+") nil t)))
15177 (while (re-search-forward property+ end t)
15178 (push (match-string-no-properties 3) value)))
15179 ;; Return final values.
15180 (and (not (equal value '(nil))) (nreverse value))))))
15182 (defun org--property-global-value (property literal-nil)
15183 "Return value for PROPERTY in current buffer.
15184 Return value is a string. Return nil if property is not set
15185 globally. Also return nil when PROPERTY is set to \"nil\",
15186 unless LITERAL-NIL is non-nil."
15187 (let ((global
15188 (cdr (or (assoc-string property org-file-properties t)
15189 (assoc-string property org-global-properties t)
15190 (assoc-string property org-global-properties-fixed t)))))
15191 (if literal-nil global (org-not-nil global))))
15193 (defun org-entry-get (pom property &optional inherit literal-nil)
15194 "Get value of PROPERTY for entry or content at point-or-marker POM.
15196 If INHERIT is non-nil and the entry does not have the property,
15197 then also check higher levels of the hierarchy. If INHERIT is
15198 the symbol `selective', use inheritance only if the setting in
15199 `org-use-property-inheritance' selects PROPERTY for inheritance.
15201 If the property is present but empty, the return value is the
15202 empty string. If the property is not present at all, nil is
15203 returned. In any other case, return the value as a string.
15204 Search is case-insensitive.
15206 If LITERAL-NIL is set, return the string value \"nil\" as
15207 a string, do not interpret it as the list atom nil. This is used
15208 for inheritance when a \"nil\" value can supersede a non-nil
15209 value higher up the hierarchy."
15210 (org-with-point-at pom
15211 (cond
15212 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15213 ;; We need a special property. Use `org-entry-properties' to
15214 ;; retrieve it, but specify the wanted property.
15215 (cdr (assoc-string property (org-entry-properties nil property))))
15216 ((and inherit
15217 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15218 (org-entry-get-with-inheritance property literal-nil))
15220 (let* ((local (org--property-local-values property literal-nil))
15221 (value (and local (mapconcat #'identity (delq nil local) " "))))
15222 (if literal-nil value (org-not-nil value)))))))
15224 (defun org-property-or-variable-value (var &optional inherit)
15225 "Check if there is a property fixing the value of VAR.
15226 If yes, return this value. If not, return the current value of the variable."
15227 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15228 (if (and prop (stringp prop) (string-match "\\S-" prop))
15229 (read prop)
15230 (symbol-value var))))
15232 (defun org-entry-delete (pom property)
15233 "Delete PROPERTY from entry at point-or-marker POM.
15234 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15235 non-nil when a property was removed."
15236 (org-with-point-at pom
15237 (pcase (org-get-property-block)
15238 (`(,begin . ,origin)
15239 (let* ((end (copy-marker origin))
15240 (re (org-re-property
15241 (concat (regexp-quote property) "\\+?") t t)))
15242 (goto-char begin)
15243 (while (re-search-forward re end t)
15244 (delete-region (match-beginning 0) (line-beginning-position 2)))
15245 ;; If drawer is empty, remove it altogether.
15246 (when (= begin end)
15247 (delete-region (line-beginning-position 0)
15248 (line-beginning-position 2)))
15249 ;; Return non-nil if some property was removed.
15250 (prog1 (/= end origin) (set-marker end nil))))
15251 (_ nil))))
15253 ;; Multi-values properties are properties that contain multiple values
15254 ;; These values are assumed to be single words, separated by whitespace.
15255 (defun org-entry-add-to-multivalued-property (pom property value)
15256 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15257 (let* ((old (org-entry-get pom property))
15258 (values (and old (split-string old))))
15259 (setq value (org-entry-protect-space value))
15260 (unless (member value values)
15261 (setq values (append values (list value)))
15262 (org-entry-put pom property (mapconcat #'identity values " ")))))
15264 (defun org-entry-remove-from-multivalued-property (pom property value)
15265 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15266 (let* ((old (org-entry-get pom property))
15267 (values (and old (split-string old))))
15268 (setq value (org-entry-protect-space value))
15269 (when (member value values)
15270 (setq values (delete value values))
15271 (org-entry-put pom property (mapconcat #'identity values " ")))))
15273 (defun org-entry-member-in-multivalued-property (pom property value)
15274 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15275 (let* ((old (org-entry-get pom property))
15276 (values (and old (split-string old))))
15277 (setq value (org-entry-protect-space value))
15278 (member value values)))
15280 (defun org-entry-get-multivalued-property (pom property)
15281 "Return a list of values in a multivalued property."
15282 (let* ((value (org-entry-get pom property))
15283 (values (and value (split-string value))))
15284 (mapcar #'org-entry-restore-space values)))
15286 (defun org-entry-put-multivalued-property (pom property &rest values)
15287 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15288 VALUES should be a list of strings. Spaces will be protected."
15289 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15290 (let* ((value (org-entry-get pom property))
15291 (values (and value (split-string value))))
15292 (mapcar #'org-entry-restore-space values)))
15294 (defun org-entry-protect-space (s)
15295 "Protect spaces and newline in string S."
15296 (while (string-match " " s)
15297 (setq s (replace-match "%20" t t s)))
15298 (while (string-match "\n" s)
15299 (setq s (replace-match "%0A" t t s)))
15302 (defun org-entry-restore-space (s)
15303 "Restore spaces and newline in string S."
15304 (while (string-match "%20" s)
15305 (setq s (replace-match " " t t s)))
15306 (while (string-match "%0A" s)
15307 (setq s (replace-match "\n" t t s)))
15310 (defvar org-entry-property-inherited-from (make-marker)
15311 "Marker pointing to the entry from where a property was inherited.
15312 Each call to `org-entry-get-with-inheritance' will set this marker to the
15313 location of the entry where the inheritance search matched. If there was
15314 no match, the marker will point nowhere.
15315 Note that also `org-entry-get' calls this function, if the INHERIT flag
15316 is set.")
15318 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15319 "Get PROPERTY of entry or content at point, search higher levels if needed.
15320 The search will stop at the first ancestor which has the property defined.
15321 If the value found is \"nil\", return nil to show that the property
15322 should be considered as undefined (this is the meaning of nil here).
15323 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15324 (move-marker org-entry-property-inherited-from nil)
15325 (org-with-wide-buffer
15326 (let (value)
15327 (catch 'exit
15328 (while t
15329 (let ((v (org--property-local-values property literal-nil)))
15330 (when v
15331 (setq value
15332 (concat (mapconcat #'identity (delq nil v) " ")
15333 (and value " ")
15334 value)))
15335 (cond
15336 ((car v)
15337 (org-back-to-heading t)
15338 (move-marker org-entry-property-inherited-from (point))
15339 (throw 'exit nil))
15340 ((org-up-heading-safe))
15342 (let ((global (org--property-global-value property literal-nil)))
15343 (cond ((not global))
15344 (value (setq value (concat global " " value)))
15345 (t (setq value global))))
15346 (throw 'exit nil))))))
15347 (if literal-nil value (org-not-nil value)))))
15349 (defvar org-property-changed-functions nil
15350 "Hook called when the value of a property has changed.
15351 Each hook function should accept two arguments, the name of the property
15352 and the new value.")
15354 (defun org-entry-put (pom property value)
15355 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15357 If the value is nil, it is converted to the empty string. If it
15358 is not a string, an error is raised. Also raise an error on
15359 invalid property names.
15361 PROPERTY can be any regular property (see
15362 `org-special-properties'). It can also be \"TODO\",
15363 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15365 For the last two properties, VALUE may have any of the special
15366 values \"earlier\" and \"later\". The function then increases or
15367 decreases scheduled or deadline date by one day."
15368 (cond ((null value) (setq value ""))
15369 ((not (stringp value)) (error "Properties values should be strings"))
15370 ((not (org--valid-property-p property))
15371 (user-error "Invalid property name: \"%s\"" property)))
15372 (org-with-point-at pom
15373 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15374 (org-back-to-heading t)
15375 (org-with-limited-levels (org-back-to-heading t)))
15376 (let ((beg (point)))
15377 (cond
15378 ((equal property "TODO")
15379 (cond ((not (org-string-nw-p value)) (setq value 'none))
15380 ((not (member value org-todo-keywords-1))
15381 (user-error "\"%s\" is not a valid TODO state" value)))
15382 (org-todo value)
15383 (org-set-tags nil 'align))
15384 ((equal property "PRIORITY")
15385 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15386 (org-set-tags nil 'align))
15387 ((equal property "SCHEDULED")
15388 (forward-line)
15389 (if (and (looking-at-p org-planning-line-re)
15390 (re-search-forward
15391 org-scheduled-time-regexp (line-end-position) t))
15392 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15393 ((string= value "later") (org-timestamp-change 1 'day))
15394 ((string= value "") (org-schedule '(4)))
15395 (t (org-schedule nil value)))
15396 (if (member value '("earlier" "later" ""))
15397 (call-interactively #'org-schedule)
15398 (org-schedule nil value))))
15399 ((equal property "DEADLINE")
15400 (forward-line)
15401 (if (and (looking-at-p org-planning-line-re)
15402 (re-search-forward
15403 org-deadline-time-regexp (line-end-position) t))
15404 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15405 ((string= value "later") (org-timestamp-change 1 'day))
15406 ((string= value "") (org-deadline '(4)))
15407 (t (org-deadline nil value)))
15408 (if (member value '("earlier" "later" ""))
15409 (call-interactively #'org-deadline)
15410 (org-deadline nil value))))
15411 ((member property org-special-properties)
15412 (error "The %s property cannot be set with `org-entry-put'" property))
15414 (let* ((range (org-get-property-block beg 'force))
15415 (end (cdr range))
15416 (case-fold-search t))
15417 (goto-char (car range))
15418 (if (re-search-forward (org-re-property property nil t) end t)
15419 (progn (delete-region (match-beginning 0) (match-end 0))
15420 (goto-char (match-beginning 0)))
15421 (goto-char end)
15422 (insert "\n")
15423 (backward-char))
15424 (insert ":" property ":")
15425 (when value (insert " " value))
15426 (org-indent-line)))))
15427 (run-hook-with-args 'org-property-changed-functions property value)))
15429 (defun org-buffer-property-keys (&optional specials defaults columns)
15430 "Get all property keys in the current buffer.
15432 When SPECIALS is non-nil, also list the special properties that
15433 reflect things like tags and TODO state.
15435 When DEFAULTS is non-nil, also include properties that has
15436 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15437 DESCRIPTION, LOCATION, and LOGGING and others.
15439 When COLUMNS in non-nil, also include property names given in
15440 COLUMN formats in the current buffer."
15441 (let ((case-fold-search t)
15442 (props (append
15443 (and specials org-special-properties)
15444 (and defaults (cons org-effort-property org-default-properties))
15445 nil)))
15446 (org-with-wide-buffer
15447 (goto-char (point-min))
15448 (while (re-search-forward org-property-start-re nil t)
15449 (catch :skip
15450 (let ((range (org-get-property-block)))
15451 (unless range (throw :skip nil))
15452 (goto-char (car range))
15453 (let ((begin (car range))
15454 (end (cdr range)))
15455 ;; Make sure that found property block is not located
15456 ;; before current point, as it would generate an infloop.
15457 ;; It can happen, for example, in the following
15458 ;; situation:
15460 ;; * Headline
15461 ;; :PROPERTIES:
15462 ;; ...
15463 ;; :END:
15464 ;; *************** Inlinetask
15465 ;; #+BEGIN_EXAMPLE
15466 ;; :PROPERTIES:
15467 ;; #+END_EXAMPLE
15469 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15470 (while (< (point) end)
15471 (let ((p (progn (looking-at org-property-re)
15472 (match-string-no-properties 2))))
15473 ;; Only add true property name, not extension symbol.
15474 (push (if (not (string-match-p "\\+\\'" p)) p
15475 (substring p 0 -1))
15476 props))
15477 (forward-line))))
15478 (outline-next-heading)))
15479 (when columns
15480 (goto-char (point-min))
15481 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15482 (let ((element (org-element-at-point)))
15483 (when (memq (org-element-type element) '(keyword node-property))
15484 (let ((value (org-element-property :value element))
15485 (start 0))
15486 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15487 \\(?:{[^}]+}\\)?"
15488 value start)
15489 (setq start (match-end 0))
15490 (let ((p (match-string-no-properties 1 value)))
15491 (unless (member-ignore-case p org-special-properties)
15492 (push p props))))))))))
15493 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15495 (defun org-property-values (key)
15496 "List all non-nil values of property KEY in current buffer."
15497 (org-with-wide-buffer
15498 (goto-char (point-min))
15499 (let ((case-fold-search t)
15500 (re (org-re-property key))
15501 values)
15502 (while (re-search-forward re nil t)
15503 (push (org-entry-get (point) key) values))
15504 (delete-dups values))))
15506 (defun org-insert-property-drawer ()
15507 "Insert a property drawer into the current entry."
15508 (org-with-wide-buffer
15509 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15510 (org-back-to-heading t)
15511 (org-with-limited-levels (org-back-to-heading t)))
15512 (forward-line)
15513 (when (looking-at-p org-planning-line-re) (forward-line))
15514 (unless (looking-at-p org-property-drawer-re)
15515 ;; Make sure we start editing a line from current entry, not from
15516 ;; next one. It prevents extending text properties or overlays
15517 ;; belonging to the latter.
15518 (when (bolp) (backward-char))
15519 (let ((begin (1+ (point)))
15520 (inhibit-read-only t))
15521 (insert "\n:PROPERTIES:\n:END:")
15522 (when (eobp) (insert "\n"))
15523 (org-indent-region begin (point))))))
15525 (defun org-insert-drawer (&optional arg drawer)
15526 "Insert a drawer at point.
15528 When optional argument ARG is non-nil, insert a property drawer.
15530 Optional argument DRAWER, when non-nil, is a string representing
15531 drawer's name. Otherwise, the user is prompted for a name.
15533 If a region is active, insert the drawer around that region
15534 instead.
15536 Point is left between drawer's boundaries."
15537 (interactive "P")
15538 (let* ((drawer (if arg "PROPERTIES"
15539 (or drawer (read-from-minibuffer "Drawer: ")))))
15540 (cond
15541 ;; With C-u, fall back on `org-insert-property-drawer'
15542 (arg (org-insert-property-drawer))
15543 ;; Check validity of suggested drawer's name.
15544 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15545 (user-error "Invalid drawer name"))
15546 ;; With an active region, insert a drawer at point.
15547 ((not (org-region-active-p))
15548 (progn
15549 (unless (bolp) (insert "\n"))
15550 (insert (format ":%s:\n\n:END:\n" drawer))
15551 (forward-line -2)))
15552 ;; Otherwise, insert the drawer at point
15554 (let ((rbeg (region-beginning))
15555 (rend (copy-marker (region-end))))
15556 (unwind-protect
15557 (progn
15558 (goto-char rbeg)
15559 (beginning-of-line)
15560 (when (save-excursion
15561 (re-search-forward org-outline-regexp-bol rend t))
15562 (user-error "Drawers cannot contain headlines"))
15563 ;; Position point at the beginning of the first
15564 ;; non-blank line in region. Insert drawer's opening
15565 ;; there, then indent it.
15566 (org-skip-whitespace)
15567 (beginning-of-line)
15568 (insert ":" drawer ":\n")
15569 (forward-line -1)
15570 (indent-for-tab-command)
15571 ;; Move point to the beginning of the first blank line
15572 ;; after the last non-blank line in region. Insert
15573 ;; drawer's closing, then indent it.
15574 (goto-char rend)
15575 (skip-chars-backward " \r\t\n")
15576 (insert "\n:END:")
15577 (deactivate-mark t)
15578 (indent-for-tab-command)
15579 (unless (eolp) (insert "\n")))
15580 ;; Clear marker, whatever the outcome of insertion is.
15581 (set-marker rend nil)))))))
15583 (defvar org-property-set-functions-alist nil
15584 "Property set function alist.
15585 Each entry should have the following format:
15587 (PROPERTY . READ-FUNCTION)
15589 The read function will be called with the same argument as
15590 `org-completing-read'.")
15592 (defun org-set-property-function (property)
15593 "Get the function that should be used to set PROPERTY.
15594 This is computed according to `org-property-set-functions-alist'."
15595 (or (cdr (assoc property org-property-set-functions-alist))
15596 'org-completing-read))
15598 (defun org-read-property-value (property)
15599 "Read PROPERTY value from user."
15600 (let* ((completion-ignore-case t)
15601 (allowed (org-property-get-allowed-values nil property 'table))
15602 (cur (org-entry-get nil property))
15603 (prompt (concat property " value"
15604 (if (and cur (string-match "\\S-" cur))
15605 (concat " [" cur "]") "") ": "))
15606 (set-function (org-set-property-function property))
15607 (val (if allowed
15608 (funcall set-function prompt allowed nil
15609 (not (get-text-property 0 'org-unrestricted
15610 (caar allowed))))
15611 (funcall set-function prompt
15612 (mapcar 'list (org-property-values property))
15613 nil nil "" nil cur))))
15614 (org-trim val)))
15616 (defvar org-last-set-property nil)
15617 (defvar org-last-set-property-value nil)
15618 (defun org-read-property-name ()
15619 "Read a property name."
15620 (let ((completion-ignore-case t)
15621 (default-prop (or (and (org-at-property-p)
15622 (match-string-no-properties 2))
15623 org-last-set-property)))
15624 (org-completing-read
15625 (concat "Property"
15626 (if default-prop (concat " [" default-prop "]") "")
15627 ": ")
15628 (mapcar #'list (org-buffer-property-keys nil t t))
15629 nil nil nil nil default-prop)))
15631 (defun org-set-property-and-value (use-last)
15632 "Allow to set [PROPERTY]: [value] direction from prompt.
15633 When use-default, don't even ask, just use the last
15634 \"[PROPERTY]: [value]\" string from the history."
15635 (interactive "P")
15636 (let* ((completion-ignore-case t)
15637 (pv (or (and use-last org-last-set-property-value)
15638 (org-completing-read
15639 "Enter a \"[Property]: [value]\" pair: "
15640 nil nil nil nil nil
15641 org-last-set-property-value)))
15642 prop val)
15643 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15644 (setq prop (match-string 1 pv)
15645 val (match-string 2 pv))
15646 (org-set-property prop val))))
15648 (defun org-set-property (property value)
15649 "In the current entry, set PROPERTY to VALUE.
15651 When called interactively, this will prompt for a property name, offering
15652 completion on existing and default properties. And then it will prompt
15653 for a value, offering completion either on allowed values (via an inherited
15654 xxx_ALL property) or on existing values in other instances of this property
15655 in the current file.
15657 Throw an error when trying to set a property with an invalid name."
15658 (interactive (list nil nil))
15659 (let ((property (or property (org-read-property-name))))
15660 ;; `org-entry-put' also makes the following check, but this one
15661 ;; avoids polluting `org-last-set-property' and
15662 ;; `org-last-set-property-value' needlessly.
15663 (unless (org--valid-property-p property)
15664 (user-error "Invalid property name: \"%s\"" property))
15665 (let ((value (or value (org-read-property-value property)))
15666 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15667 (setq org-last-set-property property)
15668 (setq org-last-set-property-value (concat property ": " value))
15669 ;; Possibly postprocess the inserted value:
15670 (when fn (setq value (funcall fn value)))
15671 (unless (equal (org-entry-get nil property) value)
15672 (org-entry-put nil property value)))))
15674 (defun org-find-property (property &optional value)
15675 "Find first entry in buffer that sets PROPERTY.
15677 When optional argument VALUE is non-nil, only consider an entry
15678 if it contains PROPERTY set to this value. If PROPERTY should be
15679 explicitly set to nil, use string \"nil\" for VALUE.
15681 Return position where the entry begins, or nil if there is no
15682 such entry. If narrowing is in effect, only search the visible
15683 part of the buffer."
15684 (save-excursion
15685 (goto-char (point-min))
15686 (let ((case-fold-search t)
15687 (re (org-re-property property nil (not value) value)))
15688 (catch 'exit
15689 (while (re-search-forward re nil t)
15690 (when (if value (org-at-property-p)
15691 (org-entry-get (point) property nil t))
15692 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15694 (defun org-delete-property (property)
15695 "In the current entry, delete PROPERTY."
15696 (interactive
15697 (let* ((completion-ignore-case t)
15698 (cat (org-entry-get (point) "CATEGORY"))
15699 (props0 (org-entry-properties nil 'standard))
15700 (props (if cat props0
15701 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15702 (prop (if (< 1 (length props))
15703 (completing-read "Property: " props nil t)
15704 (caar props))))
15705 (list prop)))
15706 (if (not property)
15707 (message "No property to delete in this entry")
15708 (org-entry-delete nil property)
15709 (message "Property \"%s\" deleted" property)))
15711 (defun org-delete-property-globally (property)
15712 "Remove PROPERTY globally, from all entries.
15713 This function ignores narrowing, if any."
15714 (interactive
15715 (let* ((completion-ignore-case t)
15716 (prop (completing-read
15717 "Globally remove property: "
15718 (mapcar #'list (org-buffer-property-keys)))))
15719 (list prop)))
15720 (org-with-wide-buffer
15721 (goto-char (point-min))
15722 (let ((count 0)
15723 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15724 (while (re-search-forward re nil t)
15725 (when (org-entry-delete (point) property) (cl-incf count)))
15726 (message "Property \"%s\" removed from %d entries" property count))))
15728 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15730 (defun org-compute-property-at-point ()
15731 "Compute the property at point.
15732 This looks for an enclosing column format, extracts the operator and
15733 then applies it to the property in the column format's scope."
15734 (interactive)
15735 (unless (org-at-property-p)
15736 (user-error "Not at a property"))
15737 (let ((prop (match-string-no-properties 2)))
15738 (org-columns-get-format-and-top-level)
15739 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15740 (user-error "No operator defined for property %s" prop))
15741 (org-columns-compute prop)))
15743 (defvar org-property-allowed-value-functions nil
15744 "Hook for functions supplying allowed values for a specific property.
15745 The functions must take a single argument, the name of the property, and
15746 return a flat list of allowed values. If \":ETC\" is one of
15747 the values, this means that these values are intended as defaults for
15748 completion, but that other values should be allowed too.
15749 The functions must return nil if they are not responsible for this
15750 property.")
15752 (defun org-property-get-allowed-values (pom property &optional table)
15753 "Get allowed values for the property PROPERTY.
15754 When TABLE is non-nil, return an alist that can directly be used for
15755 completion."
15756 (let (vals)
15757 (cond
15758 ((equal property "TODO")
15759 (setq vals (org-with-point-at pom
15760 (append org-todo-keywords-1 '("")))))
15761 ((equal property "PRIORITY")
15762 (let ((n org-lowest-priority))
15763 (while (>= n org-highest-priority)
15764 (push (char-to-string n) vals)
15765 (setq n (1- n)))))
15766 ((equal property "CATEGORY"))
15767 ((member property org-special-properties))
15768 ((setq vals (run-hook-with-args-until-success
15769 'org-property-allowed-value-functions property)))
15771 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15772 (when (and vals (string-match "\\S-" vals))
15773 (setq vals (car (read-from-string (concat "(" vals ")"))))
15774 (setq vals (mapcar (lambda (x)
15775 (cond ((stringp x) x)
15776 ((numberp x) (number-to-string x))
15777 ((symbolp x) (symbol-name x))
15778 (t "???")))
15779 vals)))))
15780 (when (member ":ETC" vals)
15781 (setq vals (remove ":ETC" vals))
15782 (org-add-props (car vals) '(org-unrestricted t)))
15783 (if table (mapcar 'list vals) vals)))
15785 (defun org-property-previous-allowed-value (&optional _previous)
15786 "Switch to the next allowed value for this property."
15787 (interactive)
15788 (org-property-next-allowed-value t))
15790 (defun org-property-next-allowed-value (&optional previous)
15791 "Switch to the next allowed value for this property."
15792 (interactive)
15793 (unless (org-at-property-p)
15794 (user-error "Not at a property"))
15795 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15796 (key (match-string 2))
15797 (value (match-string 3))
15798 (allowed (or (org-property-get-allowed-values (point) key)
15799 (and (member value '("[ ]" "[-]" "[X]"))
15800 '("[ ]" "[X]"))))
15801 (heading (save-match-data (nth 4 (org-heading-components))))
15802 nval)
15803 (unless allowed
15804 (user-error "Allowed values for this property have not been defined"))
15805 (when previous (setq allowed (reverse allowed)))
15806 (when (member value allowed)
15807 (setq nval (car (cdr (member value allowed)))))
15808 (setq nval (or nval (car allowed)))
15809 (when (equal nval value)
15810 (user-error "Only one allowed value for this property"))
15811 (org-at-property-p)
15812 (replace-match (concat " :" key ": " nval) t t)
15813 (org-indent-line)
15814 (beginning-of-line 1)
15815 (skip-chars-forward " \t")
15816 (when (equal prop org-effort-property)
15817 (org-refresh-property
15818 '((effort . identity)
15819 (effort-minutes . org-duration-to-minutes))
15820 nval)
15821 (when (string= org-clock-current-task heading)
15822 (setq org-clock-effort nval)
15823 (org-clock-update-mode-line)))
15824 (run-hook-with-args 'org-property-changed-functions key nval)))
15826 (defun org-find-olp (path &optional this-buffer)
15827 "Return a marker pointing to the entry at outline path OLP.
15828 If anything goes wrong, throw an error.
15829 You can wrap this call to catch the error like this:
15831 (condition-case msg
15832 (org-mobile-locate-entry (match-string 4))
15833 (error (nth 1 msg)))
15835 The return value will then be either a string with the error message,
15836 or a marker if everything is OK.
15838 If THIS-BUFFER is set, the outline path does not contain a file,
15839 only headings."
15840 (let* ((file (if this-buffer buffer-file-name (pop path)))
15841 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15842 (level 1)
15843 (lmin 1)
15844 (lmax 1)
15845 end found flevel)
15846 (unless buffer (error "File not found :%s" file))
15847 (with-current-buffer buffer
15848 (unless (derived-mode-p 'org-mode)
15849 (error "Buffer %s needs to be in Org mode" buffer))
15850 (org-with-wide-buffer
15851 (goto-char (point-min))
15852 (dolist (heading path)
15853 (let ((re (format org-complex-heading-regexp-format
15854 (regexp-quote heading)))
15855 (cnt 0))
15856 (while (re-search-forward re end t)
15857 (setq level (- (match-end 1) (match-beginning 1)))
15858 (when (and (>= level lmin) (<= level lmax))
15859 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15860 (when (= cnt 0)
15861 (error "Heading not found on level %d: %s" lmax heading))
15862 (when (> cnt 1)
15863 (error "Heading not unique on level %d: %s" lmax heading))
15864 (goto-char found)
15865 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15866 (setq end (save-excursion (org-end-of-subtree t t)))))
15867 (when (org-at-heading-p)
15868 (point-marker))))))
15870 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15871 "Find node HEADING in BUFFER.
15872 Return a marker to the heading if it was found, or nil if not.
15873 If POS-ONLY is set, return just the position instead of a marker.
15875 The heading text must match exact, but it may have a TODO keyword,
15876 a priority cookie and tags in the standard locations."
15877 (with-current-buffer (or buffer (current-buffer))
15878 (org-with-wide-buffer
15879 (goto-char (point-min))
15880 (let (case-fold-search)
15881 (when (re-search-forward
15882 (format org-complex-heading-regexp-format
15883 (regexp-quote heading)) nil t)
15884 (if pos-only
15885 (match-beginning 0)
15886 (move-marker (make-marker) (match-beginning 0))))))))
15888 (defun org-find-exact-heading-in-directory (heading &optional dir)
15889 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15890 When the target headline is found, return a marker to this location."
15891 (let ((files (directory-files (or dir default-directory)
15892 t "\\`[^.#].*\\.org\\'"))
15893 visiting m buffer)
15894 (catch 'found
15895 (dolist (file files)
15896 (message "trying %s" file)
15897 (setq visiting (org-find-base-buffer-visiting file))
15898 (setq buffer (or visiting (find-file-noselect file)))
15899 (setq m (org-find-exact-headline-in-buffer
15900 heading buffer))
15901 (when (and (not m) (not visiting)) (kill-buffer buffer))
15902 (and m (throw 'found m))))))
15904 (defun org-find-entry-with-id (ident)
15905 "Locate the entry that contains the ID property with exact value IDENT.
15906 IDENT can be a string, a symbol or a number, this function will search for
15907 the string representation of it.
15908 Return the position where this entry starts, or nil if there is no such entry."
15909 (interactive "sID: ")
15910 (let ((id (cond
15911 ((stringp ident) ident)
15912 ((symbolp ident) (symbol-name ident))
15913 ((numberp ident) (number-to-string ident))
15914 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15915 (org-with-wide-buffer (org-find-property "ID" id))))
15917 ;;;; Timestamps
15919 (defvar org-last-changed-timestamp nil)
15920 (defvar org-last-inserted-timestamp nil
15921 "The last time stamp inserted with `org-insert-time-stamp'.")
15923 (defun org-time-stamp (arg &optional inactive)
15924 "Prompt for a date/time and insert a time stamp.
15926 If the user specifies a time like HH:MM or if this command is
15927 called with at least one prefix argument, the time stamp contains
15928 the date and the time. Otherwise, only the date is included.
15930 All parts of a date not specified by the user are filled in from
15931 the timestamp at point, if any, or the current date/time
15932 otherwise.
15934 If there is already a timestamp at the cursor, it is replaced.
15936 With two universal prefix arguments, insert an active timestamp
15937 with the current time without prompting the user.
15939 When called from lisp, the timestamp is inactive if INACTIVE is
15940 non-nil."
15941 (interactive "P")
15942 (let* ((ts (cond
15943 ((org-at-date-range-p t)
15944 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15945 ((org-at-timestamp-p 'lax) (match-string 0))))
15946 ;; Default time is either the timestamp at point or today.
15947 ;; When entering a range, only the range start is considered.
15948 (default-time (if (not ts) (current-time)
15949 (apply #'encode-time (org-parse-time-string ts))))
15950 (default-input (and ts (org-get-compact-tod ts)))
15951 (repeater (and ts
15952 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15953 (match-string 0 ts)))
15954 org-time-was-given
15955 org-end-time-was-given
15956 (time
15957 (and (if (equal arg '(16)) (current-time)
15958 ;; Preserve `this-command' and `last-command'.
15959 (let ((this-command this-command)
15960 (last-command last-command))
15961 (org-read-date
15962 arg 'totime nil nil default-time default-input
15963 inactive))))))
15964 (cond
15965 ((and ts
15966 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15967 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15968 (insert "--")
15969 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15971 ;; Make sure we're on a timestamp. When in the middle of a date
15972 ;; range, move arbitrarily to range end.
15973 (unless (org-at-timestamp-p 'lax)
15974 (skip-chars-forward "-")
15975 (org-at-timestamp-p 'lax))
15976 (replace-match "")
15977 (setq org-last-changed-timestamp
15978 (org-insert-time-stamp
15979 time (or org-time-was-given arg)
15980 inactive nil nil (list org-end-time-was-given)))
15981 (when repeater
15982 (backward-char)
15983 (insert " " repeater)
15984 (setq org-last-changed-timestamp
15985 (concat (substring org-last-inserted-timestamp 0 -1)
15986 " " repeater ">")))
15987 (message "Timestamp updated"))
15988 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
15989 (t (org-insert-time-stamp
15990 time (or org-time-was-given arg) inactive nil nil
15991 (list org-end-time-was-given))))))
15993 ;; FIXME: can we use this for something else, like computing time differences?
15994 (defun org-get-compact-tod (s)
15995 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15996 (let* ((t1 (match-string 1 s))
15997 (h1 (string-to-number (match-string 2 s)))
15998 (m1 (string-to-number (match-string 3 s)))
15999 (t2 (and (match-end 4) (match-string 5 s)))
16000 (h2 (and t2 (string-to-number (match-string 6 s))))
16001 (m2 (and t2 (string-to-number (match-string 7 s))))
16002 dh dm)
16003 (if (not t2)
16005 (setq dh (- h2 h1) dm (- m2 m1))
16006 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16007 (concat t1 "+" (number-to-string dh)
16008 (and (/= 0 dm) (format ":%02d" dm)))))))
16010 (defun org-time-stamp-inactive (&optional arg)
16011 "Insert an inactive time stamp.
16012 An inactive time stamp is enclosed in square brackets instead of angle
16013 brackets. It is inactive in the sense that it does not trigger agenda entries,
16014 does not link to the calendar and cannot be changed with the S-cursor keys.
16015 So these are more for recording a certain time/date."
16016 (interactive "P")
16017 (org-time-stamp arg 'inactive))
16019 (defvar org-date-ovl (make-overlay 1 1))
16020 (overlay-put org-date-ovl 'face 'org-date-selected)
16021 (delete-overlay org-date-ovl)
16023 (defvar org-ans1) ; dynamically scoped parameter
16024 (defvar org-ans2) ; dynamically scoped parameter
16026 (defvar org-plain-time-of-day-regexp) ; defined below
16028 (defvar org-overriding-default-time nil) ; dynamically scoped
16029 (defvar org-read-date-overlay nil)
16030 (defvar org-dcst nil) ; dynamically scoped
16031 (defvar org-read-date-history nil)
16032 (defvar org-read-date-final-answer nil)
16033 (defvar org-read-date-analyze-futurep nil)
16034 (defvar org-read-date-analyze-forced-year nil)
16035 (defvar org-read-date-inactive)
16037 (defvar org-read-date-minibuffer-local-map
16038 (let* ((map (make-sparse-keymap)))
16039 (set-keymap-parent map minibuffer-local-map)
16040 (org-defkey map (kbd ".")
16041 (lambda () (interactive)
16042 ;; Are we at the beginning of the prompt?
16043 (if (looking-back "^[^:]+: "
16044 (let ((inhibit-field-text-motion t))
16045 (line-beginning-position)))
16046 (org-eval-in-calendar '(calendar-goto-today))
16047 (insert "."))))
16048 (org-defkey map (kbd "C-.")
16049 (lambda () (interactive)
16050 (org-eval-in-calendar '(calendar-goto-today))))
16051 (org-defkey map (kbd "M-S-<left>")
16052 (lambda () (interactive)
16053 (org-eval-in-calendar '(calendar-backward-month 1))))
16054 (org-defkey map (kbd "ESC S-<left>")
16055 (lambda () (interactive)
16056 (org-eval-in-calendar '(calendar-backward-month 1))))
16057 (org-defkey map (kbd "M-S-<right>")
16058 (lambda () (interactive)
16059 (org-eval-in-calendar '(calendar-forward-month 1))))
16060 (org-defkey map (kbd "ESC S-<right>")
16061 (lambda () (interactive)
16062 (org-eval-in-calendar '(calendar-forward-month 1))))
16063 (org-defkey map (kbd "M-S-<up>")
16064 (lambda () (interactive)
16065 (org-eval-in-calendar '(calendar-backward-year 1))))
16066 (org-defkey map (kbd "ESC S-<up>")
16067 (lambda () (interactive)
16068 (org-eval-in-calendar '(calendar-backward-year 1))))
16069 (org-defkey map (kbd "M-S-<down>")
16070 (lambda () (interactive)
16071 (org-eval-in-calendar '(calendar-forward-year 1))))
16072 (org-defkey map (kbd "ESC S-<down>")
16073 (lambda () (interactive)
16074 (org-eval-in-calendar '(calendar-forward-year 1))))
16075 (org-defkey map (kbd "S-<up>")
16076 (lambda () (interactive)
16077 (org-eval-in-calendar '(calendar-backward-week 1))))
16078 (org-defkey map (kbd "S-<down>")
16079 (lambda () (interactive)
16080 (org-eval-in-calendar '(calendar-forward-week 1))))
16081 (org-defkey map (kbd "S-<left>")
16082 (lambda () (interactive)
16083 (org-eval-in-calendar '(calendar-backward-day 1))))
16084 (org-defkey map (kbd "S-<right>")
16085 (lambda () (interactive)
16086 (org-eval-in-calendar '(calendar-forward-day 1))))
16087 (org-defkey map "!"
16088 (lambda () (interactive)
16089 (org-eval-in-calendar '(diary-view-entries))
16090 (message "")))
16091 (org-defkey map ">"
16092 (lambda () (interactive)
16093 (org-eval-in-calendar '(calendar-scroll-left 1))))
16094 (org-defkey map "<"
16095 (lambda () (interactive)
16096 (org-eval-in-calendar '(calendar-scroll-right 1))))
16097 (org-defkey map "\C-v"
16098 (lambda () (interactive)
16099 (org-eval-in-calendar
16100 '(calendar-scroll-left-three-months 1))))
16101 (org-defkey map "\M-v"
16102 (lambda () (interactive)
16103 (org-eval-in-calendar
16104 '(calendar-scroll-right-three-months 1))))
16105 map)
16106 "Keymap for minibuffer commands when using `org-read-date'.")
16108 (defvar org-def)
16109 (defvar org-defdecode)
16110 (defvar org-with-time)
16112 (defvar calendar-setup) ; Dynamically scoped.
16113 (defun org-read-date (&optional with-time to-time from-string prompt
16114 default-time default-input inactive)
16115 "Read a date, possibly a time, and make things smooth for the user.
16116 The prompt will suggest to enter an ISO date, but you can also enter anything
16117 which will at least partially be understood by `parse-time-string'.
16118 Unrecognized parts of the date will default to the current day, month, year,
16119 hour and minute. If this command is called to replace a timestamp at point,
16120 or to enter the second timestamp of a range, the default time is taken
16121 from the existing stamp. Furthermore, the command prefers the future,
16122 so if you are giving a date where the year is not given, and the day-month
16123 combination is already past in the current year, it will assume you
16124 mean next year. For details, see the manual. A few examples:
16126 3-2-5 --> 2003-02-05
16127 feb 15 --> currentyear-02-15
16128 2/15 --> currentyear-02-15
16129 sep 12 9 --> 2009-09-12
16130 12:45 --> today 12:45
16131 22 sept 0:34 --> currentyear-09-22 0:34
16132 12 --> currentyear-currentmonth-12
16133 Fri --> nearest Friday after today
16134 -Tue --> last Tuesday
16135 etc.
16137 Furthermore you can specify a relative date by giving, as the *first* thing
16138 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16139 change in days weeks, months, years.
16140 With a single plus or minus, the date is relative to today. With a double
16141 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16142 +4d --> four days from today
16143 +4 --> same as above
16144 +2w --> two weeks from today
16145 ++5 --> five days from default date
16147 The function understands only English month and weekday abbreviations.
16149 While prompting, a calendar is popped up - you can also select the
16150 date with the mouse (button 1). The calendar shows a period of three
16151 months. To scroll it to other months, use the keys `>' and `<'.
16152 If you don't like the calendar, turn it off with
16153 (setq org-read-date-popup-calendar nil)
16155 With optional argument TO-TIME, the date will immediately be converted
16156 to an internal time.
16157 With an optional argument WITH-TIME, the prompt will suggest to
16158 also insert a time. Note that when WITH-TIME is not set, you can
16159 still enter a time, and this function will inform the calling routine
16160 about this change. The calling routine may then choose to change the
16161 format used to insert the time stamp into the buffer to include the time.
16162 With optional argument FROM-STRING, read from this string instead from
16163 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16164 the time/date that is used for everything that is not specified by the
16165 user."
16166 (require 'parse-time)
16167 (let* ((org-with-time with-time)
16168 (org-time-stamp-rounding-minutes
16169 (if (equal org-with-time '(16))
16170 '(0 0)
16171 org-time-stamp-rounding-minutes))
16172 (org-dcst org-display-custom-times)
16173 (ct (org-current-time))
16174 (org-def (or org-overriding-default-time default-time ct))
16175 (org-defdecode (decode-time org-def))
16176 (cur-frame (selected-frame))
16177 (mouse-autoselect-window nil) ; Don't let the mouse jump
16178 (calendar-setup
16179 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16180 (calendar-move-hook nil)
16181 (calendar-view-diary-initially-flag nil)
16182 (calendar-view-holidays-initially-flag nil)
16183 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16184 ;; Rationalize `org-def' and `org-defdecode', if required.
16185 (when (< (nth 2 org-defdecode) org-extend-today-until)
16186 (setf (nth 2 org-defdecode) -1)
16187 (setf (nth 1 org-defdecode) 59)
16188 (setq org-def (apply #'encode-time org-defdecode))
16189 (setq org-defdecode (decode-time org-def)))
16190 (let* ((timestr (format-time-string
16191 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16192 org-def))
16193 (prompt (concat (if prompt (concat prompt " ") "")
16194 (format "Date+time [%s]: " timestr))))
16195 (cond
16196 (from-string (setq ans from-string))
16197 (org-read-date-popup-calendar
16198 (save-excursion
16199 (save-window-excursion
16200 (calendar)
16201 (when (eq calendar-setup 'calendar-only)
16202 (setq cal-frame
16203 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16204 (select-frame cal-frame))
16205 (org-eval-in-calendar '(setq cursor-type nil) t)
16206 (unwind-protect
16207 (progn
16208 (calendar-forward-day (- (time-to-days org-def)
16209 (calendar-absolute-from-gregorian
16210 (calendar-current-date))))
16211 (org-eval-in-calendar nil t)
16212 (let* ((old-map (current-local-map))
16213 (map (copy-keymap calendar-mode-map))
16214 (minibuffer-local-map
16215 (copy-keymap org-read-date-minibuffer-local-map)))
16216 (org-defkey map (kbd "RET") 'org-calendar-select)
16217 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16218 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16219 (unwind-protect
16220 (progn
16221 (use-local-map map)
16222 (setq org-read-date-inactive inactive)
16223 (add-hook 'post-command-hook 'org-read-date-display)
16224 (setq org-ans0
16225 (read-string prompt
16226 default-input
16227 'org-read-date-history
16228 nil))
16229 ;; org-ans0: from prompt
16230 ;; org-ans1: from mouse click
16231 ;; org-ans2: from calendar motion
16232 (setq ans
16233 (concat org-ans0 " " (or org-ans1 org-ans2))))
16234 (remove-hook 'post-command-hook 'org-read-date-display)
16235 (use-local-map old-map)
16236 (when org-read-date-overlay
16237 (delete-overlay org-read-date-overlay)
16238 (setq org-read-date-overlay nil)))))
16239 (bury-buffer "*Calendar*")
16240 (when cal-frame
16241 (delete-frame cal-frame)
16242 (select-frame-set-input-focus cur-frame))))))
16244 (t ; Naked prompt only
16245 (unwind-protect
16246 (setq ans (read-string prompt default-input
16247 'org-read-date-history timestr))
16248 (when org-read-date-overlay
16249 (delete-overlay org-read-date-overlay)
16250 (setq org-read-date-overlay nil))))))
16252 (setq final (org-read-date-analyze ans org-def org-defdecode))
16254 (when org-read-date-analyze-forced-year
16255 (message "Year was forced into %s"
16256 (if org-read-date-force-compatible-dates
16257 "compatible range (1970-2037)"
16258 "range representable on this machine"))
16259 (ding))
16261 ;; One round trip to get rid of 34th of August and stuff like that....
16262 (setq final (decode-time (apply 'encode-time final)))
16264 (setq org-read-date-final-answer ans)
16266 (if to-time
16267 (apply 'encode-time final)
16268 (if (and (boundp 'org-time-was-given) org-time-was-given)
16269 (format "%04d-%02d-%02d %02d:%02d"
16270 (nth 5 final) (nth 4 final) (nth 3 final)
16271 (nth 2 final) (nth 1 final))
16272 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16274 (defun org-read-date-display ()
16275 "Display the current date prompt interpretation in the minibuffer."
16276 (when org-read-date-display-live
16277 (when org-read-date-overlay
16278 (delete-overlay org-read-date-overlay))
16279 (when (minibufferp (current-buffer))
16280 (save-excursion
16281 (end-of-line 1)
16282 (while (not (equal (buffer-substring
16283 (max (point-min) (- (point) 4)) (point))
16284 " "))
16285 (insert " ")))
16286 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16287 " " (or org-ans1 org-ans2)))
16288 (org-end-time-was-given nil)
16289 (f (org-read-date-analyze ans org-def org-defdecode))
16290 (fmts (if org-dcst
16291 org-time-stamp-custom-formats
16292 org-time-stamp-formats))
16293 (fmt (if (or org-with-time
16294 (and (boundp 'org-time-was-given) org-time-was-given))
16295 (cdr fmts)
16296 (car fmts)))
16297 (txt (format-time-string fmt (apply 'encode-time f)))
16298 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16299 (txt (concat "=> " txt)))
16300 (when (and org-end-time-was-given
16301 (string-match org-plain-time-of-day-regexp txt))
16302 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16303 org-end-time-was-given
16304 (substring txt (match-end 0)))))
16305 (when org-read-date-analyze-futurep
16306 (setq txt (concat txt " (=>F)")))
16307 (setq org-read-date-overlay
16308 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16309 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16311 (defun org-read-date-analyze (ans def defdecode)
16312 "Analyze the combined answer of the date prompt."
16313 ;; FIXME: cleanup and comment
16314 ;; Pass `current-time' result to `decode-time' (instead of calling
16315 ;; without arguments) so that only `current-time' has to be
16316 ;; overridden in tests.
16317 (let ((org-def def)
16318 (org-defdecode defdecode)
16319 (nowdecode (decode-time (current-time)))
16320 delta deltan deltaw deltadef year month day
16321 hour minute second wday pm h2 m2 tl wday1
16322 iso-year iso-weekday iso-week iso-date futurep kill-year)
16323 (setq org-read-date-analyze-futurep nil
16324 org-read-date-analyze-forced-year nil)
16325 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16326 (setq ans "+0"))
16328 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16329 (setq ans (replace-match "" t t ans)
16330 deltan (car delta)
16331 deltaw (nth 1 delta)
16332 deltadef (nth 2 delta)))
16334 ;; Check if there is an iso week date in there. If yes, store the
16335 ;; info and postpone interpreting it until the rest of the parsing
16336 ;; is done.
16337 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16338 (setq iso-year (when (match-end 1)
16339 (org-small-year-to-year
16340 (string-to-number (match-string 1 ans))))
16341 iso-weekday (when (match-end 3)
16342 (string-to-number (match-string 3 ans)))
16343 iso-week (string-to-number (match-string 2 ans)))
16344 (setq ans (replace-match "" t t ans)))
16346 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16347 (when (string-match
16348 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16349 (setq year (if (match-end 2)
16350 (string-to-number (match-string 2 ans))
16351 (progn (setq kill-year t)
16352 (string-to-number (format-time-string "%Y"))))
16353 month (string-to-number (match-string 3 ans))
16354 day (string-to-number (match-string 4 ans)))
16355 (setq year (org-small-year-to-year year))
16356 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16357 t nil ans)))
16359 ;; Help matching dotted european dates
16360 (when (string-match
16361 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16362 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16363 (setq kill-year t)
16364 (string-to-number (format-time-string "%Y")))
16365 day (string-to-number (match-string 1 ans))
16366 month (string-to-number (match-string 2 ans))
16367 ans (replace-match (format "%04d-%02d-%02d" year month day)
16368 t nil ans)))
16370 ;; Help matching american dates, like 5/30 or 5/30/7
16371 (when (string-match
16372 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16373 (setq year (if (match-end 4)
16374 (string-to-number (match-string 4 ans))
16375 (progn (setq kill-year t)
16376 (string-to-number (format-time-string "%Y"))))
16377 month (string-to-number (match-string 1 ans))
16378 day (string-to-number (match-string 2 ans)))
16379 (setq year (org-small-year-to-year year))
16380 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16381 t nil ans)))
16382 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16383 ;; If there is a time with am/pm, and *no* time without it, we convert
16384 ;; so that matching will be successful.
16385 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16386 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16387 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16388 (setq hour (string-to-number (match-string 1 ans))
16389 minute (if (match-end 3)
16390 (string-to-number (match-string 3 ans))
16392 pm (equal ?p
16393 (string-to-char (downcase (match-string 4 ans)))))
16394 (if (and (= hour 12) (not pm))
16395 (setq hour 0)
16396 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16397 (setq ans (replace-match (format "%02d:%02d" hour minute)
16398 t t ans))))
16400 ;; Check if a time range is given as a duration
16401 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16402 (setq hour (string-to-number (match-string 1 ans))
16403 h2 (+ hour (string-to-number (match-string 3 ans)))
16404 minute (string-to-number (match-string 2 ans))
16405 m2 (+ minute (if (match-end 5) (string-to-number
16406 (match-string 5 ans))0)))
16407 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16408 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16409 t t ans)))
16411 ;; Check if there is a time range
16412 (when (boundp 'org-end-time-was-given)
16413 (setq org-time-was-given nil)
16414 (when (and (string-match org-plain-time-of-day-regexp ans)
16415 (match-end 8))
16416 (setq org-end-time-was-given (match-string 8 ans))
16417 (setq ans (concat (substring ans 0 (match-beginning 7))
16418 (substring ans (match-end 7))))))
16420 (setq tl (parse-time-string ans)
16421 day (or (nth 3 tl) (nth 3 org-defdecode))
16422 month
16423 (cond ((nth 4 tl))
16424 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16425 ;; Day was specified. Make sure DAY+MONTH
16426 ;; combination happens in the future.
16427 ((nth 3 tl)
16428 (setq futurep t)
16429 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16430 (nth 4 nowdecode)))
16431 (t (nth 4 org-defdecode)))
16432 year
16433 (cond ((and (not kill-year) (nth 5 tl)))
16434 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16435 ;; Month was guessed in the future and is at least
16436 ;; equal to NOWDECODE's. Fix year accordingly.
16437 (futurep
16438 (if (or (> month (nth 4 nowdecode))
16439 (>= day (nth 3 nowdecode)))
16440 (nth 5 nowdecode)
16441 (1+ (nth 5 nowdecode))))
16442 ;; Month was specified. Make sure MONTH+YEAR
16443 ;; combination happens in the future.
16444 ((nth 4 tl)
16445 (setq futurep t)
16446 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16447 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16448 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16449 (t (nth 5 nowdecode))))
16450 (t (nth 5 org-defdecode)))
16451 hour (or (nth 2 tl) (nth 2 org-defdecode))
16452 minute (or (nth 1 tl) (nth 1 org-defdecode))
16453 second (or (nth 0 tl) 0)
16454 wday (nth 6 tl))
16456 (when (and (eq org-read-date-prefer-future 'time)
16457 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16458 (equal day (nth 3 nowdecode))
16459 (equal month (nth 4 nowdecode))
16460 (equal year (nth 5 nowdecode))
16461 (nth 2 tl)
16462 (or (< (nth 2 tl) (nth 2 nowdecode))
16463 (and (= (nth 2 tl) (nth 2 nowdecode))
16464 (nth 1 tl)
16465 (< (nth 1 tl) (nth 1 nowdecode)))))
16466 (setq day (1+ day)
16467 futurep t))
16469 ;; Special date definitions below
16470 (cond
16471 (iso-week
16472 ;; There was an iso week
16473 (require 'cal-iso)
16474 (setq futurep nil)
16475 (setq year (or iso-year year)
16476 day (or iso-weekday wday 1)
16477 wday nil ; to make sure that the trigger below does not match
16478 iso-date (calendar-gregorian-from-absolute
16479 (calendar-iso-to-absolute
16480 (list iso-week day year))))
16481 ; FIXME: Should we also push ISO weeks into the future?
16482 ; (when (and org-read-date-prefer-future
16483 ; (not iso-year)
16484 ; (< (calendar-absolute-from-gregorian iso-date)
16485 ; (time-to-days (current-time))))
16486 ; (setq year (1+ year)
16487 ; iso-date (calendar-gregorian-from-absolute
16488 ; (calendar-iso-to-absolute
16489 ; (list iso-week day year)))))
16490 (setq month (car iso-date)
16491 year (nth 2 iso-date)
16492 day (nth 1 iso-date)))
16493 (deltan
16494 (setq futurep nil)
16495 (unless deltadef
16496 ;; Pass `current-time' result to `decode-time' (instead of
16497 ;; calling without arguments) so that only `current-time' has
16498 ;; to be overridden in tests.
16499 (let ((now (decode-time (current-time))))
16500 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16501 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16502 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16503 ((equal deltaw "m") (setq month (+ month deltan)))
16504 ((equal deltaw "y") (setq year (+ year deltan)))))
16505 ((and wday (not (nth 3 tl)))
16506 ;; Weekday was given, but no day, so pick that day in the week
16507 ;; on or after the derived date.
16508 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16509 (unless (equal wday wday1)
16510 (setq day (+ day (% (- wday wday1 -7) 7))))))
16511 (when (and (boundp 'org-time-was-given)
16512 (nth 2 tl))
16513 (setq org-time-was-given t))
16514 (when (< year 100) (setq year (+ 2000 year)))
16515 ;; Check of the date is representable
16516 (if org-read-date-force-compatible-dates
16517 (progn
16518 (when (< year 1970)
16519 (setq year 1970 org-read-date-analyze-forced-year t))
16520 (when (> year 2037)
16521 (setq year 2037 org-read-date-analyze-forced-year t)))
16522 (condition-case nil
16523 (ignore (encode-time second minute hour day month year))
16524 (error
16525 (setq year (nth 5 org-defdecode))
16526 (setq org-read-date-analyze-forced-year t))))
16527 (setq org-read-date-analyze-futurep futurep)
16528 (list second minute hour day month year)))
16530 (defvar parse-time-weekdays)
16531 (defun org-read-date-get-relative (s today default)
16532 "Check string S for special relative date string.
16533 TODAY and DEFAULT are internal times, for today and for a default.
16534 Return shift list (N what def-flag)
16535 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16536 N is the number of WHATs to shift.
16537 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16538 the DEFAULT date rather than TODAY."
16539 (require 'parse-time)
16540 (when (and
16541 (string-match
16542 (concat
16543 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16544 "\\([0-9]+\\)?"
16545 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16546 "\\([ \t]\\|$\\)") s)
16547 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16548 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16549 (string-to-char (substring (match-string 1 s) -1))
16550 ?+))
16551 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16552 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16553 (what (if (match-end 3) (match-string 3 s) "d"))
16554 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16555 (date (if rel default today))
16556 (wday (nth 6 (decode-time date)))
16557 delta)
16558 (if wday1
16559 (progn
16560 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16561 (when (= delta 0) (setq delta 7))
16562 (when (= dir ?-)
16563 (setq delta (- delta 7))
16564 (when (= delta 0) (setq delta -7)))
16565 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16566 (list delta "d" rel))
16567 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16569 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16570 "Turn a user-specified date into the internal representation.
16571 The internal representation needed by the calendar is (month day year).
16572 This is a wrapper to handle the brain-dead convention in calendar that
16573 user function argument order change dependent on argument order."
16574 (pcase calendar-date-style
16575 (`american (list arg1 arg2 arg3))
16576 (`european (list arg2 arg1 arg3))
16577 (`iso (list arg2 arg3 arg1))))
16579 (defun org-eval-in-calendar (form &optional keepdate)
16580 "Eval FORM in the calendar window and return to current window.
16581 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16582 (let ((sf (selected-frame))
16583 (sw (selected-window)))
16584 (select-window (get-buffer-window "*Calendar*" t))
16585 (eval form)
16586 (when (and (not keepdate) (calendar-cursor-to-date))
16587 (let* ((date (calendar-cursor-to-date))
16588 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16589 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16590 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16591 (select-window sw)
16592 (select-frame-set-input-focus sf)))
16594 (defun org-calendar-select ()
16595 "Return to `org-read-date' with the date currently selected.
16596 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16597 (interactive)
16598 (when (calendar-cursor-to-date)
16599 (let* ((date (calendar-cursor-to-date))
16600 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16601 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16602 (when (active-minibuffer-window) (exit-minibuffer))))
16604 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16605 "Insert a date stamp for the date given by the internal TIME.
16606 See `format-time-string' for the format of TIME.
16607 WITH-HM means use the stamp format that includes the time of the day.
16608 INACTIVE means use square brackets instead of angular ones, so that the
16609 stamp will not contribute to the agenda.
16610 PRE and POST are optional strings to be inserted before and after the
16611 stamp.
16612 The command returns the inserted time stamp."
16613 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16614 stamp)
16615 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16616 (insert-before-markers (or pre ""))
16617 (when (listp extra)
16618 (setq extra (car extra))
16619 (if (and (stringp extra)
16620 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16621 (setq extra (format "-%02d:%02d"
16622 (string-to-number (match-string 1 extra))
16623 (string-to-number (match-string 2 extra))))
16624 (setq extra nil)))
16625 (when extra
16626 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16627 (insert-before-markers (setq stamp (format-time-string fmt time)))
16628 (insert-before-markers (or post ""))
16629 (setq org-last-inserted-timestamp stamp)))
16631 (defun org-toggle-time-stamp-overlays ()
16632 "Toggle the use of custom time stamp formats."
16633 (interactive)
16634 (setq org-display-custom-times (not org-display-custom-times))
16635 (unless org-display-custom-times
16636 (let ((p (point-min)) (bmp (buffer-modified-p)))
16637 (while (setq p (next-single-property-change p 'display))
16638 (when (and (get-text-property p 'display)
16639 (eq (get-text-property p 'face) 'org-date))
16640 (remove-text-properties
16641 p (setq p (next-single-property-change p 'display))
16642 '(display t))))
16643 (set-buffer-modified-p bmp)))
16644 (org-restart-font-lock)
16645 (setq org-table-may-need-update t)
16646 (if org-display-custom-times
16647 (message "Time stamps are overlaid with custom format")
16648 (message "Time stamp overlays removed")))
16650 (defun org-display-custom-time (beg end)
16651 "Overlay modified time stamp format over timestamp between BEG and END."
16652 (let* ((ts (buffer-substring beg end))
16653 t1 with-hm tf time str (off 0))
16654 (save-match-data
16655 (setq t1 (org-parse-time-string ts t))
16656 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16657 (setq off (- (match-end 0) (match-beginning 0)))))
16658 (setq end (- end off))
16659 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16660 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16661 time (org-fix-decoded-time t1)
16662 str (org-add-props
16663 (format-time-string
16664 (substring tf 1 -1) (apply 'encode-time time))
16665 nil 'mouse-face 'highlight))
16666 (put-text-property beg end 'display str)))
16668 (defun org-fix-decoded-time (time)
16669 "Set 0 instead of nil for the first 6 elements of time.
16670 Don't touch the rest."
16671 (let ((n 0))
16672 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16674 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16675 "Difference between TIMESTAMP-STRING and now in days.
16676 If SECONDS is non-nil, return the difference in seconds."
16677 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16678 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16679 (funcall fdiff (current-time)))))
16681 (defun org-deadline-close-p (timestamp-string &optional ndays)
16682 "Is the time in TIMESTAMP-STRING close to the current date?"
16683 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16684 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16685 (not (org-entry-is-done-p))))
16687 (defun org-get-wdays (ts &optional delay zero-delay)
16688 "Get the deadline lead time appropriate for timestring TS.
16689 When DELAY is non-nil, get the delay time for scheduled items
16690 instead of the deadline lead time. When ZERO-DELAY is non-nil
16691 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16692 don't try to find the delay cookie in the scheduled timestamp."
16693 (let ((tv (if delay org-scheduled-delay-days
16694 org-deadline-warning-days)))
16695 (cond
16696 ((or (and delay (< tv 0))
16697 (and delay zero-delay (<= tv 0))
16698 (and (not delay) (<= tv 0)))
16699 ;; Enforce this value no matter what
16700 (- tv))
16701 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16702 ;; lead time is specified.
16703 (floor (* (string-to-number (match-string 1 ts))
16704 (cdr (assoc (match-string 2 ts)
16705 '(("d" . 1) ("w" . 7)
16706 ("m" . 30.4) ("y" . 365.25)
16707 ("h" . 0.041667)))))))
16708 ;; go for the default.
16709 (t tv))))
16711 (defun org-calendar-select-mouse (ev)
16712 "Return to `org-read-date' with the date currently selected.
16713 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16714 (interactive "e")
16715 (mouse-set-point ev)
16716 (when (calendar-cursor-to-date)
16717 (let* ((date (calendar-cursor-to-date))
16718 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16719 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16720 (when (active-minibuffer-window) (exit-minibuffer))))
16722 (defun org-check-deadlines (ndays)
16723 "Check if there are any deadlines due or past due.
16724 A deadline is considered due if it happens within `org-deadline-warning-days'
16725 days from today's date. If the deadline appears in an entry marked DONE,
16726 it is not shown. A numeric prefix argument NDAYS can be used to test that
16727 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16728 are shown."
16729 (interactive "P")
16730 (let* ((org-warn-days
16731 (cond
16732 ((equal ndays '(4)) 100000)
16733 (ndays (prefix-numeric-value ndays))
16734 (t (abs org-deadline-warning-days))))
16735 (case-fold-search nil)
16736 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16737 (callback
16738 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16739 (message "%d deadlines past-due or due within %d days"
16740 (org-occur regexp nil callback)
16741 org-warn-days)))
16743 (defsubst org-re-timestamp (type)
16744 "Return a regexp for timestamp TYPE.
16745 Allowed values for TYPE are:
16747 all: all timestamps
16748 active: only active timestamps (<...>)
16749 inactive: only inactive timestamps ([...])
16750 scheduled: only scheduled timestamps
16751 deadline: only deadline timestamps
16752 closed: only closed time-stamps
16754 When TYPE is nil, fall back on returning a regexp that matches
16755 both scheduled and deadline timestamps."
16756 (cl-case type
16757 (all org-ts-regexp-both)
16758 (active org-ts-regexp)
16759 (inactive org-ts-regexp-inactive)
16760 (scheduled org-scheduled-time-regexp)
16761 (deadline org-deadline-time-regexp)
16762 (closed org-closed-time-regexp)
16763 (otherwise
16764 (concat "\\<"
16765 (regexp-opt (list org-deadline-string org-scheduled-string))
16766 " *<\\([^>]+\\)>"))))
16768 (defun org-check-before-date (d)
16769 "Check if there are deadlines or scheduled entries before date D."
16770 (interactive (list (org-read-date)))
16771 (let* ((case-fold-search nil)
16772 (regexp (org-re-timestamp org-ts-type))
16773 (ts-type org-ts-type)
16774 (callback
16775 (lambda ()
16776 (let ((match (match-string 1)))
16777 (and (if (memq ts-type '(active inactive all))
16778 (eq (org-element-type (save-excursion
16779 (backward-char)
16780 (org-element-context)))
16781 'timestamp)
16782 (org-at-planning-p))
16783 (time-less-p
16784 (org-time-string-to-time match)
16785 (org-time-string-to-time d)))))))
16786 (message "%d entries before %s"
16787 (org-occur regexp nil callback)
16788 d)))
16790 (defun org-check-after-date (d)
16791 "Check if there are deadlines or scheduled entries after date D."
16792 (interactive (list (org-read-date)))
16793 (let* ((case-fold-search nil)
16794 (regexp (org-re-timestamp org-ts-type))
16795 (ts-type org-ts-type)
16796 (callback
16797 (lambda ()
16798 (let ((match (match-string 1)))
16799 (and (if (memq ts-type '(active inactive all))
16800 (eq (org-element-type (save-excursion
16801 (backward-char)
16802 (org-element-context)))
16803 'timestamp)
16804 (org-at-planning-p))
16805 (not (time-less-p
16806 (org-time-string-to-time match)
16807 (org-time-string-to-time d))))))))
16808 (message "%d entries after %s"
16809 (org-occur regexp nil callback)
16810 d)))
16812 (defun org-check-dates-range (start-date end-date)
16813 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16814 (interactive (list (org-read-date nil nil nil "Range starts")
16815 (org-read-date nil nil nil "Range end")))
16816 (let ((case-fold-search nil)
16817 (regexp (org-re-timestamp org-ts-type))
16818 (callback
16819 (let ((type org-ts-type))
16820 (lambda ()
16821 (let ((match (match-string 1)))
16822 (and
16823 (if (memq type '(active inactive all))
16824 (eq (org-element-type (save-excursion
16825 (backward-char)
16826 (org-element-context)))
16827 'timestamp)
16828 (org-at-planning-p))
16829 (not (time-less-p
16830 (org-time-string-to-time match)
16831 (org-time-string-to-time start-date)))
16832 (time-less-p
16833 (org-time-string-to-time match)
16834 (org-time-string-to-time end-date))))))))
16835 (message "%d entries between %s and %s"
16836 (org-occur regexp nil callback) start-date end-date)))
16838 (defun org-evaluate-time-range (&optional to-buffer)
16839 "Evaluate a time range by computing the difference between start and end.
16840 Normally the result is just printed in the echo area, but with prefix arg
16841 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16842 If the time range is actually in a table, the result is inserted into the
16843 next column.
16844 For time difference computation, a year is assumed to be exactly 365
16845 days in order to avoid rounding problems."
16846 (interactive "P")
16848 (org-clock-update-time-maybe)
16849 (save-excursion
16850 (unless (org-at-date-range-p t)
16851 (goto-char (point-at-bol))
16852 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16853 (unless (org-at-date-range-p t)
16854 (user-error "Not at a time-stamp range, and none found in current line")))
16855 (let* ((ts1 (match-string 1))
16856 (ts2 (match-string 2))
16857 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16858 (match-end (match-end 0))
16859 (time1 (org-time-string-to-time ts1))
16860 (time2 (org-time-string-to-time ts2))
16861 (t1 (float-time time1))
16862 (t2 (float-time time2))
16863 (diff (abs (- t2 t1)))
16864 (negative (< (- t2 t1) 0))
16865 ;; (ys (floor (* 365 24 60 60)))
16866 (ds (* 24 60 60))
16867 (hs (* 60 60))
16868 (fy "%dy %dd %02d:%02d")
16869 (fy1 "%dy %dd")
16870 (fd "%dd %02d:%02d")
16871 (fd1 "%dd")
16872 (fh "%02d:%02d")
16873 y d h m align)
16874 (if havetime
16875 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16877 d (floor (/ diff ds)) diff (mod diff ds)
16878 h (floor (/ diff hs)) diff (mod diff hs)
16879 m (floor (/ diff 60)))
16880 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16882 d (floor (+ (/ diff ds) 0.5))
16883 h 0 m 0))
16884 (if (not to-buffer)
16885 (message "%s" (org-make-tdiff-string y d h m))
16886 (if (org-at-table-p)
16887 (progn
16888 (goto-char match-end)
16889 (setq align t)
16890 (and (looking-at " *|") (goto-char (match-end 0))))
16891 (goto-char match-end))
16892 (when (looking-at
16893 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16894 (replace-match ""))
16895 (when negative (insert " -"))
16896 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16897 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16898 (insert " " (format fh h m))))
16899 (when align (org-table-align))
16900 (message "Time difference inserted")))))
16902 (defun org-make-tdiff-string (y d h m)
16903 (let ((fmt "")
16904 (l nil))
16905 (when (> y 0)
16906 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16907 (push y l))
16908 (when (> d 0)
16909 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16910 (push d l))
16911 (when (> h 0)
16912 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16913 (push h l))
16914 (when (> m 0)
16915 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16916 (push m l))
16917 (apply 'format fmt (nreverse l))))
16919 (defun org-time-string-to-time (s)
16920 "Convert timestamp string S into internal time."
16921 (apply #'encode-time (org-parse-time-string s)))
16923 (defun org-time-string-to-seconds (s)
16924 "Convert a timestamp string S into a number of seconds."
16925 (float-time (org-time-string-to-time s)))
16927 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16929 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16930 "Convert time stamp S to an absolute day number.
16932 If DAYNR in non-nil, and there is a specifier for a cyclic time
16933 stamp, get the closest date to DAYNR. If PREFER is
16934 `past' (respectively `future') return a date past (respectively
16935 after) or equal to DAYNR.
16937 POS is the location of time stamp S, as a buffer position in
16938 BUFFER.
16940 Diary sexp timestamps are matched against DAYNR, when non-nil.
16941 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16942 signaled."
16943 (cond
16944 ((string-match "\\`%%\\((.*)\\)" s)
16945 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16946 ;; only able to match individual dates. If it fails, raise an
16947 ;; error.
16948 (if (and daynr
16949 (org-diary-sexp-entry
16950 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16951 daynr
16952 (signal 'org-diary-sexp-no-match (list s))))
16953 (daynr (org-closest-date s daynr prefer))
16954 (t (time-to-days
16955 (condition-case errdata
16956 (apply #'encode-time (org-parse-time-string s))
16957 (error (error "Bad timestamp `%s'%s\nError was: %s"
16959 (if (not (and buffer pos)) ""
16960 (format-message " at %d in buffer `%s'" pos buffer))
16961 (cdr errdata))))))))
16963 (defun org-days-to-iso-week (days)
16964 "Return the iso week number."
16965 (require 'cal-iso)
16966 (car (calendar-iso-from-absolute days)))
16968 (defun org-small-year-to-year (year)
16969 "Convert 2-digit years into 4-digit years.
16970 YEAR is expanded into one of the 30 next years, if possible, or
16971 into a past one. Any year larger than 99 is returned unchanged."
16972 (if (>= year 100) year
16973 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
16974 (century (/ current 100))
16975 (offset (- year (% current 100))))
16976 (cond ((> offset 30) (+ (* (1- century) 100) year))
16977 ((> offset -70) (+ (* century 100) year))
16978 (t (+ (* (1+ century) 100) year))))))
16980 (defun org-time-from-absolute (d)
16981 "Return the time corresponding to date D.
16982 D may be an absolute day number, or a calendar-type list (month day year)."
16983 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16984 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16986 (defvar org-agenda-current-date)
16987 (defun org-calendar-holiday ()
16988 "List of holidays, for Diary display in Org mode."
16989 (require 'holidays)
16990 (let ((hl (calendar-check-holidays org-agenda-current-date)))
16991 (and hl (mapconcat #'identity hl "; "))))
16993 (defun org-diary-sexp-entry (sexp entry d)
16994 "Process a SEXP diary ENTRY for date D."
16995 (require 'diary-lib)
16996 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
16997 ;; dynamically.
16998 (let* ((sexp `(let ((entry ,entry)
16999 (date ',d))
17000 ,(car (read-from-string sexp))))
17001 (result (if calendar-debug-sexp (eval sexp)
17002 (condition-case nil
17003 (eval sexp)
17004 (error
17005 (beep)
17006 (message "Bad sexp at line %d in %s: %s"
17007 (org-current-line)
17008 (buffer-file-name) sexp)
17009 (sleep-for 2))))))
17010 (cond ((stringp result) (split-string result "; "))
17011 ((and (consp result)
17012 (not (consp (cdr result)))
17013 (stringp (cdr result))) (cdr result))
17014 ((and (consp result)
17015 (stringp (car result))) result)
17016 (result entry))))
17018 (defun org-diary-to-ical-string (frombuf)
17019 "Get iCalendar entries from diary entries in buffer FROMBUF.
17020 This uses the icalendar.el library."
17021 (let* ((tmpdir temporary-file-directory)
17022 (tmpfile (make-temp-name
17023 (expand-file-name "orgics" tmpdir)))
17024 buf rtn b e)
17025 (with-current-buffer frombuf
17026 (icalendar-export-region (point-min) (point-max) tmpfile)
17027 (setq buf (find-buffer-visiting tmpfile))
17028 (set-buffer buf)
17029 (goto-char (point-min))
17030 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17031 (setq b (match-beginning 0)))
17032 (goto-char (point-max))
17033 (when (re-search-backward "^END:VEVENT" nil t)
17034 (setq e (match-end 0)))
17035 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17036 (kill-buffer buf)
17037 (delete-file tmpfile)
17038 rtn))
17040 (defun org-closest-date (start current prefer)
17041 "Return closest date to CURRENT starting from START.
17043 CURRENT and START are both time stamps.
17045 When PREFER is `past', return a date that is either CURRENT or
17046 past. When PREFER is `future', return a date that is either
17047 CURRENT or future.
17049 Only time stamps with a repeater are modified. Any other time
17050 stamp stay unchanged. In any case, return value is an absolute
17051 day number."
17052 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17053 ;; No repeater. Do not shift time stamp.
17054 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17055 (let ((value (string-to-number (match-string 1 start)))
17056 (type (match-string 2 start)))
17057 (if (= 0 value)
17058 ;; Repeater with a 0-value is considered as void.
17059 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17060 (let* ((base (org-date-to-gregorian start))
17061 (target (org-date-to-gregorian current))
17062 (sday (calendar-absolute-from-gregorian base))
17063 (cday (calendar-absolute-from-gregorian target))
17064 n1 n2)
17065 ;; If START is already past CURRENT, just return START.
17066 (if (<= cday sday) sday
17067 ;; Compute closest date before (N1) and closest date past
17068 ;; (N2) CURRENT.
17069 (pcase type
17070 ("h"
17071 (let ((missing-hours
17072 (mod (+ (- (* 24 (- cday sday))
17073 (nth 2 (org-parse-time-string start)))
17074 org-extend-today-until)
17075 value)))
17076 (setf n1 (if (= missing-hours 0) cday
17077 (- cday (1+ (/ missing-hours 24)))))
17078 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17079 ((or "d" "w")
17080 (let ((value (if (equal type "w") (* 7 value) value)))
17081 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17082 (setf n2 (+ n1 value))))
17083 ("m"
17084 (let* ((add-months
17085 (lambda (d n)
17086 ;; Add N months to gregorian date D, i.e.,
17087 ;; a list (MONTH DAY YEAR). Return a valid
17088 ;; gregorian date.
17089 (let ((m (+ (nth 0 d) n)))
17090 (list (mod m 12)
17091 (nth 1 d)
17092 (+ (/ m 12) (nth 2 d))))))
17093 (months ; Complete months to TARGET.
17094 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17095 (- (nth 0 target) (nth 0 base))
17096 ;; If START's day is greater than
17097 ;; TARGET's, remove incomplete month.
17098 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17099 value)
17100 value))
17101 (before (funcall add-months base months)))
17102 (setf n1 (calendar-absolute-from-gregorian before))
17103 (setf n2
17104 (calendar-absolute-from-gregorian
17105 (funcall add-months before value)))))
17107 (let* ((d (nth 1 base))
17108 (m (nth 0 base))
17109 (y (nth 2 base))
17110 (years ; Complete years to TARGET.
17111 (* (/ (- (nth 2 target)
17113 ;; If START's month and day are
17114 ;; greater than TARGET's, remove
17115 ;; incomplete year.
17116 (if (or (> (nth 0 target) m)
17117 (and (= (nth 0 target) m)
17118 (> (nth 1 target) d)))
17121 value)
17122 value))
17123 (before (list m d (+ y years))))
17124 (setf n1 (calendar-absolute-from-gregorian before))
17125 (setf n2 (calendar-absolute-from-gregorian
17126 (list m d (+ (nth 2 before) value)))))))
17127 ;; Handle PREFER parameter, if any.
17128 (cond
17129 ((eq prefer 'past) (if (= cday n2) n2 n1))
17130 ((eq prefer 'future) (if (= cday n1) n1 n2))
17131 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17133 (defun org-date-to-gregorian (d)
17134 "Turn any specification of date D into a Gregorian date for the calendar."
17135 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17136 ((and (listp d) (= (length d) 3)) d)
17137 ((stringp d)
17138 (let ((d (org-parse-time-string d)))
17139 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17140 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17142 (defun org-parse-time-string (s &optional nodefault)
17143 "Parse the standard Org time string.
17145 This should be a lot faster than the normal `parse-time-string'.
17147 If time is not given, defaults to 0:00. However, with optional
17148 NODEFAULT, hour and minute fields will be nil if not given."
17149 (cond ((string-match org-ts-regexp0 s)
17150 (list 0
17151 (when (or (match-beginning 8) (not nodefault))
17152 (string-to-number (or (match-string 8 s) "0")))
17153 (when (or (match-beginning 7) (not nodefault))
17154 (string-to-number (or (match-string 7 s) "0")))
17155 (string-to-number (match-string 4 s))
17156 (string-to-number (match-string 3 s))
17157 (string-to-number (match-string 2 s))
17158 nil nil nil))
17159 ((string-match "^<[^>]+>$" s)
17160 ;; FIXME: `decode-time' needs to be called with ZONE as its
17161 ;; second argument. However, this requires at least Emacs
17162 ;; 25.1. We can do it when we switch to this version as our
17163 ;; minimal requirement.
17164 (decode-time (seconds-to-time (org-matcher-time s))))
17165 (t (error "Not a standard Org time string: %s" s))))
17167 (defun org-timestamp-up (&optional arg)
17168 "Increase the date item at the cursor by one.
17169 If the cursor is on the year, change the year. If it is on the month,
17170 the day or the time, change that.
17171 With prefix ARG, change by that many units."
17172 (interactive "p")
17173 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17175 (defun org-timestamp-down (&optional arg)
17176 "Decrease the date item at the cursor by one.
17177 If the cursor is on the year, change the year. If it is on the month,
17178 the day or the time, change that.
17179 With prefix ARG, change by that many units."
17180 (interactive "p")
17181 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17183 (defun org-timestamp-up-day (&optional arg)
17184 "Increase the date in the time stamp by one day.
17185 With prefix ARG, change that many days."
17186 (interactive "p")
17187 (if (and (not (org-at-timestamp-p 'lax))
17188 (org-at-heading-p))
17189 (org-todo 'up)
17190 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17192 (defun org-timestamp-down-day (&optional arg)
17193 "Decrease the date in the time stamp by one day.
17194 With prefix ARG, change that many days."
17195 (interactive "p")
17196 (if (and (not (org-at-timestamp-p 'lax))
17197 (org-at-heading-p))
17198 (org-todo 'down)
17199 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17201 (defun org-at-timestamp-p (&optional extended)
17202 "Non-nil if point is inside a timestamp.
17204 By default, the function only consider syntactically valid active
17205 timestamps. However, the caller may have a broader definition
17206 for timestamps. As a consequence, optional argument EXTENDED can
17207 be set to the following values
17209 `inactive'
17211 Include also syntactically valid inactive timestamps.
17213 `agenda'
17215 Include timestamps allowed in Agenda, i.e., those in
17216 properties drawers, planning lines and clock lines.
17218 `lax'
17220 Ignore context. The function matches any part of the
17221 document looking like a timestamp. This includes comments,
17222 example blocks...
17224 For backward-compatibility with Org 9.0, every other non-nil
17225 value is equivalent to `inactive'.
17227 When at a timestamp, return the position of the point as a symbol
17228 among `bracket', `after', `year', `month', `hour', `minute',
17229 `day' or a number of character from the last know part of the
17230 time stamp.
17232 When matching, the match groups are the following:
17233 group 1: year
17234 group 2: month
17235 group 3: day number
17236 group 4: day name
17237 group 5: hours, if any
17238 group 6: minutes, if any"
17239 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17240 (pos (point))
17241 (match?
17242 (let ((boundaries (org-in-regexp regexp)))
17243 (save-match-data
17244 (cond ((null boundaries) nil)
17245 ((eq extended 'lax) t)
17247 (or (and (eq extended 'agenda)
17248 (or (org-at-planning-p)
17249 (org-at-property-p)
17250 (and (bound-and-true-p
17251 org-agenda-include-inactive-timestamps)
17252 (org-at-clock-log-p))))
17253 (eq 'timestamp
17254 (save-excursion
17255 (when (= pos (cdr boundaries)) (forward-char -1))
17256 (org-element-type (org-element-context)))))))))))
17257 (cond
17258 ((not match?) nil)
17259 ((= pos (match-beginning 0)) 'bracket)
17260 ;; Distinguish location right before the closing bracket from
17261 ;; right after it.
17262 ((= pos (1- (match-end 0))) 'bracket)
17263 ((= pos (match-end 0)) 'after)
17264 ((org-pos-in-match-range pos 2) 'year)
17265 ((org-pos-in-match-range pos 3) 'month)
17266 ((org-pos-in-match-range pos 7) 'hour)
17267 ((org-pos-in-match-range pos 8) 'minute)
17268 ((or (org-pos-in-match-range pos 4)
17269 (org-pos-in-match-range pos 5)) 'day)
17270 ((and (> pos (or (match-end 8) (match-end 5)))
17271 (< pos (match-end 0)))
17272 (- pos (or (match-end 8) (match-end 5))))
17273 (t 'day))))
17275 (defun org-toggle-timestamp-type ()
17276 "Toggle the type (<active> or [inactive]) of a time stamp."
17277 (interactive)
17278 (when (org-at-timestamp-p 'lax)
17279 (let ((beg (match-beginning 0)) (end (match-end 0))
17280 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17281 (save-excursion
17282 (goto-char beg)
17283 (while (re-search-forward "[][<>]" end t)
17284 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17285 t t)))
17286 (message "Timestamp is now %sactive"
17287 (if (equal (char-after beg) ?<) "" "in")))))
17289 (defun org-at-clock-log-p ()
17290 "Non-nil if point is on a clock log line."
17291 (and (org-match-line org-clock-line-re)
17292 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17294 (defvar org-clock-history) ; defined in org-clock.el
17295 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17296 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17297 "Change the date in the time stamp at point.
17298 The date will be changed by N times WHAT. WHAT can be `day', `month',
17299 `year', `minute', `second'. If WHAT is not given, the cursor position
17300 in the timestamp determines what will be changed.
17301 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17302 (let ((origin (point))
17303 (timestamp? (org-at-timestamp-p 'lax))
17304 origin-cat
17305 with-hm inactive
17306 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17307 extra rem
17308 ts time time0 fixnext clrgx)
17309 (unless timestamp? (user-error "Not at a timestamp"))
17310 (if (and (not what) (eq timestamp? 'bracket))
17311 (org-toggle-timestamp-type)
17312 ;; Point isn't on brackets. Remember the part of the time-stamp
17313 ;; the point was in. Indeed, size of time-stamps may change,
17314 ;; but point must be kept in the same category nonetheless.
17315 (setq origin-cat timestamp?)
17316 (when (and (not what) (not (eq timestamp? 'day))
17317 org-display-custom-times
17318 (get-text-property (point) 'display)
17319 (not (get-text-property (1- (point)) 'display)))
17320 (setq timestamp? 'day))
17321 (setq timestamp? (or what timestamp?)
17322 inactive (= (char-after (match-beginning 0)) ?\[)
17323 ts (match-string 0))
17324 (replace-match "")
17325 (when (string-match
17326 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17328 (setq extra (match-string 1 ts))
17329 (when suppress-tmp-delay
17330 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17331 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17332 (setq with-hm t))
17333 (setq time0 (org-parse-time-string ts))
17334 (when (and updown
17335 (eq timestamp? 'minute)
17336 (not current-prefix-arg))
17337 ;; This looks like s-up and s-down. Change by one rounding step.
17338 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17339 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17340 (setcar (cdr time0) (+ (nth 1 time0)
17341 (if (> n 0) (- rem) (- dm rem))))))
17342 (setq time
17343 (apply #'encode-time
17344 (or (car time0) 0)
17345 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17346 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17347 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17348 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17349 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17350 (nthcdr 6 time0)))
17351 (when (and (memq timestamp? '(hour minute))
17352 extra
17353 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17354 (setq extra (org-modify-ts-extra
17355 extra
17356 (if (eq timestamp? 'hour) 2 5)
17357 n dm)))
17358 (when (integerp timestamp?)
17359 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17360 (when (eq what 'calendar)
17361 (let ((cal-date (org-get-date-from-calendar)))
17362 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17363 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17364 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17365 (setcar time0 (or (car time0) 0))
17366 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17367 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17368 (setq time (apply 'encode-time time0))))
17369 ;; Insert the new time-stamp, and ensure point stays in the same
17370 ;; category as before (i.e. not after the last position in that
17371 ;; category).
17372 (let ((pos (point)))
17373 ;; Stay before inserted string. `save-excursion' is of no use.
17374 (setq org-last-changed-timestamp
17375 (org-insert-time-stamp time with-hm inactive nil nil extra))
17376 (goto-char pos))
17377 (save-match-data
17378 (looking-at org-ts-regexp3)
17379 (goto-char
17380 (pcase origin-cat
17381 ;; `day' category ends before `hour' if any, or at the end
17382 ;; of the day name.
17383 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17384 (`hour (min (match-end 7) origin))
17385 (`minute (min (1- (match-end 8)) origin))
17386 ((pred integerp) (min (1- (match-end 0)) origin))
17387 ;; Point was right after the time-stamp. However, the
17388 ;; time-stamp length might have changed, so refer to
17389 ;; (match-end 0) instead.
17390 (`after (match-end 0))
17391 ;; `year' and `month' have both fixed size: point couldn't
17392 ;; have moved into another part.
17393 (_ origin))))
17394 ;; Update clock if on a CLOCK line.
17395 (org-clock-update-time-maybe)
17396 ;; Maybe adjust the closest clock in `org-clock-history'
17397 (when org-clock-adjust-closest
17398 (if (not (and (org-at-clock-log-p)
17399 (< 1 (length (delq nil (mapcar 'marker-position
17400 org-clock-history))))))
17401 (message "No clock to adjust")
17402 (cond ((save-excursion ; fix previous clock?
17403 (re-search-backward org-ts-regexp0 nil t)
17404 (looking-back (concat org-clock-string " \\[")
17405 (line-beginning-position)))
17406 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17407 ((save-excursion ; fix next clock?
17408 (re-search-backward org-ts-regexp0 nil t)
17409 (looking-at (concat org-ts-regexp0 "\\] =>")))
17410 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17411 (save-window-excursion
17412 ;; Find closest clock to point, adjust the previous/next one in history
17413 (let* ((p (save-excursion (org-back-to-heading t)))
17414 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17415 (clfixnth
17416 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17417 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17418 (if (not clfixpos)
17419 (message "No clock to adjust")
17420 (save-excursion
17421 (org-goto-marker-or-bmk clfixpos)
17422 (org-show-subtree)
17423 (when (re-search-forward clrgx nil t)
17424 (goto-char (match-beginning 1))
17425 (let (org-clock-adjust-closest)
17426 (org-timestamp-change n timestamp? updown))
17427 (message "Clock adjusted in %s for heading: %s"
17428 (file-name-nondirectory (buffer-file-name))
17429 (org-get-heading t t)))))))))
17430 ;; Try to recenter the calendar window, if any.
17431 (when (and org-calendar-follow-timestamp-change
17432 (get-buffer-window "*Calendar*" t)
17433 (memq timestamp? '(day month year)))
17434 (org-recenter-calendar (time-to-days time))))))
17436 (defun org-modify-ts-extra (s pos n dm)
17437 "Change the different parts of the lead-time and repeat fields in timestamp."
17438 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17439 ng h m new rem)
17440 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17441 (cond
17442 ((or (org-pos-in-match-range pos 2)
17443 (org-pos-in-match-range pos 3))
17444 (setq m (string-to-number (match-string 3 s))
17445 h (string-to-number (match-string 2 s)))
17446 (if (org-pos-in-match-range pos 2)
17447 (setq h (+ h n))
17448 (setq n (* dm (with-no-warnings (signum n))))
17449 (unless (= 0 (setq rem (% m dm)))
17450 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17451 (setq m (+ m n)))
17452 (when (< m 0) (setq m (+ m 60) h (1- h)))
17453 (when (> m 59) (setq m (- m 60) h (1+ h)))
17454 (setq h (mod h 24))
17455 (setq ng 1 new (format "-%02d:%02d" h m)))
17456 ((org-pos-in-match-range pos 6)
17457 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17458 ((org-pos-in-match-range pos 5)
17459 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17461 ((org-pos-in-match-range pos 9)
17462 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17463 ((org-pos-in-match-range pos 8)
17464 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17466 (when ng
17467 (setq s (concat
17468 (substring s 0 (match-beginning ng))
17470 (substring s (match-end ng))))))
17473 (defun org-recenter-calendar (d)
17474 "If the calendar is visible, recenter it to date D."
17475 (let ((cwin (get-buffer-window "*Calendar*" t)))
17476 (when cwin
17477 (let ((calendar-move-hook nil))
17478 (with-selected-window cwin
17479 (calendar-goto-date
17480 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17482 (defun org-goto-calendar (&optional arg)
17483 "Go to the Emacs calendar at the current date.
17484 If there is a time stamp in the current line, go to that date.
17485 A prefix ARG can be used to force the current date."
17486 (interactive "P")
17487 (let ((calendar-move-hook nil)
17488 (calendar-view-holidays-initially-flag nil)
17489 (calendar-view-diary-initially-flag nil)
17490 diff)
17491 (when (or (org-at-timestamp-p 'lax)
17492 (org-match-line (concat ".*" org-ts-regexp)))
17493 (let ((d1 (time-to-days (current-time)))
17494 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17495 (setq diff (- d2 d1))))
17496 (calendar)
17497 (calendar-goto-today)
17498 (when (and diff (not arg)) (calendar-forward-day diff))))
17500 (defun org-get-date-from-calendar ()
17501 "Return a list (month day year) of date at point in calendar."
17502 (with-current-buffer "*Calendar*"
17503 (save-match-data
17504 (calendar-cursor-to-date))))
17506 (defun org-date-from-calendar ()
17507 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17508 If there is already a time stamp at the cursor position, update it."
17509 (interactive)
17510 (if (org-at-timestamp-p 'lax)
17511 (org-timestamp-change 0 'calendar)
17512 (let ((cal-date (org-get-date-from-calendar)))
17513 (org-insert-time-stamp
17514 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17516 (defcustom org-effort-durations
17517 `(("min" . 1)
17518 ("h" . 60)
17519 ("d" . ,(* 60 8))
17520 ("w" . ,(* 60 8 5))
17521 ("m" . ,(* 60 8 5 4))
17522 ("y" . ,(* 60 8 5 40)))
17523 "Conversion factor to minutes for an effort modifier.
17525 Each entry has the form (MODIFIER . MINUTES).
17527 In an effort string, a number followed by MODIFIER is multiplied
17528 by the specified number of MINUTES to obtain an effort in
17529 minutes.
17531 For example, if the value of this variable is ((\"hours\" . 60)), then an
17532 effort string \"2hours\" is equivalent to 120 minutes."
17533 :group 'org-agenda
17534 :version "26.1"
17535 :package-version '(Org . "8.3")
17536 :type '(alist :key-type (string :tag "Modifier")
17537 :value-type (number :tag "Minutes")))
17539 (defcustom org-image-actual-width t
17540 "Should we use the actual width of images when inlining them?
17542 When set to t, always use the image width.
17544 When set to a number, use imagemagick (when available) to set
17545 the image's width to this value.
17547 When set to a number in a list, try to get the width from any
17548 #+ATTR.* keyword if it matches a width specification like
17550 #+ATTR_HTML: :width 300px
17552 and fall back on that number if none is found.
17554 When set to nil, try to get the width from an #+ATTR.* keyword
17555 and fall back on the original width if none is found.
17557 This requires Emacs >= 24.1, build with imagemagick support."
17558 :group 'org-appearance
17559 :version "24.4"
17560 :package-version '(Org . "8.0")
17561 :type '(choice
17562 (const :tag "Use the image width" t)
17563 (integer :tag "Use a number of pixels")
17564 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17565 (const :tag "Use #+ATTR* or don't resize" nil)))
17567 (defcustom org-agenda-inhibit-startup nil
17568 "Inhibit startup when preparing agenda buffers.
17569 When this variable is t, the initialization of the Org agenda
17570 buffers is inhibited: e.g. the visibility state is not set, the
17571 tables are not re-aligned, etc."
17572 :type 'boolean
17573 :version "24.3"
17574 :group 'org-agenda)
17576 (defcustom org-agenda-ignore-properties nil
17577 "Avoid updating text properties when building the agenda.
17578 Properties are used to prepare buffers for effort estimates,
17579 appointments, statistics and subtree-local categories.
17580 If you don't use these in the agenda, you can add them to this
17581 list and agenda building will be a bit faster.
17582 The value is a list, with zero or more of the symbols `effort', `appt',
17583 `stats' or `category'."
17584 :type '(set :greedy t
17585 (const effort)
17586 (const appt)
17587 (const stats)
17588 (const category))
17589 :version "26.1"
17590 :package-version '(Org . "8.3")
17591 :group 'org-agenda)
17593 ;;;; Files
17595 (defun org-save-all-org-buffers ()
17596 "Save all Org buffers without user confirmation."
17597 (interactive)
17598 (message "Saving all Org buffers...")
17599 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17600 (when (featurep 'org-id) (org-id-locations-save))
17601 (message "Saving all Org buffers... done"))
17603 (defun org-revert-all-org-buffers ()
17604 "Revert all Org buffers.
17605 Prompt for confirmation when there are unsaved changes.
17606 Be sure you know what you are doing before letting this function
17607 overwrite your changes.
17609 This function is useful in a setup where one tracks Org files
17610 with a version control system, to revert on one machine after pulling
17611 changes from another. I believe the procedure must be like this:
17613 1. M-x org-save-all-org-buffers
17614 2. Pull changes from the other machine, resolve conflicts
17615 3. M-x org-revert-all-org-buffers"
17616 (interactive)
17617 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17618 (user-error "Abort"))
17619 (save-excursion
17620 (save-window-excursion
17621 (dolist (b (buffer-list))
17622 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17623 (with-current-buffer b buffer-file-name))
17624 (pop-to-buffer-same-window b)
17625 (revert-buffer t 'no-confirm)))
17626 (when (and (featurep 'org-id) org-id-track-globally)
17627 (org-id-locations-load)))))
17629 ;;;; Agenda files
17631 ;;;###autoload
17632 (defun org-switchb (&optional arg)
17633 "Switch between Org buffers.
17635 With `\\[universal-argument]' prefix, restrict available buffers to files.
17637 With `\\[universal-argument] \\[universal-argument]' \
17638 prefix, restrict available buffers to agenda files."
17639 (interactive "P")
17640 (let ((blist (org-buffer-list
17641 (cond ((equal arg '(4)) 'files)
17642 ((equal arg '(16)) 'agenda)))))
17643 (pop-to-buffer-same-window
17644 (completing-read "Org buffer: "
17645 (mapcar #'list (mapcar #'buffer-name blist))
17646 nil t))))
17648 (defun org-buffer-list (&optional predicate exclude-tmp)
17649 "Return a list of Org buffers.
17650 PREDICATE can be `export', `files' or `agenda'.
17652 export restrict the list to Export buffers.
17653 files restrict the list to buffers visiting Org files.
17654 agenda restrict the list to buffers visiting agenda files.
17656 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17657 (let* ((bfn nil)
17658 (agenda-files (and (eq predicate 'agenda)
17659 (mapcar 'file-truename (org-agenda-files t))))
17660 (filter
17661 (cond
17662 ((eq predicate 'files)
17663 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17664 ((eq predicate 'export)
17665 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17666 ((eq predicate 'agenda)
17667 (lambda (b)
17668 (with-current-buffer b
17669 (and (derived-mode-p 'org-mode)
17670 (setq bfn (buffer-file-name b))
17671 (member (file-truename bfn) agenda-files)))))
17672 (t (lambda (b) (with-current-buffer b
17673 (or (derived-mode-p 'org-mode)
17674 (string-match "\\*Org .*Export"
17675 (buffer-name b)))))))))
17676 (delq nil
17677 (mapcar
17678 (lambda(b)
17679 (if (and (funcall filter b)
17680 (or (not exclude-tmp)
17681 (not (string-match "tmp" (buffer-name b)))))
17683 nil))
17684 (buffer-list)))))
17686 (defun org-agenda-files (&optional unrestricted archives)
17687 "Get the list of agenda files.
17688 Optional UNRESTRICTED means return the full list even if a restriction
17689 is currently in place.
17690 When ARCHIVES is t, include all archive files that are really being
17691 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17692 `org-agenda-archives-mode' is t."
17693 (let ((files
17694 (cond
17695 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17696 ((stringp org-agenda-files) (org-read-agenda-file-list))
17697 ((listp org-agenda-files) org-agenda-files)
17698 (t (error "Invalid value of `org-agenda-files'")))))
17699 (setq files (apply 'append
17700 (mapcar (lambda (f)
17701 (if (file-directory-p f)
17702 (directory-files
17703 f t org-agenda-file-regexp)
17704 (list f)))
17705 files)))
17706 (when org-agenda-skip-unavailable-files
17707 (setq files (delq nil
17708 (mapcar (function
17709 (lambda (file)
17710 (and (file-readable-p file) file)))
17711 files))))
17712 (when (or (eq archives t)
17713 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17714 (setq files (org-add-archive-files files)))
17715 files))
17717 (defun org-agenda-file-p (&optional file)
17718 "Return non-nil, if FILE is an agenda file.
17719 If FILE is omitted, use the file associated with the current
17720 buffer."
17721 (let ((fname (or file (buffer-file-name))))
17722 (and fname
17723 (member (file-truename fname)
17724 (mapcar #'file-truename (org-agenda-files t))))))
17726 (defun org-edit-agenda-file-list ()
17727 "Edit the list of agenda files.
17728 Depending on setup, this either uses customize to edit the variable
17729 `org-agenda-files', or it visits the file that is holding the list. In the
17730 latter case, the buffer is set up in a way that saving it automatically kills
17731 the buffer and restores the previous window configuration."
17732 (interactive)
17733 (if (stringp org-agenda-files)
17734 (let ((cw (current-window-configuration)))
17735 (find-file org-agenda-files)
17736 (setq-local org-window-configuration cw)
17737 (add-hook 'after-save-hook
17738 (lambda ()
17739 (set-window-configuration
17740 (prog1 org-window-configuration
17741 (kill-buffer (current-buffer))))
17742 (org-install-agenda-files-menu)
17743 (message "New agenda file list installed"))
17744 nil 'local)
17745 (message "%s" (substitute-command-keys
17746 "Edit list and finish with \\[save-buffer]")))
17747 (customize-variable 'org-agenda-files)))
17749 (defun org-store-new-agenda-file-list (list)
17750 "Set new value for the agenda file list and save it correctly."
17751 (if (stringp org-agenda-files)
17752 (let ((fe (org-read-agenda-file-list t)) b u)
17753 (while (setq b (find-buffer-visiting org-agenda-files))
17754 (kill-buffer b))
17755 (with-temp-file org-agenda-files
17756 (insert
17757 (mapconcat
17758 (lambda (f) ;; Keep un-expanded entries.
17759 (if (setq u (assoc f fe))
17760 (cdr u)
17762 list "\n")
17763 "\n")))
17764 (let ((org-mode-hook nil) (org-inhibit-startup t)
17765 (org-insert-mode-line-in-empty-file nil))
17766 (setq org-agenda-files list)
17767 (customize-save-variable 'org-agenda-files org-agenda-files))))
17769 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17770 "Read the list of agenda files from a file.
17771 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17772 filenames, used by `org-store-new-agenda-file-list' to write back
17773 un-expanded file names."
17774 (when (file-directory-p org-agenda-files)
17775 (error "`org-agenda-files' cannot be a single directory"))
17776 (when (stringp org-agenda-files)
17777 (with-temp-buffer
17778 (insert-file-contents org-agenda-files)
17779 (mapcar
17780 (lambda (f)
17781 (let ((e (expand-file-name (substitute-in-file-name f)
17782 org-directory)))
17783 (if pair-with-expansion
17784 (cons e f)
17785 e)))
17786 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17788 ;;;###autoload
17789 (defun org-cycle-agenda-files ()
17790 "Cycle through the files in `org-agenda-files'.
17791 If the current buffer visits an agenda file, find the next one in the list.
17792 If the current buffer does not, find the first agenda file."
17793 (interactive)
17794 (let* ((fs (or (org-agenda-files t)
17795 (user-error "No agenda files")))
17796 (files (copy-sequence fs))
17797 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17798 file)
17799 (when tcf
17800 (while (and (setq file (pop files))
17801 (not (equal (file-truename file) tcf)))))
17802 (find-file (car (or files fs)))
17803 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17805 (defun org-agenda-file-to-front (&optional to-end)
17806 "Move/add the current file to the top of the agenda file list.
17807 If the file is not present in the list, it is added to the front. If it is
17808 present, it is moved there. With optional argument TO-END, add/move to the
17809 end of the list."
17810 (interactive "P")
17811 (let ((org-agenda-skip-unavailable-files nil)
17812 (file-alist (mapcar (lambda (x)
17813 (cons (file-truename x) x))
17814 (org-agenda-files t)))
17815 (ctf (file-truename
17816 (or buffer-file-name
17817 (user-error "Please save the current buffer to a file"))))
17818 x had)
17819 (setq x (assoc ctf file-alist) had x)
17821 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17822 (if to-end
17823 (setq file-alist (append (delq x file-alist) (list x)))
17824 (setq file-alist (cons x (delq x file-alist))))
17825 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17826 (org-install-agenda-files-menu)
17827 (message "File %s to %s of agenda file list"
17828 (if had "moved" "added") (if to-end "end" "front"))))
17830 (defun org-remove-file (&optional file)
17831 "Remove current file from the list of files in variable `org-agenda-files'.
17832 These are the files which are being checked for agenda entries.
17833 Optional argument FILE means use this file instead of the current."
17834 (interactive)
17835 (let* ((org-agenda-skip-unavailable-files nil)
17836 (file (or file buffer-file-name
17837 (user-error "Current buffer does not visit a file")))
17838 (true-file (file-truename file))
17839 (afile (abbreviate-file-name file))
17840 (files (delq nil (mapcar
17841 (lambda (x)
17842 (unless (equal true-file
17843 (file-truename x))
17845 (org-agenda-files t)))))
17846 (if (not (= (length files) (length (org-agenda-files t))))
17847 (progn
17848 (org-store-new-agenda-file-list files)
17849 (org-install-agenda-files-menu)
17850 (message "Removed from Org Agenda list: %s" afile))
17851 (message "File was not in list: %s (not removed)" afile))))
17853 (defun org-file-menu-entry (file)
17854 (vector file (list 'find-file file) t))
17856 (defun org-check-agenda-file (file)
17857 "Make sure FILE exists. If not, ask user what to do."
17858 (unless (file-exists-p file)
17859 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17860 (abbreviate-file-name file))
17861 (let ((r (downcase (read-char-exclusive))))
17862 (cond
17863 ((equal r ?r)
17864 (org-remove-file file)
17865 (throw 'nextfile t))
17866 (t (user-error "Abort"))))))
17868 (defun org-get-agenda-file-buffer (file)
17869 "Get an agenda buffer visiting FILE.
17870 If the buffer needs to be created, add it to the list of buffers
17871 which might be released later."
17872 (let ((buf (org-find-base-buffer-visiting file)))
17873 (if buf
17874 buf ; just return it
17875 ;; Make a new buffer and remember it
17876 (setq buf (find-file-noselect file))
17877 (when buf (push buf org-agenda-new-buffers))
17878 buf)))
17880 (defun org-release-buffers (blist)
17881 "Release all buffers in list, asking the user for confirmation when needed.
17882 When a buffer is unmodified, it is just killed. When modified, it is saved
17883 \(if the user agrees) and then killed."
17884 (let (file)
17885 (dolist (buf blist)
17886 (setq file (buffer-file-name buf))
17887 (when (and (buffer-modified-p buf)
17888 file
17889 (y-or-n-p (format "Save file %s? " file)))
17890 (with-current-buffer buf (save-buffer)))
17891 (kill-buffer buf))))
17893 (defun org-agenda-prepare-buffers (files)
17894 "Create buffers for all agenda files, protect archived trees and comments."
17895 (interactive)
17896 (let ((pa '(:org-archived t))
17897 (pc '(:org-comment t))
17898 (pall '(:org-archived t :org-comment t))
17899 (inhibit-read-only t)
17900 (org-inhibit-startup org-agenda-inhibit-startup)
17901 (rea (concat ":" org-archive-tag ":"))
17902 re pos)
17903 (setq org-tag-alist-for-agenda nil
17904 org-tag-groups-alist-for-agenda nil)
17905 (save-excursion
17906 (save-restriction
17907 (dolist (file files)
17908 (catch 'nextfile
17909 (if (bufferp file)
17910 (set-buffer file)
17911 (org-check-agenda-file file)
17912 (set-buffer (org-get-agenda-file-buffer file)))
17913 (widen)
17914 (org-set-regexps-and-options 'tags-only)
17915 (setq pos (point))
17916 (or (memq 'category org-agenda-ignore-properties)
17917 (org-refresh-category-properties))
17918 (or (memq 'stats org-agenda-ignore-properties)
17919 (org-refresh-stats-properties))
17920 (or (memq 'effort org-agenda-ignore-properties)
17921 (org-refresh-effort-properties))
17922 (or (memq 'appt org-agenda-ignore-properties)
17923 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17924 (setq org-todo-keywords-for-agenda
17925 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17926 (setq org-done-keywords-for-agenda
17927 (append org-done-keywords-for-agenda org-done-keywords))
17928 (setq org-todo-keyword-alist-for-agenda
17929 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17930 (setq org-tag-alist-for-agenda
17931 (org-uniquify
17932 (append org-tag-alist-for-agenda
17933 org-current-tag-alist)))
17934 ;; Merge current file's tag groups into global
17935 ;; `org-tag-groups-alist-for-agenda'.
17936 (when org-group-tags
17937 (dolist (alist org-tag-groups-alist)
17938 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17939 (if old
17940 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17941 (push alist org-tag-groups-alist-for-agenda)))))
17942 (org-with-silent-modifications
17943 (save-excursion
17944 (remove-text-properties (point-min) (point-max) pall)
17945 (when org-agenda-skip-archived-trees
17946 (goto-char (point-min))
17947 (while (re-search-forward rea nil t)
17948 (when (org-at-heading-p t)
17949 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17950 (goto-char (point-min))
17951 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17952 (while (re-search-forward re nil t)
17953 (when (save-match-data (org-in-commented-heading-p t))
17954 (add-text-properties
17955 (match-beginning 0) (org-end-of-subtree t) pc)))))
17956 (goto-char pos)))))
17957 (setq org-todo-keywords-for-agenda
17958 (org-uniquify org-todo-keywords-for-agenda))
17959 (setq org-todo-keyword-alist-for-agenda
17960 (org-uniquify org-todo-keyword-alist-for-agenda))))
17963 ;;;; CDLaTeX minor mode
17965 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17966 "Keymap for the minor `org-cdlatex-mode'.")
17968 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17969 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17970 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17971 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17972 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
17974 (defvar org-cdlatex-texmathp-advice-is-done nil
17975 "Flag remembering if we have applied the advice to texmathp already.")
17977 (define-minor-mode org-cdlatex-mode
17978 "Toggle the minor `org-cdlatex-mode'.
17979 This mode supports entering LaTeX environment and math in LaTeX fragments
17980 in Org mode.
17981 \\{org-cdlatex-mode-map}"
17982 nil " OCDL" nil
17983 (when org-cdlatex-mode
17984 (require 'cdlatex)
17985 (run-hooks 'cdlatex-mode-hook)
17986 (cdlatex-compute-tables))
17987 (unless org-cdlatex-texmathp-advice-is-done
17988 (setq org-cdlatex-texmathp-advice-is-done t)
17989 (defadvice texmathp (around org-math-always-on activate)
17990 "Always return t in Org buffers.
17991 This is because we want to insert math symbols without dollars even outside
17992 the LaTeX math segments. If Org mode thinks that point is actually inside
17993 an embedded LaTeX fragment, let `texmathp' do its job.
17994 `\\[org-cdlatex-mode-map]'"
17995 (interactive)
17996 (let (p)
17997 (cond
17998 ((not (derived-mode-p 'org-mode)) ad-do-it)
17999 ((eq this-command 'cdlatex-math-symbol)
18000 (setq ad-return-value t
18001 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18003 (let ((p (org-inside-LaTeX-fragment-p)))
18004 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18005 (setq ad-return-value t
18006 texmathp-why '("Org mode embedded math" . 0))
18007 (when p ad-do-it)))))))))
18009 (defun turn-on-org-cdlatex ()
18010 "Unconditionally turn on `org-cdlatex-mode'."
18011 (org-cdlatex-mode 1))
18013 (defun org-try-cdlatex-tab ()
18014 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18015 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18016 - inside a LaTeX fragment, or
18017 - after the first word in a line, where an abbreviation expansion could
18018 insert a LaTeX environment."
18019 (when org-cdlatex-mode
18020 (cond
18021 ;; Before any word on the line: No expansion possible.
18022 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18023 ;; Just after first word on the line: Expand it. Make sure it
18024 ;; cannot happen on headlines, though.
18025 ((save-excursion
18026 (skip-chars-backward "a-zA-Z0-9*")
18027 (skip-chars-backward " \t")
18028 (and (bolp) (not (org-at-heading-p))))
18029 (cdlatex-tab) t)
18030 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18032 (defun org-cdlatex-underscore-caret (&optional _arg)
18033 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18034 Revert to the normal definition outside of these fragments."
18035 (interactive "P")
18036 (if (org-inside-LaTeX-fragment-p)
18037 (call-interactively 'cdlatex-sub-superscript)
18038 (let (org-cdlatex-mode)
18039 (call-interactively (key-binding (vector last-input-event))))))
18041 (defun org-cdlatex-math-modify (&optional _arg)
18042 "Execute `cdlatex-math-modify' in LaTeX fragments.
18043 Revert to the normal definition outside of these fragments."
18044 (interactive "P")
18045 (if (org-inside-LaTeX-fragment-p)
18046 (call-interactively 'cdlatex-math-modify)
18047 (let (org-cdlatex-mode)
18048 (call-interactively (key-binding (vector last-input-event))))))
18050 (defun org-cdlatex-environment-indent (&optional environment item)
18051 "Execute `cdlatex-environment' and indent the inserted environment.
18053 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18055 The inserted environment is indented to current indentation
18056 unless point is at the beginning of the line, in which the
18057 environment remains unintended."
18058 (interactive)
18059 ;; cdlatex-environment always return nil. Therefore, capture output
18060 ;; first and determine if an environment was selected.
18061 (let* ((beg (point-marker))
18062 (end (copy-marker (point) t))
18063 (inserted (progn
18064 (ignore-errors (cdlatex-environment environment item))
18065 (< beg end)))
18066 ;; Figure out how many lines to move forward after the
18067 ;; environment has been inserted.
18068 (lines (when inserted
18069 (save-excursion
18070 (- (cl-loop while (< beg (point))
18071 with x = 0
18072 do (forward-line -1)
18073 (cl-incf x)
18074 finally return x)
18075 (if (progn (goto-char beg)
18076 (and (progn (skip-chars-forward " \t") (eolp))
18077 (progn (skip-chars-backward " \t") (bolp))))
18078 1 0)))))
18079 (env (org-trim (delete-and-extract-region beg end))))
18080 (when inserted
18081 ;; Get indentation of next line unless at column 0.
18082 (let ((ind (if (bolp) 0
18083 (save-excursion
18084 (org-return-indent)
18085 (prog1 (org-get-indentation)
18086 (when (progn (skip-chars-forward " \t") (eolp))
18087 (delete-region beg (point)))))))
18088 (bol (progn (skip-chars-backward " \t") (bolp))))
18089 ;; Insert a newline before environment unless at column zero
18090 ;; to "escape" the current line. Insert a newline if
18091 ;; something is one the same line as \end{ENVIRONMENT}.
18092 (insert
18093 (concat (unless bol "\n") env
18094 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18095 (unless (zerop ind)
18096 (save-excursion
18097 (goto-char beg)
18098 (while (< (point) end)
18099 (unless (eolp) (indent-line-to ind))
18100 (forward-line))))
18101 (goto-char beg)
18102 (forward-line lines)
18103 (indent-line-to ind)))
18104 (set-marker beg nil)
18105 (set-marker end nil)))
18108 ;;;; LaTeX fragments
18110 (defun org-inside-LaTeX-fragment-p ()
18111 "Test if point is inside a LaTeX fragment.
18112 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18113 sequence appearing also before point.
18114 Even though the matchers for math are configurable, this function assumes
18115 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18116 delimiters are skipped when they have been removed by customization.
18117 The return value is nil, or a cons cell with the delimiter and the
18118 position of this delimiter.
18120 This function does a reasonably good job, but can locally be fooled by
18121 for example currency specifications. For example it will assume being in
18122 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18123 fragments that are properly closed, but during editing, we have to live
18124 with the uncertainty caused by missing closing delimiters. This function
18125 looks only before point, not after."
18126 (catch 'exit
18127 (let ((pos (point))
18128 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18129 (lim (save-excursion (org-backward-paragraph) (point)))
18130 dd-on str (start 0) m re)
18131 (goto-char pos)
18132 (when dodollar
18133 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18134 re (nth 1 (assoc "$" org-latex-regexps)))
18135 (while (string-match re str start)
18136 (cond
18137 ((= (match-end 0) (length str))
18138 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18139 ((= (match-end 0) (- (length str) 5))
18140 (throw 'exit nil))
18141 (t (setq start (match-end 0))))))
18142 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18143 (goto-char pos)
18144 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18145 (and (match-beginning 2) (throw 'exit nil))
18146 ;; count $$
18147 (while (re-search-backward "\\$\\$" lim t)
18148 (setq dd-on (not dd-on)))
18149 (goto-char pos)
18150 (when dd-on (cons "$$" m))))))
18152 (defun org-inside-latex-macro-p ()
18153 "Is point inside a LaTeX macro or its arguments?"
18154 (save-match-data
18155 (org-in-regexp
18156 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18158 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18159 "Build an overlay between BEG and END using IMAGE file.
18160 Argument IMAGETYPE is the extension of the displayed image,
18161 as a string. It defaults to \"png\"."
18162 (let ((ov (make-overlay beg end))
18163 (imagetype (or (intern imagetype) 'png)))
18164 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18165 (overlay-put ov 'evaporate t)
18166 (overlay-put ov
18167 'modification-hooks
18168 (list (lambda (o _flag _beg _end &optional _l)
18169 (delete-overlay o))))
18170 (overlay-put ov
18171 'display
18172 (list 'image :type imagetype :file image :ascent 'center))))
18174 (defun org--list-latex-overlays (&optional beg end)
18175 "List all Org LaTeX overlays in current buffer.
18176 Limit to overlays between BEG and END when those are provided."
18177 (cl-remove-if-not
18178 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18179 (overlays-in (or beg (point-min)) (or end (point-max)))))
18181 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18182 "Remove all overlays with LaTeX fragment images in current buffer.
18183 When optional arguments BEG and END are non-nil, remove all
18184 overlays between them instead. Return a non-nil value when some
18185 overlays were removed, nil otherwise."
18186 (let ((overlays (org--list-latex-overlays beg end)))
18187 (mapc #'delete-overlay overlays)
18188 overlays))
18190 (defun org-toggle-latex-fragment (&optional arg)
18191 "Preview the LaTeX fragment at point, or all locally or globally.
18193 If the cursor is on a LaTeX fragment, create the image and overlay
18194 it over the source code, if there is none. Remove it otherwise.
18195 If there is no fragment at point, display all fragments in the
18196 current section.
18198 With prefix ARG, preview or clear image for all fragments in the
18199 current subtree or in the whole buffer when used before the first
18200 headline. With a prefix ARG `\\[universal-argument] \
18201 \\[universal-argument]' preview or clear images
18202 for all fragments in the buffer."
18203 (interactive "P")
18204 (when (display-graphic-p)
18205 (catch 'exit
18206 (save-excursion
18207 (let (beg end msg)
18208 (cond
18209 ((or (equal arg '(16))
18210 (and (equal arg '(4))
18211 (org-with-limited-levels (org-before-first-heading-p))))
18212 (if (org-remove-latex-fragment-image-overlays)
18213 (progn (message "LaTeX fragments images removed from buffer")
18214 (throw 'exit nil))
18215 (setq msg "Creating images for buffer...")))
18216 ((equal arg '(4))
18217 (org-with-limited-levels (org-back-to-heading t))
18218 (setq beg (point))
18219 (setq end (progn (org-end-of-subtree t) (point)))
18220 (if (org-remove-latex-fragment-image-overlays beg end)
18221 (progn
18222 (message "LaTeX fragment images removed from subtree")
18223 (throw 'exit nil))
18224 (setq msg "Creating images for subtree...")))
18225 ((let ((datum (org-element-context)))
18226 (when (memq (org-element-type datum)
18227 '(latex-environment latex-fragment))
18228 (setq beg (org-element-property :begin datum))
18229 (setq end (org-element-property :end datum))
18230 (if (org-remove-latex-fragment-image-overlays beg end)
18231 (progn (message "LaTeX fragment image removed")
18232 (throw 'exit nil))
18233 (setq msg "Creating image...")))))
18235 (org-with-limited-levels
18236 (setq beg (if (org-at-heading-p) (line-beginning-position)
18237 (outline-previous-heading)
18238 (point)))
18239 (setq end (progn (outline-next-heading) (point)))
18240 (if (org-remove-latex-fragment-image-overlays beg end)
18241 (progn
18242 (message "LaTeX fragment images removed from section")
18243 (throw 'exit nil))
18244 (setq msg "Creating images for section...")))))
18245 (let ((file (buffer-file-name (buffer-base-buffer))))
18246 (org-format-latex
18247 (concat org-preview-latex-image-directory "org-ltximg")
18248 beg end
18249 ;; Emacs cannot overlay images from remote hosts. Create
18250 ;; it in `temporary-file-directory' instead.
18251 (if (or (not file) (file-remote-p file))
18252 temporary-file-directory
18253 default-directory)
18254 'overlays msg 'forbuffer org-preview-latex-default-process))
18255 (message (concat msg "done")))))))
18257 (defun org-format-latex
18258 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18259 "Replace LaTeX fragments with links to an image.
18261 The function takes care of creating the replacement image.
18263 Only consider fragments between BEG and END when those are
18264 provided.
18266 When optional argument OVERLAYS is non-nil, display the image on
18267 top of the fragment instead of replacing it.
18269 PROCESSING-TYPE is the conversion method to use, as a symbol.
18271 Some of the options can be changed using the variable
18272 `org-format-latex-options', which see."
18273 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18274 (unless (eq processing-type 'verbatim)
18275 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18276 (cnt 0)
18277 checkdir-flag)
18278 (goto-char (or beg (point-min)))
18279 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18280 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18281 (overlay-recenter (or end (point-max))))
18282 (while (re-search-forward math-regexp end t)
18283 (unless (and overlays
18284 (eq (get-char-property (point) 'org-overlay-type)
18285 'org-latex-overlay))
18286 (let* ((context (org-element-context))
18287 (type (org-element-type context)))
18288 (when (memq type '(latex-environment latex-fragment))
18289 (let ((block-type (eq type 'latex-environment))
18290 (value (org-element-property :value context))
18291 (beg (org-element-property :begin context))
18292 (end (save-excursion
18293 (goto-char (org-element-property :end context))
18294 (skip-chars-backward " \r\t\n")
18295 (point))))
18296 (cond
18297 ((eq processing-type 'mathjax)
18298 ;; Prepare for MathJax processing.
18299 (if (not (string-match "\\`\\$\\$?" value))
18300 (goto-char end)
18301 (delete-region beg end)
18302 (if (string= (match-string 0 value) "$$")
18303 (insert "\\[" (substring value 2 -2) "\\]")
18304 (insert "\\(" (substring value 1 -1) "\\)"))))
18305 ((assq processing-type org-preview-latex-process-alist)
18306 ;; Process to an image.
18307 (cl-incf cnt)
18308 (goto-char beg)
18309 (let* ((processing-info
18310 (cdr (assq processing-type org-preview-latex-process-alist)))
18311 (face (face-at-point))
18312 ;; Get the colors from the face at point.
18314 (let ((color (plist-get org-format-latex-options
18315 :foreground)))
18316 (if (and forbuffer (eq color 'auto))
18317 (face-attribute face :foreground nil 'default)
18318 color)))
18320 (let ((color (plist-get org-format-latex-options
18321 :background)))
18322 (if (and forbuffer (eq color 'auto))
18323 (face-attribute face :background nil 'default)
18324 color)))
18325 (hash (sha1 (prin1-to-string
18326 (list org-format-latex-header
18327 org-latex-default-packages-alist
18328 org-latex-packages-alist
18329 org-format-latex-options
18330 forbuffer value fg bg))))
18331 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18332 (absprefix (expand-file-name prefix dir))
18333 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18334 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18335 (sep (and block-type "\n\n"))
18336 (link (concat sep "[[file:" linkfile "]]" sep))
18337 (options
18338 (org-combine-plists
18339 org-format-latex-options
18340 `(:foreground ,fg :background ,bg))))
18341 (when msg (message msg cnt))
18342 (unless checkdir-flag ; Ensure the directory exists.
18343 (setq checkdir-flag t)
18344 (let ((todir (file-name-directory absprefix)))
18345 (unless (file-directory-p todir)
18346 (make-directory todir t))))
18347 (unless (file-exists-p movefile)
18348 (org-create-formula-image
18349 value movefile options forbuffer processing-type))
18350 (if overlays
18351 (progn
18352 (dolist (o (overlays-in beg end))
18353 (when (eq (overlay-get o 'org-overlay-type)
18354 'org-latex-overlay)
18355 (delete-overlay o)))
18356 (org--format-latex-make-overlay beg end movefile imagetype)
18357 (goto-char end))
18358 (delete-region beg end)
18359 (insert
18360 (org-add-props link
18361 (list 'org-latex-src
18362 (replace-regexp-in-string "\"" "" value)
18363 'org-latex-src-embed-type
18364 (if block-type 'paragraph 'character)))))))
18365 ((eq processing-type 'mathml)
18366 ;; Process to MathML.
18367 (unless (org-format-latex-mathml-available-p)
18368 (user-error "LaTeX to MathML converter not configured"))
18369 (cl-incf cnt)
18370 (when msg (message msg cnt))
18371 (goto-char beg)
18372 (delete-region beg end)
18373 (insert (org-format-latex-as-mathml
18374 value block-type prefix dir)))
18376 (error "Unknown conversion process %s for LaTeX fragments"
18377 processing-type)))))))))))
18379 (defun org-create-math-formula (latex-frag &optional mathml-file)
18380 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18381 Use `org-latex-to-mathml-convert-command'. If the conversion is
18382 sucessful, return the portion between \"<math...> </math>\"
18383 elements otherwise return nil. When MATHML-FILE is specified,
18384 write the results in to that file. When invoked as an
18385 interactive command, prompt for LATEX-FRAG, with initial value
18386 set to the current active region and echo the results for user
18387 inspection."
18388 (interactive (list (let ((frag (when (org-region-active-p)
18389 (buffer-substring-no-properties
18390 (region-beginning) (region-end)))))
18391 (read-string "LaTeX Fragment: " frag nil frag))))
18392 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18393 (let* ((tmp-in-file
18394 (let ((file (file-relative-name
18395 (make-temp-name (expand-file-name "ltxmathml-in")))))
18396 (write-region latex-frag nil file)
18397 file))
18398 (tmp-out-file (file-relative-name
18399 (make-temp-name (expand-file-name "ltxmathml-out"))))
18400 (cmd (format-spec
18401 org-latex-to-mathml-convert-command
18402 `((?j . ,(and org-latex-to-mathml-jar-file
18403 (shell-quote-argument
18404 (expand-file-name
18405 org-latex-to-mathml-jar-file))))
18406 (?I . ,(shell-quote-argument tmp-in-file))
18407 (?i . ,latex-frag)
18408 (?o . ,(shell-quote-argument tmp-out-file)))))
18409 mathml shell-command-output)
18410 (when (called-interactively-p 'any)
18411 (unless (org-format-latex-mathml-available-p)
18412 (user-error "LaTeX to MathML converter not configured")))
18413 (message "Running %s" cmd)
18414 (setq shell-command-output (shell-command-to-string cmd))
18415 (setq mathml
18416 (when (file-readable-p tmp-out-file)
18417 (with-current-buffer (find-file-noselect tmp-out-file t)
18418 (goto-char (point-min))
18419 (when (re-search-forward
18420 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18421 (regexp-quote
18422 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18423 nil t)
18424 (prog1 (match-string 0) (kill-buffer))))))
18425 (cond
18426 (mathml
18427 (setq mathml
18428 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18429 (when mathml-file
18430 (write-region mathml nil mathml-file))
18431 (when (called-interactively-p 'any)
18432 (message mathml)))
18433 ((message "LaTeX to MathML conversion failed")
18434 (message shell-command-output)))
18435 (delete-file tmp-in-file)
18436 (when (file-exists-p tmp-out-file)
18437 (delete-file tmp-out-file))
18438 mathml))
18440 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18441 prefix &optional dir)
18442 "Use `org-create-math-formula' but check local cache first."
18443 (let* ((absprefix (expand-file-name prefix dir))
18444 (print-length nil) (print-level nil)
18445 (formula-id (concat
18446 "formula-"
18447 (sha1
18448 (prin1-to-string
18449 (list latex-frag
18450 org-latex-to-mathml-convert-command)))))
18451 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18452 (formula-cache-dir (file-name-directory formula-cache)))
18454 (unless (file-directory-p formula-cache-dir)
18455 (make-directory formula-cache-dir t))
18457 (unless (file-exists-p formula-cache)
18458 (org-create-math-formula latex-frag formula-cache))
18460 (if (file-exists-p formula-cache)
18461 ;; Successful conversion. Return the link to MathML file.
18462 (org-add-props
18463 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18464 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18465 'org-latex-src-embed-type (if latex-frag-type
18466 'paragraph 'character)))
18467 ;; Failed conversion. Return the LaTeX fragment verbatim
18468 latex-frag)))
18470 (defun org--get-display-dpi ()
18471 "Get the DPI of the display.
18472 The function assumes that the display has the same pixel width in
18473 the horizontal and vertical directions."
18474 (if (display-graphic-p)
18475 (round (/ (display-pixel-height)
18476 (/ (display-mm-height) 25.4)))
18477 (error "Attempt to calculate the dpi of a non-graphic display")))
18479 (defun org-create-formula-image
18480 (string tofile options buffer &optional processing-type)
18481 "Create an image from LaTeX source using external processes.
18483 The LaTeX STRING is saved to a temporary LaTeX file, then
18484 converted to an image file by process PROCESSING-TYPE defined in
18485 `org-preview-latex-process-alist'. A nil value defaults to
18486 `org-preview-latex-default-process'.
18488 The generated image file is eventually moved to TOFILE.
18490 The OPTIONS argument controls the size, foreground color and
18491 background color of the generated image.
18493 When BUFFER non-nil, this function is used for LaTeX previewing.
18494 Otherwise, it is used to deal with LaTeX snippets showed in
18495 a HTML file."
18496 (let* ((processing-type (or processing-type
18497 org-preview-latex-default-process))
18498 (processing-info
18499 (cdr (assq processing-type org-preview-latex-process-alist)))
18500 (programs (plist-get processing-info :programs))
18501 (error-message (or (plist-get processing-info :message) ""))
18502 (use-xcolor (plist-get processing-info :use-xcolor))
18503 (image-input-type (plist-get processing-info :image-input-type))
18504 (image-output-type (plist-get processing-info :image-output-type))
18505 (post-clean (or (plist-get processing-info :post-clean)
18506 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18507 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18508 (latex-header
18509 (or (plist-get processing-info :latex-header)
18510 (org-latex-make-preamble
18511 (org-export-get-environment (org-export-get-backend 'latex))
18512 org-format-latex-header
18513 'snippet)))
18514 (latex-compiler (plist-get processing-info :latex-compiler))
18515 (image-converter (plist-get processing-info :image-converter))
18516 (tmpdir temporary-file-directory)
18517 (texfilebase (make-temp-name
18518 (expand-file-name "orgtex" tmpdir)))
18519 (texfile (concat texfilebase ".tex"))
18520 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18521 '(1.0 . 1.0)))
18522 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18523 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18524 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18525 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18526 "Black"))
18527 (bg (or (plist-get options (if buffer :background :html-background))
18528 "Transparent"))
18529 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18530 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18531 (dolist (program programs)
18532 (org-check-external-command program error-message))
18533 (if use-xcolor
18534 (progn (if (eq fg 'default)
18535 (setq fg (org-latex-color :foreground))
18536 (setq fg (org-latex-color-format fg)))
18537 (if (eq bg 'default)
18538 (setq bg (org-latex-color :background))
18539 (setq bg (org-latex-color-format
18540 (if (string= bg "Transparent") "white" bg))))
18541 (with-temp-file texfile
18542 (insert latex-header)
18543 (insert "\n\\begin{document}\n"
18544 "\\definecolor{fg}{rgb}{" fg "}\n"
18545 "\\definecolor{bg}{rgb}{" bg "}\n"
18546 "\n\\pagecolor{bg}\n"
18547 "\n{\\color{fg}\n"
18548 string
18549 "\n}\n"
18550 "\n\\end{document}\n")))
18551 (if (eq fg 'default)
18552 (setq fg (org-dvipng-color :foreground))
18553 (unless (string= fg "Transparent")
18554 (setq fg (org-dvipng-color-format fg))))
18555 (if (eq bg 'default)
18556 (setq bg (org-dvipng-color :background))
18557 (unless (string= bg "Transparent")
18558 (setq bg (org-dvipng-color-format bg))))
18559 (with-temp-file texfile
18560 (insert latex-header)
18561 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18563 (let* ((err-msg (format "Please adjust `%s' part of \
18564 `org-preview-latex-process-alist'."
18565 processing-type))
18566 (image-input-file
18567 (org-compile-file
18568 texfile latex-compiler image-input-type err-msg log-buf))
18569 (image-output-file
18570 (org-compile-file
18571 image-input-file image-converter image-output-type err-msg log-buf
18572 `((?F . ,(shell-quote-argument fg))
18573 (?B . ,(shell-quote-argument bg))
18574 (?D . ,(shell-quote-argument (format "%s" dpi)))
18575 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18576 (copy-file image-output-file tofile 'replace)
18577 (dolist (e post-clean)
18578 (when (file-exists-p (concat texfilebase e))
18579 (delete-file (concat texfilebase e))))
18580 image-output-file)))
18582 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18583 "Fill a LaTeX header template TPL.
18584 In the template, the following place holders will be recognized:
18586 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18587 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18588 [PACKAGES] \\usepackage statements for PKG
18589 [NO-PACKAGES] do not include PKG
18590 [EXTRA] the string EXTRA
18591 [NO-EXTRA] do not include EXTRA
18593 For backward compatibility, if both the positive and the negative place
18594 holder is missing, the positive one (without the \"NO-\") will be
18595 assumed to be present at the end of the template.
18596 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18597 EXTRA is a string.
18598 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18599 (let (rpl (end ""))
18600 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18601 (setq rpl (if (or (match-end 1) (not def-pkg))
18602 "" (org-latex-packages-to-string def-pkg snippets-p t))
18603 tpl (replace-match rpl t t tpl))
18604 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18606 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18607 (setq rpl (if (or (match-end 1) (not pkg))
18608 "" (org-latex-packages-to-string pkg snippets-p t))
18609 tpl (replace-match rpl t t tpl))
18610 (when pkg (setq end
18611 (concat end "\n"
18612 (org-latex-packages-to-string pkg snippets-p)))))
18614 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18615 (setq rpl (if (or (match-end 1) (not extra))
18616 "" (concat extra "\n"))
18617 tpl (replace-match rpl t t tpl))
18618 (when (and extra (string-match "\\S-" extra))
18619 (setq end (concat end "\n" extra))))
18621 (if (string-match "\\S-" end)
18622 (concat tpl "\n" end)
18623 tpl)))
18625 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18626 "Turn an alist of packages into a string with the \\usepackage macros."
18627 (setq pkg (mapconcat (lambda(p)
18628 (cond
18629 ((stringp p) p)
18630 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18631 (format "%% Package %s omitted" (cadr p)))
18632 ((equal "" (car p))
18633 (format "\\usepackage{%s}" (cadr p)))
18635 (format "\\usepackage[%s]{%s}"
18636 (car p) (cadr p)))))
18638 "\n"))
18639 (if newline (concat pkg "\n") pkg))
18641 (defun org-dvipng-color (attr)
18642 "Return a RGB color specification for dvipng."
18643 (org-dvipng-color-format (face-attribute 'default attr nil)))
18645 (defun org-dvipng-color-format (color-name)
18646 "Convert COLOR-NAME to a RGB color value for dvipng."
18647 (apply #'format "rgb %s %s %s"
18648 (mapcar 'org-normalize-color
18649 (color-values color-name))))
18651 (defun org-latex-color (attr)
18652 "Return a RGB color for the LaTeX color package."
18653 (org-latex-color-format (face-attribute 'default attr nil)))
18655 (defun org-latex-color-format (color-name)
18656 "Convert COLOR-NAME to a RGB color value."
18657 (apply #'format "%s,%s,%s"
18658 (mapcar 'org-normalize-color
18659 (color-values color-name))))
18661 (defun org-normalize-color (value)
18662 "Return string to be used as color value for an RGB component."
18663 (format "%g" (/ value 65535.0)))
18667 ;; Image display
18669 (defvar-local org-inline-image-overlays nil)
18671 (defun org-toggle-inline-images (&optional include-linked)
18672 "Toggle the display of inline images.
18673 INCLUDE-LINKED is passed to `org-display-inline-images'."
18674 (interactive "P")
18675 (if org-inline-image-overlays
18676 (progn
18677 (org-remove-inline-images)
18678 (when (called-interactively-p 'interactive)
18679 (message "Inline image display turned off")))
18680 (org-display-inline-images include-linked)
18681 (when (called-interactively-p 'interactive)
18682 (message (if org-inline-image-overlays
18683 (format "%d images displayed inline"
18684 (length org-inline-image-overlays))
18685 "No images to display inline")))))
18687 (defun org-redisplay-inline-images ()
18688 "Refresh the display of inline images."
18689 (interactive)
18690 (if (not org-inline-image-overlays)
18691 (org-toggle-inline-images)
18692 (org-toggle-inline-images)
18693 (org-toggle-inline-images)))
18695 (defun org-display-inline-images (&optional include-linked refresh beg end)
18696 "Display inline images.
18698 An inline image is a link which follows either of these
18699 conventions:
18701 1. Its path is a file with an extension matching return value
18702 from `image-file-name-regexp' and it has no contents.
18704 2. Its description consists in a single link of the previous
18705 type.
18707 When optional argument INCLUDE-LINKED is non-nil, also links with
18708 a text description part will be inlined. This can be nice for
18709 a quick look at those images, but it does not reflect what
18710 exported files will look like.
18712 When optional argument REFRESH is non-nil, refresh existing
18713 images between BEG and END. This will create new image displays
18714 only if necessary. BEG and END default to the buffer
18715 boundaries."
18716 (interactive "P")
18717 (when (display-graphic-p)
18718 (unless refresh
18719 (org-remove-inline-images)
18720 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18721 (org-with-wide-buffer
18722 (goto-char (or beg (point-min)))
18723 (let* ((case-fold-search t)
18724 (file-extension-re (image-file-name-regexp))
18725 (link-abbrevs (mapcar #'car
18726 (append org-link-abbrev-alist-local
18727 org-link-abbrev-alist)))
18728 ;; Check absolute, relative file names and explicit
18729 ;; "file:" links. Also check link abbreviations since
18730 ;; some might expand to "file" links.
18731 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18732 (if (not link-abbrevs) ""
18733 (format "\\|\\(?:%s:\\)"
18734 (regexp-opt link-abbrevs))))))
18735 (while (re-search-forward file-types-re end t)
18736 (let ((link (save-match-data (org-element-context))))
18737 ;; Check if we're at an inline image, i.e., an image file
18738 ;; link without a description (unless INCLUDE-LINKED is
18739 ;; non-nil).
18740 (when (and (equal "file" (org-element-property :type link))
18741 (or include-linked
18742 (null (org-element-contents link)))
18743 (string-match-p file-extension-re
18744 (org-element-property :path link)))
18745 (let ((file (expand-file-name
18746 (org-link-unescape
18747 (org-element-property :path link)))))
18748 (when (file-exists-p file)
18749 (let ((width
18750 ;; Apply `org-image-actual-width' specifications.
18751 (cond
18752 ((not (image-type-available-p 'imagemagick)) nil)
18753 ((eq org-image-actual-width t) nil)
18754 ((listp org-image-actual-width)
18756 ;; First try to find a width among
18757 ;; attributes associated to the paragraph
18758 ;; containing link.
18759 (let ((paragraph
18760 (let ((e link))
18761 (while (and (setq e (org-element-property
18762 :parent e))
18763 (not (eq (org-element-type e)
18764 'paragraph))))
18765 e)))
18766 (when paragraph
18767 (save-excursion
18768 (goto-char (org-element-property :begin paragraph))
18769 (when
18770 (re-search-forward
18771 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18772 (org-element-property
18773 :post-affiliated paragraph)
18775 (string-to-number (match-string 1))))))
18776 ;; Otherwise, fall-back to provided number.
18777 (car org-image-actual-width)))
18778 ((numberp org-image-actual-width)
18779 org-image-actual-width)))
18780 (old (get-char-property-and-overlay
18781 (org-element-property :begin link)
18782 'org-image-overlay)))
18783 (if (and (car-safe old) refresh)
18784 (image-refresh (overlay-get (cdr old) 'display))
18785 (let ((image (create-image file
18786 (and width 'imagemagick)
18788 :width width)))
18789 (when image
18790 (let ((ov (make-overlay
18791 (org-element-property :begin link)
18792 (progn
18793 (goto-char
18794 (org-element-property :end link))
18795 (skip-chars-backward " \t")
18796 (point)))))
18797 (overlay-put ov 'display image)
18798 (overlay-put ov 'face 'default)
18799 (overlay-put ov 'org-image-overlay t)
18800 (overlay-put
18801 ov 'modification-hooks
18802 (list 'org-display-inline-remove-overlay))
18803 (push ov org-inline-image-overlays)))))))))))))))
18805 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18806 "Remove inline-display overlay if a corresponding region is modified."
18807 (let ((inhibit-modification-hooks t))
18808 (when (and ov after)
18809 (delete ov org-inline-image-overlays)
18810 (delete-overlay ov))))
18812 (defun org-remove-inline-images ()
18813 "Remove inline display of images."
18814 (interactive)
18815 (mapc #'delete-overlay org-inline-image-overlays)
18816 (setq org-inline-image-overlays nil))
18819 ;;; Key bindings
18821 (defun org-remap (map &rest commands)
18822 "In MAP, remap the functions given in COMMANDS.
18823 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18824 (let (new old)
18825 (while commands
18826 (setq old (pop commands) new (pop commands))
18827 (org-defkey map (vector 'remap old) new))))
18829 ;;;; Outline functions that can be remapped in Org
18830 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18831 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18832 (define-key org-mode-map [remap outline-forward-same-level]
18833 #'org-forward-heading-same-level)
18834 (define-key org-mode-map [remap outline-backward-same-level]
18835 #'org-backward-heading-same-level)
18836 (define-key org-mode-map [remap outline-show-branches]
18837 #'org-kill-note-or-show-branches)
18838 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18839 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18840 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18841 (define-key org-mode-map [remap outline-next-visible-heading]
18842 #'org-next-visible-heading)
18843 (define-key org-mode-map [remap outline-previous-visible-heading]
18844 #'org-previous-visible-heading)
18845 (define-key org-mode-map [remap show-children] #'org-show-children)
18847 ;;;; Make `C-c C-x' a prefix key
18848 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18850 ;;;; TAB key with modifiers
18851 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18852 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18853 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18854 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18855 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18857 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18858 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18859 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18861 ;;;; RET key with modifiers
18862 (org-defkey org-mode-map (kbd "S-RET") #'org-table-copy-down)
18863 (org-defkey org-mode-map (kbd "M-S-RET") #'org-insert-todo-heading)
18864 (org-defkey org-mode-map (kbd "ESC S-RET") #'org-insert-todo-heading)
18865 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18866 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18868 ;;;; Cursor keys with modifiers
18869 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18870 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18871 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18872 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18873 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18874 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18875 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18877 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18878 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18879 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18880 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18881 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18882 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18883 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18884 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18885 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18886 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18888 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18889 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18890 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18891 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18893 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18894 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18895 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18896 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18898 ;;;; Babel keys
18899 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18900 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18901 (define-key org-babel-map key def))
18903 ;;;; Extra keys for TTY access.
18905 ;; We only set them when really needed because otherwise the
18906 ;; menus don't show the simple keys
18908 (when (or org-use-extra-keys (not window-system))
18909 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18910 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18911 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18912 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18913 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18914 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18915 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18916 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18917 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18918 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18919 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18920 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18921 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18922 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18923 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18924 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18925 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18926 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18927 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18928 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18930 ;;;; Narrow map
18931 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18932 (org-defkey narrow-map "b" #'org-narrow-to-block)
18933 (org-defkey narrow-map "e" #'org-narrow-to-element)
18935 ;;;; Remap usual Emacs bindings
18936 (org-remap org-mode-map
18937 'self-insert-command 'org-self-insert-command
18938 'delete-char 'org-delete-char
18939 'delete-backward-char 'org-delete-backward-char
18940 'open-line 'org-open-line
18941 'comment-dwim 'org-comment-dwim
18942 'forward-paragraph 'org-forward-paragraph
18943 'backward-paragraph 'org-backward-paragraph
18944 'delete-indentation 'org-delete-indentation)
18946 ;;;; All the other keys
18947 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18948 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18949 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18950 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18951 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18952 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18953 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18954 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18955 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18956 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18957 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18958 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18959 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18960 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18961 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18962 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18963 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18964 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18965 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
18966 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
18967 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
18968 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
18969 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
18970 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
18971 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
18972 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
18973 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
18974 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
18975 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
18976 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
18977 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
18978 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
18979 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
18980 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
18981 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
18982 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
18983 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
18984 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
18985 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
18986 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
18987 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
18988 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
18989 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
18990 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
18991 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
18992 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
18993 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
18994 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
18995 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
18996 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
18997 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
18998 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
18999 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19000 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19001 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19002 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19003 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19004 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19005 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19006 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19007 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19008 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19009 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19010 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19011 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19012 (org-defkey org-mode-map (kbd "RET") #'org-return)
19013 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19014 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19015 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19016 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19017 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19018 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19019 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19020 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19021 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19022 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19023 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19024 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19025 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19026 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19027 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19028 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19029 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19030 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19031 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19032 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19033 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19034 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19035 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19037 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19038 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19039 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19041 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19042 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19043 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19044 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19045 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19046 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19047 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19048 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19049 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19050 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19051 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19052 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19053 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19054 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19055 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19056 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19057 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19058 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19059 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19060 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19061 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19062 (org-defkey org-mode-map (kbd "C-c C-x w") #'org-insert-structure-template)
19064 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19065 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19066 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19067 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19068 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19069 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19071 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19073 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19075 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19076 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19078 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19081 ;;; Speed commands
19083 (defconst org-speed-commands-default
19085 ("Outline Navigation")
19086 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19087 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19088 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19089 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19090 ("F" . org-next-block)
19091 ("B" . org-previous-block)
19092 ("u" . (org-speed-move-safe 'outline-up-heading))
19093 ("j" . org-goto)
19094 ("g" . (org-refile t))
19095 ("Outline Visibility")
19096 ("c" . org-cycle)
19097 ("C" . org-shifttab)
19098 (" " . org-display-outline-path)
19099 ("s" . org-narrow-to-subtree)
19100 ("=" . org-columns)
19101 ("Outline Structure Editing")
19102 ("U" . org-metaup)
19103 ("D" . org-metadown)
19104 ("r" . org-metaright)
19105 ("l" . org-metaleft)
19106 ("R" . org-shiftmetaright)
19107 ("L" . org-shiftmetaleft)
19108 ("i" . (progn (forward-char 1) (call-interactively
19109 'org-insert-heading-respect-content)))
19110 ("^" . org-sort)
19111 ("w" . org-refile)
19112 ("a" . org-archive-subtree-default-with-confirmation)
19113 ("@" . org-mark-subtree)
19114 ("#" . org-toggle-comment)
19115 ("Clock Commands")
19116 ("I" . org-clock-in)
19117 ("O" . org-clock-out)
19118 ("Meta Data Editing")
19119 ("t" . org-todo)
19120 ("," . (org-priority))
19121 ("0" . (org-priority ?\ ))
19122 ("1" . (org-priority ?A))
19123 ("2" . (org-priority ?B))
19124 ("3" . (org-priority ?C))
19125 (":" . org-set-tags-command)
19126 ("e" . org-set-effort)
19127 ("E" . org-inc-effort)
19128 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19129 (org-entry-put (point) "APPT_WARNTIME" m)))
19130 ("Agenda Views etc")
19131 ("v" . org-agenda)
19132 ("/" . org-sparse-tree)
19133 ("Misc")
19134 ("o" . org-open-at-point)
19135 ("?" . org-speed-command-help)
19136 ("<" . (org-agenda-set-restriction-lock 'subtree))
19137 (">" . (org-agenda-remove-restriction-lock))
19139 "The default speed commands.")
19141 (defun org-print-speed-command (e)
19142 (if (> (length (car e)) 1)
19143 (progn
19144 (princ "\n")
19145 (princ (car e))
19146 (princ "\n")
19147 (princ (make-string (length (car e)) ?-))
19148 (princ "\n"))
19149 (princ (car e))
19150 (princ " ")
19151 (if (symbolp (cdr e))
19152 (princ (symbol-name (cdr e)))
19153 (prin1 (cdr e)))
19154 (princ "\n")))
19156 (defun org-speed-command-help ()
19157 "Show the available speed commands."
19158 (interactive)
19159 (if (not org-use-speed-commands)
19160 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19161 (with-output-to-temp-buffer "*Help*"
19162 (princ "User-defined Speed commands\n===========================\n")
19163 (mapc #'org-print-speed-command org-speed-commands-user)
19164 (princ "\n")
19165 (princ "Built-in Speed commands\n=======================\n")
19166 (mapc #'org-print-speed-command org-speed-commands-default))
19167 (with-current-buffer "*Help*"
19168 (setq truncate-lines t))))
19170 (defun org-speed-move-safe (cmd)
19171 "Execute CMD, but make sure that the cursor always ends up in a headline.
19172 If not, return to the original position and throw an error."
19173 (interactive)
19174 (let ((pos (point)))
19175 (call-interactively cmd)
19176 (unless (and (bolp) (org-at-heading-p))
19177 (goto-char pos)
19178 (error "Boundary reached while executing %s" cmd))))
19180 (defvar org-self-insert-command-undo-counter 0)
19182 (defvar org-table-auto-blank-field) ; defined in org-table.el
19183 (defvar org-speed-command nil)
19185 (defun org-speed-command-activate (keys)
19186 "Hook for activating single-letter speed commands.
19187 `org-speed-commands-default' specifies a minimal command set.
19188 Use `org-speed-commands-user' for further customization."
19189 (when (or (and (bolp) (looking-at org-outline-regexp))
19190 (and (functionp org-use-speed-commands)
19191 (funcall org-use-speed-commands)))
19192 (cdr (assoc keys (append org-speed-commands-user
19193 org-speed-commands-default)))))
19195 (defun org-babel-speed-command-activate (keys)
19196 "Hook for activating single-letter code block commands."
19197 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19198 (cdr (assoc keys org-babel-key-bindings))))
19200 (defcustom org-speed-command-hook
19201 '(org-speed-command-activate org-babel-speed-command-activate)
19202 "Hook for activating speed commands at strategic locations.
19203 Hook functions are called in sequence until a valid handler is
19204 found.
19206 Each hook takes a single argument, a user-pressed command key
19207 which is also a `self-insert-command' from the global map.
19209 Within the hook, examine the cursor position and the command key
19210 and return nil or a valid handler as appropriate. Handler could
19211 be one of an interactive command, a function, or a form.
19213 Set `org-use-speed-commands' to non-nil value to enable this
19214 hook. The default setting is `org-speed-command-activate'."
19215 :group 'org-structure
19216 :version "24.1"
19217 :type 'hook)
19219 (defun org-self-insert-command (N)
19220 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19221 If the cursor is in a table looking at whitespace, the whitespace is
19222 overwritten, and the table is not marked as requiring realignment."
19223 (interactive "p")
19224 (org-check-before-invisible-edit 'insert)
19225 (cond
19226 ((and org-use-speed-commands
19227 (let ((kv (this-command-keys-vector)))
19228 (setq org-speed-command
19229 (run-hook-with-args-until-success
19230 'org-speed-command-hook
19231 (make-string 1 (aref kv (1- (length kv))))))))
19232 (cond
19233 ((commandp org-speed-command)
19234 (setq this-command org-speed-command)
19235 (call-interactively org-speed-command))
19236 ((functionp org-speed-command)
19237 (funcall org-speed-command))
19238 ((and org-speed-command (listp org-speed-command))
19239 (eval org-speed-command))
19240 (t (let (org-use-speed-commands)
19241 (call-interactively 'org-self-insert-command)))))
19242 ((and
19243 (org-at-table-p)
19244 (eq N 1)
19245 (not (org-region-active-p))
19246 (progn
19247 ;; Check if we blank the field, and if that triggers align.
19248 (and (featurep 'org-table) 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 (delete-region (match-beginning 1) (match-end 1))
19262 (self-insert-command N))
19264 (setq org-table-may-need-update t)
19265 (self-insert-command N)
19266 (org-fix-tags-on-the-fly)
19267 (when org-self-insert-cluster-for-undo
19268 (if (not (eq last-command 'org-self-insert-command))
19269 (setq org-self-insert-command-undo-counter 1)
19270 (if (>= org-self-insert-command-undo-counter 20)
19271 (setq org-self-insert-command-undo-counter 1)
19272 (and (> org-self-insert-command-undo-counter 0)
19273 buffer-undo-list (listp buffer-undo-list)
19274 (not (cadr buffer-undo-list)) ; remove nil entry
19275 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19276 (setq org-self-insert-command-undo-counter
19277 (1+ org-self-insert-command-undo-counter))))))))
19279 (defun org-check-before-invisible-edit (kind)
19280 "Check is editing if kind KIND would be dangerous with invisible text around.
19281 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19282 ;; First, try to get out of here as quickly as possible, to reduce overhead
19283 (when (and org-catch-invisible-edits
19284 (or (not (boundp 'visible-mode)) (not visible-mode))
19285 (or (get-char-property (point) 'invisible)
19286 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19287 ;; OK, we need to take a closer look. Do not consider
19288 ;; invisibility obtained through text properties (e.g., link
19289 ;; fontification), as it cannot be toggled.
19290 (let* ((invisible-at-point
19291 (pcase (get-char-property-and-overlay (point) 'invisible)
19292 (`(,_ . ,(and (pred overlayp) o)) o)))
19293 ;; Assume that point cannot land in the middle of an
19294 ;; overlay, or between two overlays.
19295 (invisible-before-point
19296 (and (not invisible-at-point)
19297 (not (bobp))
19298 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19299 (`(,_ . ,(and (pred overlayp) o)) o))))
19300 (border-and-ok-direction
19302 ;; Check if we are acting predictably before invisible
19303 ;; text.
19304 (and invisible-at-point
19305 (memq kind '(insert delete-backward)))
19306 ;; Check if we are acting predictably after invisible text
19307 ;; This works not well, and I have turned it off. It seems
19308 ;; better to always show and stop after invisible text.
19309 ;; (and (not invisible-at-point) invisible-before-point
19310 ;; (memq kind '(insert delete)))
19312 (when (or invisible-at-point invisible-before-point)
19313 (when (eq org-catch-invisible-edits 'error)
19314 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19315 (if (and org-custom-properties-overlays
19316 (y-or-n-p "Display invisible properties in this buffer? "))
19317 (org-toggle-custom-properties-visibility)
19318 ;; Make the area visible
19319 (save-excursion
19320 (when invisible-before-point
19321 (goto-char
19322 (previous-single-char-property-change (point) 'invisible)))
19323 ;; Remove whatever overlay is currently making yet-to-be
19324 ;; edited text invisible. Also remove nested invisibility
19325 ;; related overlays.
19326 (delete-overlay (or invisible-at-point invisible-before-point))
19327 (let ((origin (if invisible-at-point (point) (1- (point)))))
19328 (while (pcase (get-char-property-and-overlay origin 'invisible)
19329 (`(,_ . ,(and (pred overlayp) o))
19330 (delete-overlay o)
19331 t)))))
19332 (cond
19333 ((eq org-catch-invisible-edits 'show)
19334 ;; That's it, we do the edit after showing
19335 (message
19336 "Unfolding invisible region around point before editing")
19337 (sit-for 1))
19338 ((and (eq org-catch-invisible-edits 'smart)
19339 border-and-ok-direction)
19340 (message "Unfolding invisible region around point before editing"))
19342 ;; Don't do the edit, make the user repeat it in full visibility
19343 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19345 (defun org-fix-tags-on-the-fly ()
19346 "Align tags in headline at point.
19347 Unlike to `org-set-tags', it ignores region and sorting."
19348 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19349 (org-at-heading-p))
19350 (let ((org-ignore-region t)
19351 (org-tags-sort-function nil))
19352 (org-set-tags nil t))))
19354 (defun org-delete-backward-char (N)
19355 "Like `delete-backward-char', insert whitespace at field end in tables.
19356 When deleting backwards, in tables this function will insert whitespace in
19357 front of the next \"|\" separator, to keep the table aligned. The table will
19358 still be marked for re-alignment if the field did fill the entire column,
19359 because, in this case the deletion might narrow the column."
19360 (interactive "p")
19361 (save-match-data
19362 (org-check-before-invisible-edit 'delete-backward)
19363 (if (and (org-at-table-p)
19364 (eq N 1)
19365 (not (org-region-active-p))
19366 (string-match "|" (buffer-substring (point-at-bol) (point)))
19367 (looking-at ".*?|"))
19368 (let ((pos (point))
19369 (noalign (looking-at "[^|\n\r]* |"))
19370 (c org-table-may-need-update))
19371 (backward-delete-char N)
19372 (unless overwrite-mode
19373 (skip-chars-forward "^|")
19374 (insert " ")
19375 (goto-char (1- pos)))
19376 ;; noalign: if there were two spaces at the end, this field
19377 ;; does not determine the width of the column.
19378 (when noalign (setq org-table-may-need-update c)))
19379 (backward-delete-char N)
19380 (org-fix-tags-on-the-fly))))
19382 (defun org-delete-char (N)
19383 "Like `delete-char', but insert whitespace at field end in tables.
19384 When deleting characters, in tables this function will insert whitespace in
19385 front of the next \"|\" separator, to keep the table aligned. The table will
19386 still be marked for re-alignment if the field did fill the entire column,
19387 because, in this case the deletion might narrow the column."
19388 (interactive "p")
19389 (save-match-data
19390 (org-check-before-invisible-edit 'delete)
19391 (if (and (org-at-table-p)
19392 (not (bolp))
19393 (not (= (char-after) ?|))
19394 (eq N 1))
19395 (if (looking-at ".*?|")
19396 (let ((pos (point))
19397 (noalign (looking-at "[^|\n\r]* |"))
19398 (c org-table-may-need-update))
19399 (replace-match
19400 (concat (substring (match-string 0) 1 -1) " |") nil t)
19401 (goto-char pos)
19402 ;; noalign: if there were two spaces at the end, this field
19403 ;; does not determine the width of the column.
19404 (when noalign (setq org-table-may-need-update c)))
19405 (delete-char N))
19406 (delete-char N)
19407 (org-fix-tags-on-the-fly))))
19409 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19410 (put 'org-self-insert-command 'delete-selection
19411 (lambda ()
19412 (not (run-hook-with-args-until-success
19413 'self-insert-uses-region-functions))))
19414 (put 'orgtbl-self-insert-command 'delete-selection
19415 (lambda ()
19416 (not (run-hook-with-args-until-success
19417 'self-insert-uses-region-functions))))
19418 (put 'org-delete-char 'delete-selection 'supersede)
19419 (put 'org-delete-backward-char 'delete-selection 'supersede)
19420 (put 'org-yank 'delete-selection 'yank)
19422 ;; Make `flyspell-mode' delay after some commands
19423 (put 'org-self-insert-command 'flyspell-delayed t)
19424 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19425 (put 'org-delete-char 'flyspell-delayed t)
19426 (put 'org-delete-backward-char 'flyspell-delayed t)
19428 ;; Make pabbrev-mode expand after Org mode commands
19429 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19430 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19432 (defun org-transpose-words ()
19433 "Transpose words for Org.
19434 This uses the `org-mode-transpose-word-syntax-table' syntax
19435 table, which interprets characters in `org-emphasis-alist' as
19436 word constituents."
19437 (interactive)
19438 (with-syntax-table org-mode-transpose-word-syntax-table
19439 (call-interactively 'transpose-words)))
19440 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19442 (defvar org-ctrl-c-ctrl-c-hook nil
19443 "Hook for functions attaching themselves to `C-c C-c'.
19445 This can be used to add additional functionality to the C-c C-c
19446 key which executes context-dependent commands. This hook is run
19447 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19448 run after the last test.
19450 Each function will be called with no arguments. The function
19451 must check if the context is appropriate for it to act. If yes,
19452 it should do its thing and then return a non-nil value. If the
19453 context is wrong, just do nothing and return nil.")
19455 (defvar org-ctrl-c-ctrl-c-final-hook nil
19456 "Hook for functions attaching themselves to `C-c C-c'.
19458 This can be used to add additional functionality to the C-c C-c
19459 key which executes context-dependent commands. This hook is run
19460 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19461 before the first test.
19463 Each function will be called with no arguments. The function
19464 must check if the context is appropriate for it to act. If yes,
19465 it should do its thing and then return a non-nil value. If the
19466 context is wrong, just do nothing and return nil.")
19468 (defvar org-tab-first-hook nil
19469 "Hook for functions to attach themselves to TAB.
19470 See `org-ctrl-c-ctrl-c-hook' for more information.
19471 This hook runs as the first action when TAB is pressed, even before
19472 `org-cycle' messes around with the `outline-regexp' to cater for
19473 inline tasks and plain list item folding.
19474 If any function in this hook returns t, any other actions that
19475 would have been caused by TAB (such as table field motion or visibility
19476 cycling) will not occur.")
19478 (defvar org-tab-after-check-for-table-hook nil
19479 "Hook for functions to attach themselves to TAB.
19480 See `org-ctrl-c-ctrl-c-hook' for more information.
19481 This hook runs after it has been established that the cursor is not in a
19482 table, but before checking if the cursor is in a headline or if global cycling
19483 should be done.
19484 If any function in this hook returns t, not other actions like visibility
19485 cycling will be done.")
19487 (defvar org-tab-after-check-for-cycling-hook nil
19488 "Hook for functions to attach themselves to TAB.
19489 See `org-ctrl-c-ctrl-c-hook' for more information.
19490 This hook runs after it has been established that not table field motion and
19491 not visibility should be done because of current context. This is probably
19492 the place where a package like yasnippets can hook in.")
19494 (defvar org-tab-before-tab-emulation-hook nil
19495 "Hook for functions to attach themselves to TAB.
19496 See `org-ctrl-c-ctrl-c-hook' for more information.
19497 This hook runs after every other options for TAB have been exhausted, but
19498 before indentation and \t insertion takes place.")
19500 (defvar org-metaleft-hook nil
19501 "Hook for functions attaching themselves to `M-left'.
19502 See `org-ctrl-c-ctrl-c-hook' for more information.")
19503 (defvar org-metaright-hook nil
19504 "Hook for functions attaching themselves to `M-right'.
19505 See `org-ctrl-c-ctrl-c-hook' for more information.")
19506 (defvar org-metaup-hook nil
19507 "Hook for functions attaching themselves to `M-up'.
19508 See `org-ctrl-c-ctrl-c-hook' for more information.")
19509 (defvar org-metadown-hook nil
19510 "Hook for functions attaching themselves to `M-down'.
19511 See `org-ctrl-c-ctrl-c-hook' for more information.")
19512 (defvar org-shiftmetaleft-hook nil
19513 "Hook for functions attaching themselves to `M-S-left'.
19514 See `org-ctrl-c-ctrl-c-hook' for more information.")
19515 (defvar org-shiftmetaright-hook nil
19516 "Hook for functions attaching themselves to `M-S-right'.
19517 See `org-ctrl-c-ctrl-c-hook' for more information.")
19518 (defvar org-shiftmetaup-hook nil
19519 "Hook for functions attaching themselves to `M-S-up'.
19520 See `org-ctrl-c-ctrl-c-hook' for more information.")
19521 (defvar org-shiftmetadown-hook nil
19522 "Hook for functions attaching themselves to `M-S-down'.
19523 See `org-ctrl-c-ctrl-c-hook' for more information.")
19524 (defvar org-metareturn-hook nil
19525 "Hook for functions attaching themselves to `M-RET'.
19526 See `org-ctrl-c-ctrl-c-hook' for more information.")
19527 (defvar org-shiftup-hook nil
19528 "Hook for functions attaching themselves to `S-up'.
19529 See `org-ctrl-c-ctrl-c-hook' for more information.")
19530 (defvar org-shiftup-final-hook nil
19531 "Hook for functions attaching themselves to `S-up'.
19532 This one runs after all other options except shift-select have been excluded.
19533 See `org-ctrl-c-ctrl-c-hook' for more information.")
19534 (defvar org-shiftdown-hook nil
19535 "Hook for functions attaching themselves to `S-down'.
19536 See `org-ctrl-c-ctrl-c-hook' for more information.")
19537 (defvar org-shiftdown-final-hook nil
19538 "Hook for functions attaching themselves to `S-down'.
19539 This one runs after all other options except shift-select have been excluded.
19540 See `org-ctrl-c-ctrl-c-hook' for more information.")
19541 (defvar org-shiftleft-hook nil
19542 "Hook for functions attaching themselves to `S-left'.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.")
19544 (defvar org-shiftleft-final-hook nil
19545 "Hook for functions attaching themselves to `S-left'.
19546 This one runs after all other options except shift-select have been excluded.
19547 See `org-ctrl-c-ctrl-c-hook' for more information.")
19548 (defvar org-shiftright-hook nil
19549 "Hook for functions attaching themselves to `S-right'.
19550 See `org-ctrl-c-ctrl-c-hook' for more information.")
19551 (defvar org-shiftright-final-hook nil
19552 "Hook for functions attaching themselves to `S-right'.
19553 This one runs after all other options except shift-select have been excluded.
19554 See `org-ctrl-c-ctrl-c-hook' for more information.")
19556 (defun org-modifier-cursor-error ()
19557 "Throw an error, a modified cursor command was applied in wrong context."
19558 (user-error "This command is active in special context like tables, headlines or items"))
19560 (defun org-shiftselect-error ()
19561 "Throw an error because Shift-Cursor command was applied in wrong context."
19562 (if (and (boundp 'shift-select-mode) shift-select-mode)
19563 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19564 (user-error "This command works only in special context like headlines or timestamps")))
19566 (defun org-call-for-shift-select (cmd)
19567 (let ((this-command-keys-shift-translated t))
19568 (call-interactively cmd)))
19570 (defun org-shifttab (&optional arg)
19571 "Global visibility cycling or move to previous table field.
19572 Call `org-table-previous-field' within a table.
19573 When ARG is nil, cycle globally through visibility states.
19574 When ARG is a numeric prefix, show contents of this level."
19575 (interactive "P")
19576 (cond
19577 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19578 ((integerp arg)
19579 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19580 (message "Content view to level: %d" arg)
19581 (org-content (prefix-numeric-value arg2))
19582 (org-cycle-show-empty-lines t)
19583 (setq org-cycle-global-status 'overview)))
19584 (t (call-interactively 'org-global-cycle))))
19586 (defun org-shiftmetaleft ()
19587 "Promote subtree or delete table column.
19588 Calls `org-promote-subtree', `org-outdent-item-tree', or
19589 `org-table-delete-column', depending on context. See the
19590 individual commands for more information."
19591 (interactive)
19592 (cond
19593 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19594 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19595 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19596 ((if (not (org-region-active-p)) (org-at-item-p)
19597 (save-excursion (goto-char (region-beginning))
19598 (org-at-item-p)))
19599 (call-interactively 'org-outdent-item-tree))
19600 (t (org-modifier-cursor-error))))
19602 (defun org-shiftmetaright ()
19603 "Demote subtree or insert table column.
19604 Calls `org-demote-subtree', `org-indent-item-tree', or
19605 `org-table-insert-column', depending on context. See the
19606 individual commands for more information."
19607 (interactive)
19608 (cond
19609 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19610 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19611 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19612 ((if (not (org-region-active-p)) (org-at-item-p)
19613 (save-excursion (goto-char (region-beginning))
19614 (org-at-item-p)))
19615 (call-interactively 'org-indent-item-tree))
19616 (t (org-modifier-cursor-error))))
19618 (defun org-shiftmetaup (&optional _arg)
19619 "Drag the line at point up.
19620 In a table, kill the current row.
19621 On a clock timestamp, update the value of the timestamp like `S-<up>'
19622 but also adjust the previous clocked item in the clock history.
19623 Everywhere else, drag the line at point up."
19624 (interactive "P")
19625 (cond
19626 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19627 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19628 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19629 (call-interactively 'org-timestamp-up)))
19630 (t (call-interactively 'org-drag-line-backward))))
19632 (defun org-shiftmetadown (&optional _arg)
19633 "Drag the line at point down.
19634 In a table, insert an empty row at the current line.
19635 On a clock timestamp, update the value of the timestamp like `S-<down>'
19636 but also adjust the previous clocked item in the clock history.
19637 Everywhere else, drag the line at point down."
19638 (interactive "P")
19639 (cond
19640 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19641 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19642 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19643 (call-interactively 'org-timestamp-down)))
19644 (t (call-interactively 'org-drag-line-forward))))
19646 (defsubst org-hidden-tree-error ()
19647 (user-error
19648 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19650 (defun org-metaleft (&optional _arg)
19651 "Promote heading, list item at point or move table column left.
19653 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19654 depending on context. With no specific context, calls the Emacs
19655 default `backward-word'. See the individual commands for more
19656 information.
19658 This function runs the hook `org-metaleft-hook' as a first step,
19659 and returns at first non-nil value."
19660 (interactive "P")
19661 (cond
19662 ((run-hook-with-args-until-success 'org-metaleft-hook))
19663 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19664 ((org-with-limited-levels
19665 (or (org-at-heading-p)
19666 (and (org-region-active-p)
19667 (save-excursion
19668 (goto-char (region-beginning))
19669 (org-at-heading-p)))))
19670 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19671 (call-interactively 'org-do-promote))
19672 ;; At an inline task.
19673 ((org-at-heading-p)
19674 (call-interactively 'org-inlinetask-promote))
19675 ((or (org-at-item-p)
19676 (and (org-region-active-p)
19677 (save-excursion
19678 (goto-char (region-beginning))
19679 (org-at-item-p))))
19680 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19681 (call-interactively 'org-outdent-item))
19682 (t (call-interactively 'backward-word))))
19684 (defun org-metaright (&optional _arg)
19685 "Demote heading, list item at point or move table column right.
19687 In front of a drawer or a block keyword, indent it correctly.
19689 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19690 `org-indent-drawer' or `org-indent-block' depending on context.
19691 With no specific context, calls the Emacs default `forward-word'.
19692 See the individual commands for more information.
19694 This function runs the hook `org-metaright-hook' as a first step,
19695 and returns at first non-nil value."
19696 (interactive "P")
19697 (cond
19698 ((run-hook-with-args-until-success 'org-metaright-hook))
19699 ((org-at-table-p) (call-interactively 'org-table-move-column))
19700 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19701 ((org-at-block-p) (call-interactively 'org-indent-block))
19702 ((org-with-limited-levels
19703 (or (org-at-heading-p)
19704 (and (org-region-active-p)
19705 (save-excursion
19706 (goto-char (region-beginning))
19707 (org-at-heading-p)))))
19708 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19709 (call-interactively 'org-do-demote))
19710 ;; At an inline task.
19711 ((org-at-heading-p)
19712 (call-interactively 'org-inlinetask-demote))
19713 ((or (org-at-item-p)
19714 (and (org-region-active-p)
19715 (save-excursion
19716 (goto-char (region-beginning))
19717 (org-at-item-p))))
19718 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19719 (call-interactively 'org-indent-item))
19720 (t (call-interactively 'forward-word))))
19722 (defun org-check-for-hidden (what)
19723 "Check if there are hidden headlines/items in the current visual line.
19724 WHAT can be either `headlines' or `items'. If the current line is
19725 an outline or item heading and it has a folded subtree below it,
19726 this function returns t, nil otherwise."
19727 (let ((re (cond
19728 ((eq what 'headlines) org-outline-regexp-bol)
19729 ((eq what 'items) (org-item-beginning-re))
19730 (t (error "This should not happen"))))
19731 beg end)
19732 (save-excursion
19733 (catch 'exit
19734 (unless (org-region-active-p)
19735 (setq beg (point-at-bol))
19736 (beginning-of-line 2)
19737 (while (and (not (eobp)) ;; this is like `next-line'
19738 (get-char-property (1- (point)) 'invisible))
19739 (beginning-of-line 2))
19740 (setq end (point))
19741 (goto-char beg)
19742 (goto-char (point-at-eol))
19743 (setq end (max end (point)))
19744 (while (re-search-forward re end t)
19745 (when (get-char-property (match-beginning 0) 'invisible)
19746 (throw 'exit t))))
19747 nil))))
19749 (defun org-metaup (&optional _arg)
19750 "Move subtree up or move table row up.
19751 Calls `org-move-subtree-up' or `org-table-move-row' or
19752 `org-move-item-up', depending on context. See the individual commands
19753 for more information."
19754 (interactive "P")
19755 (cond
19756 ((run-hook-with-args-until-success 'org-metaup-hook))
19757 ((org-region-active-p)
19758 (let* ((a (min (region-beginning) (region-end)))
19759 (b (1- (max (region-beginning) (region-end))))
19760 (c (save-excursion (goto-char a)
19761 (move-beginning-of-line 0)))
19762 (d (save-excursion (goto-char a)
19763 (move-end-of-line 0) (point))))
19764 (transpose-regions a b c d)
19765 (goto-char c)))
19766 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19767 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19768 ((org-at-item-p) (call-interactively 'org-move-item-up))
19769 (t (org-drag-element-backward))))
19771 (defun org-metadown (&optional _arg)
19772 "Move subtree down or move table row down.
19773 Calls `org-move-subtree-down' or `org-table-move-row' or
19774 `org-move-item-down', depending on context. See the individual
19775 commands for more information."
19776 (interactive "P")
19777 (cond
19778 ((run-hook-with-args-until-success 'org-metadown-hook))
19779 ((org-region-active-p)
19780 (let* ((a (min (region-beginning) (region-end)))
19781 (b (max (region-beginning) (region-end)))
19782 (c (save-excursion (goto-char b)
19783 (move-beginning-of-line 1)))
19784 (d (save-excursion (goto-char b)
19785 (move-end-of-line 1) (1+ (point)))))
19786 (transpose-regions a b c d)
19787 (goto-char d)))
19788 ((org-at-table-p) (call-interactively 'org-table-move-row))
19789 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19790 ((org-at-item-p) (call-interactively 'org-move-item-down))
19791 (t (org-drag-element-forward))))
19793 (defun org-shiftup (&optional arg)
19794 "Increase item in timestamp or increase priority of current headline.
19795 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19796 depending on context. See the individual commands for more information."
19797 (interactive "P")
19798 (cond
19799 ((run-hook-with-args-until-success 'org-shiftup-hook))
19800 ((and org-support-shift-select (org-region-active-p))
19801 (org-call-for-shift-select 'previous-line))
19802 ((org-at-timestamp-p 'lax)
19803 (call-interactively (if org-edit-timestamp-down-means-later
19804 'org-timestamp-down 'org-timestamp-up)))
19805 ((and (not (eq org-support-shift-select 'always))
19806 org-enable-priority-commands
19807 (org-at-heading-p))
19808 (call-interactively 'org-priority-up))
19809 ((and (not org-support-shift-select) (org-at-item-p))
19810 (call-interactively 'org-previous-item))
19811 ((org-clocktable-try-shift 'up arg))
19812 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19813 (org-support-shift-select
19814 (org-call-for-shift-select 'previous-line))
19815 (t (org-shiftselect-error))))
19817 (defun org-shiftdown (&optional arg)
19818 "Decrease item in timestamp or decrease priority of current headline.
19819 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19820 depending on context. See the individual commands for more information."
19821 (interactive "P")
19822 (cond
19823 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19824 ((and org-support-shift-select (org-region-active-p))
19825 (org-call-for-shift-select 'next-line))
19826 ((org-at-timestamp-p 'lax)
19827 (call-interactively (if org-edit-timestamp-down-means-later
19828 'org-timestamp-up 'org-timestamp-down)))
19829 ((and (not (eq org-support-shift-select 'always))
19830 org-enable-priority-commands
19831 (org-at-heading-p))
19832 (call-interactively 'org-priority-down))
19833 ((and (not org-support-shift-select) (org-at-item-p))
19834 (call-interactively 'org-next-item))
19835 ((org-clocktable-try-shift 'down arg))
19836 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19837 (org-support-shift-select
19838 (org-call-for-shift-select 'next-line))
19839 (t (org-shiftselect-error))))
19841 (defun org-shiftright (&optional arg)
19842 "Cycle the thing at point or in the current line, depending on context.
19843 Depending on context, this does one of the following:
19845 - switch a timestamp at point one day into the future
19846 - on a headline, switch to the next TODO keyword.
19847 - on an item, switch entire list to the next bullet type
19848 - on a property line, switch to the next allowed value
19849 - on a clocktable definition line, move time block into the future"
19850 (interactive "P")
19851 (cond
19852 ((run-hook-with-args-until-success 'org-shiftright-hook))
19853 ((and org-support-shift-select (org-region-active-p))
19854 (org-call-for-shift-select 'forward-char))
19855 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19856 ((and (not (eq org-support-shift-select 'always))
19857 (org-at-heading-p))
19858 (let ((org-inhibit-logging
19859 (not org-treat-S-cursor-todo-selection-as-state-change))
19860 (org-inhibit-blocking
19861 (not org-treat-S-cursor-todo-selection-as-state-change)))
19862 (org-call-with-arg 'org-todo 'right)))
19863 ((or (and org-support-shift-select
19864 (not (eq org-support-shift-select 'always))
19865 (org-at-item-bullet-p))
19866 (and (not org-support-shift-select) (org-at-item-p)))
19867 (org-call-with-arg 'org-cycle-list-bullet nil))
19868 ((and (not (eq org-support-shift-select 'always))
19869 (org-at-property-p))
19870 (call-interactively 'org-property-next-allowed-value))
19871 ((org-clocktable-try-shift 'right arg))
19872 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19873 (org-support-shift-select
19874 (org-call-for-shift-select 'forward-char))
19875 (t (org-shiftselect-error))))
19877 (defun org-shiftleft (&optional arg)
19878 "Cycle the thing at point or in the current line, depending on context.
19879 Depending on context, this does one of the following:
19881 - switch a timestamp at point one day into the past
19882 - on a headline, switch to the previous TODO keyword.
19883 - on an item, switch entire list to the previous bullet type
19884 - on a property line, switch to the previous allowed value
19885 - on a clocktable definition line, move time block into the past"
19886 (interactive "P")
19887 (cond
19888 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19889 ((and org-support-shift-select (org-region-active-p))
19890 (org-call-for-shift-select 'backward-char))
19891 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19892 ((and (not (eq org-support-shift-select 'always))
19893 (org-at-heading-p))
19894 (let ((org-inhibit-logging
19895 (not org-treat-S-cursor-todo-selection-as-state-change))
19896 (org-inhibit-blocking
19897 (not org-treat-S-cursor-todo-selection-as-state-change)))
19898 (org-call-with-arg 'org-todo 'left)))
19899 ((or (and org-support-shift-select
19900 (not (eq org-support-shift-select 'always))
19901 (org-at-item-bullet-p))
19902 (and (not org-support-shift-select) (org-at-item-p)))
19903 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19904 ((and (not (eq org-support-shift-select 'always))
19905 (org-at-property-p))
19906 (call-interactively 'org-property-previous-allowed-value))
19907 ((org-clocktable-try-shift 'left arg))
19908 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19909 (org-support-shift-select
19910 (org-call-for-shift-select 'backward-char))
19911 (t (org-shiftselect-error))))
19913 (defun org-shiftcontrolright ()
19914 "Switch to next TODO set."
19915 (interactive)
19916 (cond
19917 ((and org-support-shift-select (org-region-active-p))
19918 (org-call-for-shift-select 'forward-word))
19919 ((and (not (eq org-support-shift-select 'always))
19920 (org-at-heading-p))
19921 (org-call-with-arg 'org-todo 'nextset))
19922 (org-support-shift-select
19923 (org-call-for-shift-select 'forward-word))
19924 (t (org-shiftselect-error))))
19926 (defun org-shiftcontrolleft ()
19927 "Switch to previous TODO set."
19928 (interactive)
19929 (cond
19930 ((and org-support-shift-select (org-region-active-p))
19931 (org-call-for-shift-select 'backward-word))
19932 ((and (not (eq org-support-shift-select 'always))
19933 (org-at-heading-p))
19934 (org-call-with-arg 'org-todo 'previousset))
19935 (org-support-shift-select
19936 (org-call-for-shift-select 'backward-word))
19937 (t (org-shiftselect-error))))
19939 (defun org-shiftcontrolup (&optional n)
19940 "Change timestamps synchronously up in CLOCK log lines.
19941 Optional argument N tells to change by that many units."
19942 (interactive "P")
19943 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19944 (let (org-support-shift-select)
19945 (org-clock-timestamps-up n))
19946 (user-error "Not at a clock log")))
19948 (defun org-shiftcontroldown (&optional n)
19949 "Change timestamps synchronously down in CLOCK log lines.
19950 Optional argument N tells to change by that many units."
19951 (interactive "P")
19952 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19953 (let (org-support-shift-select)
19954 (org-clock-timestamps-down n))
19955 (user-error "Not at a clock log")))
19957 (defun org-increase-number-at-point (&optional inc)
19958 "Increment the number at point.
19959 With an optional prefix numeric argument INC, increment using
19960 this numeric value."
19961 (interactive "p")
19962 (if (not (number-at-point))
19963 (user-error "Not on a number")
19964 (unless inc (setq inc 1))
19965 (let ((pos (point))
19966 (beg (skip-chars-backward "-+^/*0-9eE."))
19967 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
19968 (setq nap (buffer-substring-no-properties
19969 (+ pos beg) (+ pos beg end)))
19970 (delete-region (+ pos beg) (+ pos beg end))
19971 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
19972 (when (org-at-table-p)
19973 (org-table-align)
19974 (org-table-end-of-field 1))))
19976 (defun org-decrease-number-at-point (&optional inc)
19977 "Decrement the number at point.
19978 With an optional prefix numeric argument INC, decrement using
19979 this numeric value."
19980 (interactive "p")
19981 (org-increase-number-at-point (- (or inc 1))))
19983 (defun org-ctrl-c-ret ()
19984 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19985 (interactive)
19986 (cond
19987 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19988 (t (call-interactively 'org-insert-heading))))
19990 (defun org-find-visible ()
19991 (let ((s (point)))
19992 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19993 (get-char-property s 'invisible)))
19995 (defun org-find-invisible ()
19996 (let ((s (point)))
19997 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19998 (not (get-char-property s 'invisible))))
20001 (defun org-copy-visible (beg end)
20002 "Copy the visible parts of the region."
20003 (interactive "r")
20004 (let ((result ""))
20005 (while (/= beg end)
20006 (when (get-char-property beg 'invisible)
20007 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20008 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20009 (setq result (concat result (buffer-substring beg next)))
20010 (setq beg next)))
20011 (kill-new result)))
20013 (defun org-copy-special ()
20014 "Copy region in table or copy current subtree.
20015 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20016 context. See the individual commands for more information."
20017 (interactive)
20018 (call-interactively
20019 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20021 (defun org-cut-special ()
20022 "Cut region in table or cut current subtree.
20023 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20024 context. See the individual commands for more information."
20025 (interactive)
20026 (call-interactively
20027 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20029 (defun org-paste-special (arg)
20030 "Paste rectangular region into table, or past subtree relative to level.
20031 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20032 See the individual commands for more information."
20033 (interactive "P")
20034 (if (org-at-table-p)
20035 (org-table-paste-rectangle)
20036 (org-paste-subtree arg)))
20038 (defun org-edit-special (&optional arg)
20039 "Call a special editor for the element at point.
20040 When at a table, call the formula editor with `org-table-edit-formulas'.
20041 When in a source code block, call `org-edit-src-code'.
20042 When in a fixed-width region, call `org-edit-fixed-width-region'.
20043 When in an export block, call `org-edit-export-block'.
20044 When in a LaTeX environment, call `org-edit-latex-environment'.
20045 When at an #+INCLUDE keyword, visit the included file.
20046 When at a footnote reference, call `org-edit-footnote-reference'
20047 On a link, call `ffap' to visit the link at point.
20048 Otherwise, return a user error."
20049 (interactive "P")
20050 (let ((element (org-element-at-point)))
20051 (barf-if-buffer-read-only)
20052 (pcase (org-element-type element)
20053 (`src-block
20054 (if (not arg) (org-edit-src-code)
20055 (let* ((info (org-babel-get-src-block-info))
20056 (lang (nth 0 info))
20057 (params (nth 2 info))
20058 (session (cdr (assq :session params))))
20059 (if (not session) (org-edit-src-code)
20060 ;; At a src-block with a session and function called with
20061 ;; an ARG: switch to the buffer related to the inferior
20062 ;; process.
20063 (switch-to-buffer
20064 (funcall (intern (concat "org-babel-prep-session:" lang))
20065 session params))))))
20066 (`keyword
20067 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20068 (org-open-link-from-string
20069 (format "[[%s]]"
20070 (expand-file-name
20071 (let ((value (org-element-property :value element)))
20072 (cond ((org-file-url-p value)
20073 (user-error "The file is specified as a URL, cannot be edited"))
20074 ((not (org-string-nw-p value))
20075 (user-error "No file to edit"))
20076 ((string-match "\\`\"\\(.*?\\)\"" value)
20077 (match-string 1 value))
20078 ((string-match "\\`[^ \t\"]\\S-*" value)
20079 (match-string 0 value))
20080 (t (user-error "No valid file specified")))))))
20081 (user-error "No special environment to edit here")))
20082 (`table
20083 (if (eq (org-element-property :type element) 'table.el)
20084 (org-edit-table.el)
20085 (call-interactively 'org-table-edit-formulas)))
20086 ;; Only Org tables contain `table-row' type elements.
20087 (`table-row (call-interactively 'org-table-edit-formulas))
20088 (`example-block (org-edit-src-code))
20089 (`export-block (org-edit-export-block))
20090 (`fixed-width (org-edit-fixed-width-region))
20091 (`latex-environment (org-edit-latex-environment))
20093 ;; No notable element at point. Though, we may be at a link or
20094 ;; a footnote reference, which are objects. Thus, scan deeper.
20095 (let ((context (org-element-context element)))
20096 (pcase (org-element-type context)
20097 (`footnote-reference (org-edit-footnote-reference))
20098 (`inline-src-block (org-edit-inline-src-code))
20099 (`link (call-interactively #'ffap))
20100 (_ (user-error "No special environment to edit here"))))))))
20102 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20103 (defun org-ctrl-c-ctrl-c (&optional arg)
20104 "Set tags in headline, or update according to changed information at point.
20106 This command does many different things, depending on context:
20108 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20109 this is what we do.
20111 - If the cursor is on a statistics cookie, update it.
20113 - If the cursor is in a headline, prompt for tags and insert them
20114 into the current line, aligned to `org-tags-column'. When called
20115 with prefix arg, realign all tags in the current buffer.
20117 - If the cursor is in one of the special #+KEYWORD lines, this
20118 triggers scanning the buffer for these lines and updating the
20119 information.
20121 - If the cursor is inside a table, realign the table. This command
20122 works even if the automatic table editor has been turned off.
20124 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20125 the entire table.
20127 - If the cursor is at a footnote reference or definition, jump to
20128 the corresponding definition or references, respectively.
20130 - If the cursor is a the beginning of a dynamic block, update it.
20132 - If the current buffer is a capture buffer, close note and file it.
20134 - If the cursor is on a <<<target>>>, update radio targets and
20135 corresponding links in this buffer.
20137 - If the cursor is on a numbered item in a plain list, renumber the
20138 ordered list.
20140 - If the cursor is on a checkbox, toggle it.
20142 - If the cursor is on a code block, evaluate it. The variable
20143 `org-confirm-babel-evaluate' can be used to control prompting
20144 before code block evaluation, by default every code block
20145 evaluation requires confirmation. Code block evaluation can be
20146 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20147 (interactive "P")
20148 (cond
20149 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20150 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20151 (org-remove-occur-highlights)
20152 (message "Temporary highlights/overlays removed from current buffer"))
20153 ((and (local-variable-p 'org-finish-function)
20154 (fboundp org-finish-function))
20155 (funcall org-finish-function))
20156 ((org-babel-hash-at-point))
20157 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20159 (let* ((context
20160 (org-element-lineage
20161 (org-element-context)
20162 ;; Limit to supported contexts.
20163 '(babel-call clock dynamic-block footnote-definition
20164 footnote-reference inline-babel-call inline-src-block
20165 inlinetask item keyword node-property paragraph
20166 plain-list planning property-drawer radio-target
20167 src-block statistics-cookie table table-cell table-row
20168 timestamp)
20170 (type (org-element-type context)))
20171 ;; For convenience: at the first line of a paragraph on the same
20172 ;; line as an item, apply function on that item instead.
20173 (when (eq type 'paragraph)
20174 (let ((parent (org-element-property :parent context)))
20175 (when (and (eq (org-element-type parent) 'item)
20176 (= (line-beginning-position)
20177 (org-element-property :begin parent)))
20178 (setq context parent)
20179 (setq type 'item))))
20180 ;; Act according to type of element or object at point.
20182 ;; Do nothing on a blank line, except if it is contained in
20183 ;; a src block. Hence, we first check if point is in such
20184 ;; a block and then if it is at a blank line.
20185 (pcase type
20186 ((or `inline-src-block `src-block)
20187 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20188 (org-babel-eval-wipe-error-buffer)
20189 (org-babel-execute-src-block
20190 current-prefix-arg (org-babel-get-src-block-info nil context))))
20191 ((guard (org-match-line "[ \t]*$"))
20192 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20193 (user-error
20194 (substitute-command-keys
20195 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20196 ((or `babel-call `inline-babel-call)
20197 (let ((info (org-babel-lob-get-info context)))
20198 (when info (org-babel-execute-src-block nil info))))
20199 (`clock (org-clock-update-time-maybe))
20200 (`dynamic-block
20201 (save-excursion
20202 (goto-char (org-element-property :post-affiliated context))
20203 (org-update-dblock)))
20204 (`footnote-definition
20205 (goto-char (org-element-property :post-affiliated context))
20206 (call-interactively 'org-footnote-action))
20207 (`footnote-reference (call-interactively #'org-footnote-action))
20208 ((or `headline `inlinetask)
20209 (save-excursion (goto-char (org-element-property :begin context))
20210 (call-interactively #'org-set-tags)))
20211 (`item
20212 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20213 ;; unconditionally, whereas `C-u' will toggle its presence.
20214 ;; Without a universal argument, if the item has a checkbox,
20215 ;; toggle it. Otherwise repair the list.
20216 (let* ((box (org-element-property :checkbox context))
20217 (struct (org-element-property :structure context))
20218 (old-struct (copy-tree struct))
20219 (parents (org-list-parents-alist struct))
20220 (prevs (org-list-prevs-alist struct))
20221 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20222 (org-list-set-checkbox
20223 (org-element-property :begin context) struct
20224 (cond ((equal arg '(16)) "[-]")
20225 ((and (not box) (equal arg '(4))) "[ ]")
20226 ((or (not box) (equal arg '(4))) nil)
20227 ((eq box 'on) "[ ]")
20228 (t "[X]")))
20229 ;; Mimic `org-list-write-struct' but with grabbing a return
20230 ;; value from `org-list-struct-fix-box'.
20231 (org-list-struct-fix-ind struct parents 2)
20232 (org-list-struct-fix-item-end struct)
20233 (org-list-struct-fix-bul struct prevs)
20234 (org-list-struct-fix-ind struct parents)
20235 (let ((block-item
20236 (org-list-struct-fix-box struct parents prevs orderedp)))
20237 (if (and box (equal struct old-struct))
20238 (if (equal arg '(16))
20239 (message "Checkboxes already reset")
20240 (user-error "Cannot toggle this checkbox: %s"
20241 (if (eq box 'on)
20242 "all subitems checked"
20243 "unchecked subitems")))
20244 (org-list-struct-apply-struct struct old-struct)
20245 (org-update-checkbox-count-maybe))
20246 (when block-item
20247 (message "Checkboxes were removed due to empty box at line %d"
20248 (org-current-line block-item))))))
20249 (`keyword
20250 (let ((org-inhibit-startup-visibility-stuff t)
20251 (org-startup-align-all-tables nil))
20252 (when (boundp 'org-table-coordinate-overlays)
20253 (mapc #'delete-overlay org-table-coordinate-overlays)
20254 (setq org-table-coordinate-overlays nil))
20255 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20256 (message "Local setup has been refreshed"))
20257 (`plain-list
20258 ;; At a plain list, with a double C-u argument, set
20259 ;; checkboxes of each item to "[-]", whereas a single one
20260 ;; will toggle their presence according to the state of the
20261 ;; first item in the list. Without an argument, repair the
20262 ;; list.
20263 (let* ((begin (org-element-property :contents-begin context))
20264 (struct (org-element-property :structure context))
20265 (old-struct (copy-tree struct))
20266 (first-box (save-excursion
20267 (goto-char begin)
20268 (looking-at org-list-full-item-re)
20269 (match-string-no-properties 3)))
20270 (new-box (cond ((equal arg '(16)) "[-]")
20271 ((equal arg '(4)) (unless first-box "[ ]"))
20272 ((equal first-box "[X]") "[ ]")
20273 (t "[X]"))))
20274 (cond
20275 (arg
20276 (dolist (pos
20277 (org-list-get-all-items
20278 begin struct (org-list-prevs-alist struct)))
20279 (org-list-set-checkbox pos struct new-box)))
20280 ((and first-box (eq (point) begin))
20281 ;; For convenience, when point is at bol on the first
20282 ;; item of the list and no argument is provided, simply
20283 ;; toggle checkbox of that item, if any.
20284 (org-list-set-checkbox begin struct new-box)))
20285 (org-list-write-struct
20286 struct (org-list-parents-alist struct) old-struct)
20287 (org-update-checkbox-count-maybe)))
20288 ((or `property-drawer `node-property)
20289 (call-interactively #'org-property-action))
20290 (`radio-target
20291 (call-interactively #'org-update-radio-target-regexp))
20292 (`statistics-cookie
20293 (call-interactively #'org-update-statistics-cookies))
20294 ((or `table `table-cell `table-row)
20295 ;; At a table, recalculate every field and align it. Also
20296 ;; send the table if necessary. If the table has
20297 ;; a `table.el' type, just give up. At a table row or cell,
20298 ;; maybe recalculate line but always align table.
20299 (if (eq (org-element-property :type context) 'table.el)
20300 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20301 Use `\\[org-edit-special]' to edit table.el tables"))
20302 (if (or (eq type 'table)
20303 ;; Check if point is at a TBLFM line.
20304 (and (eq type 'table-row)
20305 (= (point) (org-element-property :end context))))
20306 (save-excursion
20307 (if (org-at-TBLFM-p)
20308 (progn (require 'org-table)
20309 (org-table-calc-current-TBLFM))
20310 (goto-char (org-element-property :contents-begin context))
20311 (org-call-with-arg 'org-table-recalculate (or arg t))
20312 (orgtbl-send-table 'maybe)))
20313 (org-table-maybe-eval-formula)
20314 (cond (arg (call-interactively #'org-table-recalculate))
20315 ((org-table-maybe-recalculate-line))
20316 (t (org-table-align))))))
20317 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20318 (org-timestamp-change 0 'day))
20319 ((and `nil (guard (org-at-heading-p)))
20320 ;; When point is on an unsupported object type, we can miss
20321 ;; the fact that it also is at a heading. Handle it here.
20322 (call-interactively #'org-set-tags))
20323 ((guard
20324 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20326 (user-error
20327 (substitute-command-keys
20328 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20330 (defun org-mode-restart ()
20331 (interactive)
20332 (let ((indent-status (bound-and-true-p org-indent-mode)))
20333 (funcall major-mode)
20334 (hack-local-variables)
20335 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20336 (org-indent-mode -1))
20337 (org-reset-file-cache))
20338 (message "%s restarted" major-mode))
20340 (defun org-kill-note-or-show-branches ()
20341 "Abort storing current note, or call `outline-show-branches'."
20342 (interactive)
20343 (if (not org-finish-function)
20344 (save-excursion
20345 (save-restriction
20346 (org-narrow-to-subtree)
20347 (org-flag-subtree t)
20348 (call-interactively 'outline-show-branches)
20349 (org-hide-archived-subtrees (point-min) (point-max))))
20350 (let ((org-note-abort t))
20351 (funcall org-finish-function))))
20353 (defun org-delete-indentation (&optional arg)
20354 "Join current line to previous and fix whitespace at join.
20356 If previous line is a headline add to headline title. Otherwise
20357 the function calls `delete-indentation'.
20359 With a non-nil optional argument, join it to the following one."
20360 (interactive "*P")
20361 (if (save-excursion
20362 (beginning-of-line (if arg 1 0))
20363 (let ((case-fold-search nil))
20364 (looking-at org-complex-heading-regexp)))
20365 ;; At headline.
20366 (let ((tags-column (when (match-beginning 5)
20367 (save-excursion (goto-char (match-beginning 5))
20368 (current-column))))
20369 (string (concat " " (progn (when arg (forward-line 1))
20370 (org-trim (delete-and-extract-region
20371 (line-beginning-position)
20372 (line-end-position)))))))
20373 (unless (bobp) (delete-region (point) (1- (point))))
20374 (goto-char (or (match-end 4)
20375 (match-beginning 5)
20376 (match-end 0)))
20377 (skip-chars-backward " \t")
20378 (save-excursion (insert string))
20379 ;; Adjust alignment of tags.
20380 (cond
20381 ((not tags-column)) ;no tags
20382 (org-auto-align-tags (org-set-tags nil t))
20383 (t (org--align-tags-here tags-column)))) ;preserve tags column
20384 (delete-indentation arg)))
20386 (defun org-open-line (n)
20387 "Insert a new row in tables, call `open-line' elsewhere.
20388 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20389 As a special case, when a document starts with a table, allow to
20390 call `open-line' on the very first character."
20391 (interactive "*p")
20392 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20393 (org-table-insert-row)
20394 (open-line n)))
20396 (defun org-return (&optional indent)
20397 "Goto next table row or insert a newline.
20399 Calls `org-table-next-row' or `newline', depending on context.
20401 When optional INDENT argument is non-nil, call
20402 `newline-and-indent' instead of `newline'.
20404 When `org-return-follows-link' is non-nil and point is on
20405 a timestamp or a link, call `org-open-at-point'. However, it
20406 will not happen if point is in a table or on a \"dead\"
20407 object (e.g., within a comment). In these case, you need to use
20408 `org-open-at-point' directly."
20409 (interactive)
20410 (let ((context (if org-return-follows-link (org-element-context)
20411 (org-element-at-point))))
20412 (cond
20413 ;; In a table, call `org-table-next-row'. However, before first
20414 ;; column or after last one, split the table.
20415 ((or (and (eq (org-element-type context) 'table)
20416 (>= (point) (org-element-property :contents-begin context))
20417 (< (point) (org-element-property :contents-end context)))
20418 (org-element-lineage context '(table-row table-cell) t))
20419 (if (or (looking-at-p "[ \t]*$")
20420 (save-excursion (skip-chars-backward " \t") (bolp)))
20421 (insert "\n")
20422 (org-table-justify-field-maybe)
20423 (call-interactively #'org-table-next-row)))
20424 ;; On a link or a timestamp, call `org-open-at-point' if
20425 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20426 ;; locations, e.g., in a comment, as `org-open-at-point'.
20427 ((and org-return-follows-link
20428 (or (org-in-regexp org-ts-regexp-both nil t)
20429 (org-in-regexp org-tsr-regexp-both nil t)
20430 (org-in-regexp org-any-link-re nil t)))
20431 (call-interactively #'org-open-at-point))
20432 ;; Insert newline in heading, but preserve tags.
20433 ((and (not (bolp))
20434 (save-excursion (beginning-of-line)
20435 (let ((case-fold-search nil))
20436 (looking-at org-complex-heading-regexp))))
20437 ;; At headline. Split line. However, if point is on keyword,
20438 ;; priority cookie or tags, do not break any of them: add
20439 ;; a newline after the headline instead.
20440 (let ((tags-column (and (match-beginning 5)
20441 (save-excursion (goto-char (match-beginning 5))
20442 (current-column))))
20443 (string
20444 (when (and (match-end 4) (org-point-in-group (point) 4))
20445 (delete-and-extract-region (point) (match-end 4)))))
20446 ;; Adjust tag alignment.
20447 (cond
20448 ((not (and tags-column string)))
20449 (org-auto-align-tags (org-set-tags nil t))
20450 (t (org--align-tags-here tags-column))) ;preserve tags column
20451 (end-of-line)
20452 (org-show-entry)
20453 (if indent (newline-and-indent) (newline))
20454 (when string (save-excursion (insert (org-trim string))))))
20455 ;; In a list, make sure indenting keeps trailing text within.
20456 ((and indent
20457 (not (eolp))
20458 (org-element-lineage context '(item)))
20459 (let ((trailing-data
20460 (delete-and-extract-region (point) (line-end-position))))
20461 (newline-and-indent)
20462 (save-excursion (insert trailing-data))))
20463 (t (if indent (newline-and-indent) (newline))))))
20465 (defun org-return-indent ()
20466 "Goto next table row or insert a newline and indent.
20467 Calls `org-table-next-row' or `newline-and-indent', depending on
20468 context. See the individual commands for more information."
20469 (interactive)
20470 (org-return t))
20472 (defun org-ctrl-c-tab (&optional _arg)
20473 "Toggle columns width in a table, or show children.
20474 Call `org-table-toggle-column-width' if point is in a table.
20475 Otherwise, call `org-show-children'."
20476 (interactive "p")
20477 (call-interactively
20478 (if (org-at-table-p) #'org-table-toggle-column-width
20479 #'org-show-children)))
20481 (defun org-ctrl-c-star ()
20482 "Compute table, or change heading status of lines.
20483 Calls `org-table-recalculate' or `org-toggle-heading',
20484 depending on context."
20485 (interactive)
20486 (cond
20487 ((org-at-table-p)
20488 (call-interactively 'org-table-recalculate))
20490 ;; Convert all lines in region to list items
20491 (call-interactively 'org-toggle-heading))))
20493 (defun org-ctrl-c-minus ()
20494 "Insert separator line in table or modify bullet status of line.
20495 Also turns a plain line or a region of lines into list items.
20496 Calls `org-table-insert-hline', `org-toggle-item', or
20497 `org-cycle-list-bullet', depending on context."
20498 (interactive)
20499 (cond
20500 ((org-at-table-p)
20501 (call-interactively 'org-table-insert-hline))
20502 ((org-region-active-p)
20503 (call-interactively 'org-toggle-item))
20504 ((org-in-item-p)
20505 (call-interactively 'org-cycle-list-bullet))
20507 (call-interactively 'org-toggle-item))))
20509 (defun org-toggle-heading (&optional nstars)
20510 "Convert headings to normal text, or items or text to headings.
20511 If there is no active region, only convert the current line.
20513 With a `\\[universal-argument]' prefix, convert the whole list at
20514 point into heading.
20516 In a region:
20518 - If the first non blank line is a headline, remove the stars
20519 from all headlines in the region.
20521 - If it is a normal line, turn each and every normal line (i.e.,
20522 not an heading or an item) in the region into headings. If you
20523 want to convert only the first line of this region, use one
20524 universal prefix argument.
20526 - If it is a plain list item, turn all plain list items into headings.
20528 When converting a line into a heading, the number of stars is chosen
20529 such that the lines become children of the current entry. However,
20530 when a numeric prefix argument is given, its value determines the
20531 number of stars to add."
20532 (interactive "P")
20533 (let ((skip-blanks
20534 (function
20535 ;; Return beginning of first non-blank line, starting from
20536 ;; line at POS.
20537 (lambda (pos)
20538 (save-excursion
20539 (goto-char pos)
20540 (while (org-at-comment-p) (forward-line))
20541 (skip-chars-forward " \r\t\n")
20542 (point-at-bol)))))
20543 beg end toggled)
20544 ;; Determine boundaries of changes. If a universal prefix has
20545 ;; been given, put the list in a region. If region ends at a bol,
20546 ;; do not consider the last line to be in the region.
20548 (when (and current-prefix-arg (org-at-item-p))
20549 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20550 (org-mark-element))
20552 (if (org-region-active-p)
20553 (setq beg (funcall skip-blanks (region-beginning))
20554 end (copy-marker (save-excursion
20555 (goto-char (region-end))
20556 (if (bolp) (point) (point-at-eol)))))
20557 (setq beg (funcall skip-blanks (point-at-bol))
20558 end (copy-marker (point-at-eol))))
20559 ;; Ensure inline tasks don't count as headings.
20560 (org-with-limited-levels
20561 (save-excursion
20562 (goto-char beg)
20563 (cond
20564 ;; Case 1. Started at an heading: de-star headings.
20565 ((org-at-heading-p)
20566 (while (< (point) end)
20567 (when (org-at-heading-p t)
20568 (looking-at org-outline-regexp) (replace-match "")
20569 (setq toggled t))
20570 (forward-line)))
20571 ;; Case 2. Started at an item: change items into headlines.
20572 ;; One star will be added by `org-list-to-subtree'.
20573 ((org-at-item-p)
20574 (while (< (point) end)
20575 (when (org-at-item-p)
20576 ;; Pay attention to cases when region ends before list.
20577 (let* ((struct (org-list-struct))
20578 (list-end
20579 (min (org-list-get-bottom-point struct) (1+ end))))
20580 (save-restriction
20581 (narrow-to-region (point) list-end)
20582 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20583 (setq toggled t))
20584 (forward-line)))
20585 ;; Case 3. Started at normal text: make every line an heading,
20586 ;; skipping headlines and items.
20587 (t (let* ((stars
20588 (make-string
20589 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20590 (add-stars
20591 (cond (nstars "") ; stars from prefix only
20592 ((equal stars "") "*") ; before first heading
20593 (org-odd-levels-only "**") ; inside heading, odd
20594 (t "*"))) ; inside heading, oddeven
20595 (rpl (concat stars add-stars " "))
20596 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20597 (while (< (point) (if (equal nstars '(4)) lend end))
20598 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20599 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20600 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20601 (forward-line)))))))
20602 (unless toggled (message "Cannot toggle heading from here"))))
20604 (defun org-meta-return (&optional arg)
20605 "Insert a new heading or wrap a region in a table.
20606 Calls `org-insert-heading', `org-insert-item' or
20607 `org-table-wrap-region', depending on context. When called with
20608 an argument, unconditionally call `org-insert-heading'."
20609 (interactive "P")
20610 (org-check-before-invisible-edit 'insert)
20611 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20612 (call-interactively (cond (arg #'org-insert-heading)
20613 ((org-at-table-p) #'org-table-wrap-region)
20614 ((org-in-item-p) #'org-insert-item)
20615 (t #'org-insert-heading)))))
20617 ;;; Menu entries
20619 (defsubst org-in-subtree-not-table-p ()
20620 "Are we in a subtree and not in a table?"
20621 (and (not (org-before-first-heading-p))
20622 (not (org-at-table-p))))
20624 ;; Define the Org mode menus
20625 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20626 '("Tbl"
20627 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20628 ["Next Field" org-cycle (org-at-table-p)]
20629 ["Previous Field" org-shifttab (org-at-table-p)]
20630 ["Next Row" org-return (org-at-table-p)]
20631 "--"
20632 ["Blank Field" org-table-blank-field (org-at-table-p)]
20633 ["Edit Field" org-table-edit-field (org-at-table-p)]
20634 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20635 "--"
20636 ("Column"
20637 ["Move Column Left" org-metaleft (org-at-table-p)]
20638 ["Move Column Right" org-metaright (org-at-table-p)]
20639 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20640 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20641 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20642 ("Row"
20643 ["Move Row Up" org-metaup (org-at-table-p)]
20644 ["Move Row Down" org-metadown (org-at-table-p)]
20645 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20646 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20647 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20648 "--"
20649 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20650 ("Rectangle"
20651 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20652 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20653 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20654 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20655 "--"
20656 ("Calculate"
20657 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20658 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20659 ["Edit Formulas" org-edit-special (org-at-table-p)]
20660 "--"
20661 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20662 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20663 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20664 "--"
20665 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20666 "--"
20667 ["Sum Column/Rectangle" org-table-sum
20668 (or (org-at-table-p) (org-region-active-p))]
20669 ["Which Column?" org-table-current-column (org-at-table-p)])
20670 ["Debug Formulas"
20671 org-table-toggle-formula-debugger
20672 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20673 ["Show Col/Row Numbers"
20674 org-table-toggle-coordinate-overlays
20675 :style toggle
20676 :selected (bound-and-true-p org-table-overlay-coordinates)]
20677 "--"
20678 ["Create" org-table-create (not (org-at-table-p))]
20679 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20680 ["Import from File" org-table-import (not (org-at-table-p))]
20681 ["Export to File" org-table-export (org-at-table-p)]
20682 "--"
20683 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20684 "--"
20685 ("Plot"
20686 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20687 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20689 (easy-menu-define org-org-menu org-mode-map "Org menu"
20690 '("Org"
20691 ("Show/Hide"
20692 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20693 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20694 ["Sparse Tree..." org-sparse-tree t]
20695 ["Reveal Context" org-reveal t]
20696 ["Show All" org-show-all t]
20697 "--"
20698 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20699 "--"
20700 ["New Heading" org-insert-heading t]
20701 ("Navigate Headings"
20702 ["Up" outline-up-heading t]
20703 ["Next" outline-next-visible-heading t]
20704 ["Previous" outline-previous-visible-heading t]
20705 ["Next Same Level" outline-forward-same-level t]
20706 ["Previous Same Level" outline-backward-same-level t]
20707 "--"
20708 ["Jump" org-goto t])
20709 ("Edit Structure"
20710 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20711 "--"
20712 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20713 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20714 "--"
20715 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20716 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20717 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20718 "--"
20719 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20720 "--"
20721 ["Copy visible text" org-copy-visible t]
20722 "--"
20723 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20724 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20725 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20726 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20727 "--"
20728 ["Sort Region/Children" org-sort t]
20729 "--"
20730 ["Convert to odd levels" org-convert-to-odd-levels t]
20731 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20732 ("Editing"
20733 ["Emphasis..." org-emphasize t]
20734 ["Edit Source Example" org-edit-special t]
20735 "--"
20736 ["Footnote new/jump" org-footnote-action t]
20737 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20738 ("Archive"
20739 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20740 "--"
20741 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20742 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20743 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20745 "--"
20746 ("Hyperlinks"
20747 ["Store Link (Global)" org-store-link t]
20748 ["Find existing link to here" org-occur-link-in-agenda-files t]
20749 ["Insert Link" org-insert-link t]
20750 ["Follow Link" org-open-at-point t]
20751 "--"
20752 ["Next link" org-next-link t]
20753 ["Previous link" org-previous-link t]
20754 "--"
20755 ["Descriptive Links"
20756 org-toggle-link-display
20757 :style radio
20758 :selected org-descriptive-links
20760 ["Literal Links"
20761 org-toggle-link-display
20762 :style radio
20763 :selected (not org-descriptive-links)])
20764 "--"
20765 ("TODO Lists"
20766 ["TODO/DONE/-" org-todo t]
20767 ("Select keyword"
20768 ["Next keyword" org-shiftright (org-at-heading-p)]
20769 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20770 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20771 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20772 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20773 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20774 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20775 "--"
20776 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20777 :selected org-enforce-todo-dependencies :style toggle :active t]
20778 "Settings for tree at point"
20779 ["Do Children sequentially" org-toggle-ordered-property :style radio
20780 :selected (org-entry-get nil "ORDERED")
20781 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20782 ["Do Children parallel" org-toggle-ordered-property :style radio
20783 :selected (not (org-entry-get nil "ORDERED"))
20784 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20785 "--"
20786 ["Set Priority" org-priority t]
20787 ["Priority Up" org-shiftup t]
20788 ["Priority Down" org-shiftdown t]
20789 "--"
20790 ["Get news from all feeds" org-feed-update-all t]
20791 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20792 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20793 ("TAGS and Properties"
20794 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20795 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20796 "--"
20797 ["Set property" org-set-property (not (org-before-first-heading-p))]
20798 ["Column view of properties" org-columns t]
20799 ["Insert Column View DBlock" org-columns-insert-dblock t])
20800 ("Dates and Scheduling"
20801 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20802 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20803 ("Change Date"
20804 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20805 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20806 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20807 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20808 ["Compute Time Range" org-evaluate-time-range t]
20809 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20810 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20811 "--"
20812 ["Custom time format" org-toggle-time-stamp-overlays
20813 :style radio :selected org-display-custom-times]
20814 "--"
20815 ["Goto Calendar" org-goto-calendar t]
20816 ["Date from Calendar" org-date-from-calendar t]
20817 "--"
20818 ["Start/Restart Timer" org-timer-start t]
20819 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20820 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20821 ["Insert Timer String" org-timer t]
20822 ["Insert Timer Item" org-timer-item t])
20823 ("Logging work"
20824 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20825 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20826 ["Clock out" org-clock-out t]
20827 ["Clock cancel" org-clock-cancel t]
20828 "--"
20829 ["Mark as default task" org-clock-mark-default-task t]
20830 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20831 ["Goto running clock" org-clock-goto t]
20832 "--"
20833 ["Display times" org-clock-display t]
20834 ["Create clock table" org-clock-report t]
20835 "--"
20836 ["Record DONE time"
20837 (progn (setq org-log-done (not org-log-done))
20838 (message "Switching to %s will %s record a timestamp"
20839 (car org-done-keywords)
20840 (if org-log-done "automatically" "not")))
20841 :style toggle :selected org-log-done])
20842 "--"
20843 ["Agenda Command..." org-agenda t]
20844 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20845 ("File List for Agenda")
20846 ("Special views current file"
20847 ["TODO Tree" org-show-todo-tree t]
20848 ["Check Deadlines" org-check-deadlines t]
20849 ["Tags/Property tree" org-match-sparse-tree t])
20850 "--"
20851 ["Export/Publish..." org-export-dispatch t]
20852 ("LaTeX"
20853 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20854 :style toggle :selected org-cdlatex-mode]
20855 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20856 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20857 ["Modify math symbol" org-cdlatex-math-modify
20858 (org-inside-LaTeX-fragment-p)]
20859 ["Insert citation" org-reftex-citation t])
20860 "--"
20861 ("MobileOrg"
20862 ["Push Files and Views" org-mobile-push t]
20863 ["Get Captured and Flagged" org-mobile-pull t]
20864 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20865 "--"
20866 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20867 "--"
20868 ("Documentation"
20869 ["Show Version" org-version t]
20870 ["Info Documentation" org-info t])
20871 ("Customize"
20872 ["Browse Org Group" org-customize t]
20873 "--"
20874 ["Expand This Menu" org-create-customize-menu
20875 (fboundp 'customize-menu-create)])
20876 ["Send bug report" org-submit-bug-report t]
20877 "--"
20878 ("Refresh/Reload"
20879 ["Refresh setup current buffer" org-mode-restart t]
20880 ["Reload Org (after update)" org-reload t]
20881 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20884 (defun org-info (&optional node)
20885 "Read documentation for Org in the info system.
20886 With optional NODE, go directly to that node."
20887 (interactive)
20888 (info (format "(org)%s" (or node ""))))
20890 ;;;###autoload
20891 (defun org-submit-bug-report ()
20892 "Submit a bug report on Org via mail.
20894 Don't hesitate to report any problems or inaccurate documentation.
20896 If you don't have setup sending mail from (X)Emacs, please copy the
20897 output buffer into your mail program, as it gives us important
20898 information about your Org version and configuration."
20899 (interactive)
20900 (require 'reporter)
20901 (defvar reporter-prompt-for-summary-p)
20902 (org-load-modules-maybe)
20903 (org-require-autoloaded-modules)
20904 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20905 (reporter-submit-bug-report
20906 "emacs-orgmode@gnu.org"
20907 (org-version nil 'full)
20908 (let (list)
20909 (save-window-excursion
20910 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20911 (delete-other-windows)
20912 (erase-buffer)
20913 (insert "You are about to submit a bug report to the Org mailing list.
20915 We would like to add your full Org and Outline configuration to the
20916 bug report. This greatly simplifies the work of the maintainer and
20917 other experts on the mailing list.
20919 HOWEVER, some variables you have customized may contain private
20920 information. The names of customers, colleagues, or friends, might
20921 appear in the form of file names, tags, todo states, or search strings.
20922 If you answer yes to the prompt, you might want to check and remove
20923 such private information before sending the email.")
20924 (add-text-properties (point-min) (point-max) '(face org-warning))
20925 (when (yes-or-no-p "Include your Org configuration ")
20926 (mapatoms
20927 (lambda (v)
20928 (and (boundp v)
20929 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20930 (or (and (symbol-value v)
20931 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20932 (and
20933 (get v 'custom-type) (get v 'standard-value)
20934 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20935 (push v list)))))
20936 (kill-buffer (get-buffer "*Warn about privacy*"))
20937 list))
20938 nil nil
20939 "Remember to cover the basics, that is, what you expected to happen and
20940 what in fact did happen. You don't know how to make a good report? See
20942 https://orgmode.org/manual/Feedback.html#Feedback
20944 Your bug report will be posted to the Org mailing list.
20945 ------------------------------------------------------------------------")
20946 (save-excursion
20947 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20948 (replace-match "\\1Bug: \\3 [\\2]")))))
20951 (defun org-install-agenda-files-menu ()
20952 (let ((bl (buffer-list)))
20953 (save-excursion
20954 (while bl
20955 (set-buffer (pop bl))
20956 (when (derived-mode-p 'org-mode) (setq bl nil)))
20957 (when (derived-mode-p 'org-mode)
20958 (easy-menu-change
20959 '("Org") "File List for Agenda"
20960 (append
20961 (list
20962 ["Edit File List" (org-edit-agenda-file-list) t]
20963 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20964 ["Remove Current File from List" org-remove-file t]
20965 ["Cycle through agenda files" org-cycle-agenda-files t]
20966 ["Occur in all agenda files" org-occur-in-agenda-files t]
20967 "--")
20968 (mapcar 'org-file-menu-entry
20969 ;; Prevent initialization from failing.
20970 (ignore-errors (org-agenda-files t)))))))))
20972 ;;;; Documentation
20974 (defun org-require-autoloaded-modules ()
20975 (interactive)
20976 (mapc #'require
20977 '(org-agenda org-archive org-attach org-clock org-colview org-id
20978 org-table org-timer)))
20980 ;;;###autoload
20981 (defun org-reload (&optional uncompiled)
20982 "Reload all Org Lisp files.
20983 With prefix arg UNCOMPILED, load the uncompiled versions."
20984 (interactive "P")
20985 (require 'loadhist)
20986 (let* ((org-dir (org-find-library-dir "org"))
20987 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20988 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20989 (remove-re (format "\\`%s\\'"
20990 (regexp-opt '("org" "org-loaddefs" "org-version"))))
20991 (feats (delete-dups
20992 (mapcar 'file-name-sans-extension
20993 (mapcar 'file-name-nondirectory
20994 (delq nil
20995 (mapcar 'feature-file
20996 features))))))
20997 (lfeat (append
20998 (sort
20999 (setq feats
21000 (delq nil (mapcar
21001 (lambda (f)
21002 (if (and (string-match feature-re f)
21003 (not (string-match remove-re f)))
21004 f nil))
21005 feats)))
21006 'string-lessp)
21007 (list "org-version" "org")))
21008 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21009 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21010 load-uncore load-misses)
21011 (setq load-misses
21012 (delq 't
21013 (mapcar (lambda (f)
21014 (or (org-load-noerror-mustsuffix (concat org-dir f))
21015 (and (string= org-dir contrib-dir)
21016 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21017 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21018 (add-to-list 'load-uncore f 'append)
21021 lfeat)))
21022 (when load-uncore
21023 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21024 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21025 (if load-misses
21026 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21027 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21028 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21030 ;;;###autoload
21031 (defun org-customize ()
21032 "Call the customize function with org as argument."
21033 (interactive)
21034 (org-load-modules-maybe)
21035 (org-require-autoloaded-modules)
21036 (customize-browse 'org))
21038 (defun org-create-customize-menu ()
21039 "Create a full customization menu for Org mode, insert it into the menu."
21040 (interactive)
21041 (org-load-modules-maybe)
21042 (org-require-autoloaded-modules)
21043 (if (fboundp 'customize-menu-create)
21044 (progn
21045 (easy-menu-change
21046 '("Org") "Customize"
21047 `(["Browse Org group" org-customize t]
21048 "--"
21049 ,(customize-menu-create 'org)
21050 ["Set" Custom-set t]
21051 ["Save" Custom-save t]
21052 ["Reset to Current" Custom-reset-current t]
21053 ["Reset to Saved" Custom-reset-saved t]
21054 ["Reset to Standard Settings" Custom-reset-standard t]))
21055 (message "\"Org\"-menu now contains full customization menu"))
21056 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21058 ;;;; Miscellaneous stuff
21060 ;;; Generally useful functions
21062 (defun org-link-display-format (s)
21063 "Replace links in string S with their description.
21064 If there is no description, use the link target."
21065 (save-match-data
21066 (replace-regexp-in-string
21067 org-bracket-link-analytic-regexp
21068 (lambda (m)
21069 (if (match-end 5) (match-string 5 m)
21070 (concat (match-string 1 m) (match-string 3 m))))
21071 s nil t)))
21073 (defun org-toggle-link-display ()
21074 "Toggle the literal or descriptive display of links."
21075 (interactive)
21076 (if org-descriptive-links
21077 (progn (org-remove-from-invisibility-spec '(org-link))
21078 (org-restart-font-lock)
21079 (setq org-descriptive-links nil))
21080 (progn (add-to-invisibility-spec '(org-link))
21081 (org-restart-font-lock)
21082 (setq org-descriptive-links t))))
21084 (defun org-in-clocktable-p ()
21085 "Check if the cursor is in a clocktable."
21086 (let ((pos (point)) start)
21087 (save-excursion
21088 (end-of-line 1)
21089 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21090 (setq start (match-beginning 0))
21091 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21092 (>= (match-end 0) pos)
21093 start))))
21095 (defun org-in-verbatim-emphasis ()
21096 (save-match-data
21097 (and (org-in-regexp org-verbatim-re 2)
21098 (>= (point) (match-beginning 3))
21099 (<= (point) (match-end 4)))))
21101 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21102 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21103 (if (and marker (marker-buffer marker)
21104 (buffer-live-p (marker-buffer marker)))
21105 (progn
21106 (pop-to-buffer-same-window (marker-buffer marker))
21107 (when (or (> marker (point-max)) (< marker (point-min)))
21108 (widen))
21109 (goto-char marker)
21110 (org-show-context 'org-goto))
21111 (if bookmark
21112 (bookmark-jump bookmark)
21113 (error "Cannot find location"))))
21115 (defun org-quote-csv-field (s)
21116 "Quote field for inclusion in CSV material."
21117 (if (string-match "[\",]" s)
21118 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21121 (defun org-force-self-insert (N)
21122 "Needed to enforce self-insert under remapping."
21123 (interactive "p")
21124 (self-insert-command N))
21126 (defun org-fill-template (template alist)
21127 "Find each %key of ALIST in TEMPLATE and replace it."
21128 (let ((case-fold-search nil))
21129 (dolist (entry (sort (copy-sequence alist)
21130 (lambda (a b) (< (length (car a)) (length (car b))))))
21131 (setq template
21132 (replace-regexp-in-string
21133 (concat "%" (regexp-quote (car entry)))
21134 (or (cdr entry) "") template t t)))
21135 template))
21137 (defun org-quote-vert (s)
21138 "Replace \"|\" with \"\\vert\"."
21139 (while (string-match "|" s)
21140 (setq s (replace-match "\\vert" t t s)))
21143 (defun org-uuidgen-p (s)
21144 "Is S an ID created by UUIDGEN?"
21145 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21147 (defun org-in-src-block-p (&optional inside)
21148 "Whether point is in a code source block.
21149 When INSIDE is non-nil, don't consider we are within a src block
21150 when point is at #+BEGIN_SRC or #+END_SRC."
21151 (let ((case-fold-search t))
21152 (or (and (eq (get-char-property (point) 'src-block) t))
21153 (and (not inside)
21154 (save-match-data
21155 (save-excursion
21156 (beginning-of-line)
21157 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21159 (defun org-context ()
21160 "Return a list of contexts of the current cursor position.
21161 If several contexts apply, all are returned.
21162 Each context entry is a list with a symbol naming the context, and
21163 two positions indicating start and end of the context. Possible
21164 contexts are:
21166 :headline anywhere in a headline
21167 :headline-stars on the leading stars in a headline
21168 :todo-keyword on a TODO keyword (including DONE) in a headline
21169 :tags on the TAGS in a headline
21170 :priority on the priority cookie in a headline
21171 :item on the first line of a plain list item
21172 :item-bullet on the bullet/number of a plain list item
21173 :checkbox on the checkbox in a plain list item
21174 :table in an Org table
21175 :table-special on a special filed in a table
21176 :table-table in a table.el table
21177 :clocktable in a clocktable
21178 :src-block in a source block
21179 :link on a hyperlink
21180 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21181 :target on a <<target>>
21182 :radio-target on a <<<radio-target>>>
21183 :latex-fragment on a LaTeX fragment
21184 :latex-preview on a LaTeX fragment with overlaid preview image
21186 This function expects the position to be visible because it uses font-lock
21187 faces as a help to recognize the following contexts: :table-special, :link,
21188 and :keyword."
21189 (let* ((f (get-text-property (point) 'face))
21190 (faces (if (listp f) f (list f)))
21191 (case-fold-search t)
21192 (p (point)) clist o)
21193 ;; First the large context
21194 (cond
21195 ((org-at-heading-p t)
21196 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21197 (when (progn
21198 (beginning-of-line 1)
21199 (looking-at org-todo-line-tags-regexp))
21200 (push (org-point-in-group p 1 :headline-stars) clist)
21201 (push (org-point-in-group p 2 :todo-keyword) clist)
21202 (push (org-point-in-group p 4 :tags) clist))
21203 (goto-char p)
21204 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21205 (when (looking-at "\\[#[A-Z0-9]\\]")
21206 (push (org-point-in-group p 0 :priority) clist)))
21208 ((org-at-item-p)
21209 (push (org-point-in-group p 2 :item-bullet) clist)
21210 (push (list :item (point-at-bol)
21211 (save-excursion (org-end-of-item) (point)))
21212 clist)
21213 (and (org-at-item-checkbox-p)
21214 (push (org-point-in-group p 0 :checkbox) clist)))
21216 ((org-at-table-p)
21217 (push (list :table (org-table-begin) (org-table-end)) clist)
21218 (when (memq 'org-formula faces)
21219 (push (list :table-special
21220 (previous-single-property-change p 'face)
21221 (next-single-property-change p 'face)) clist)))
21222 ((org-at-table-p 'any)
21223 (push (list :table-table) clist)))
21224 (goto-char p)
21226 (let ((case-fold-search t))
21227 ;; New the "medium" contexts: clocktables, source blocks
21228 (cond ((org-in-clocktable-p)
21229 (push (list :clocktable
21230 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21231 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21232 (match-beginning 1))
21233 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21234 (match-end 0))) clist))
21235 ((org-in-src-block-p)
21236 (push (list :src-block
21237 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21238 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21239 (match-beginning 1))
21240 (and (search-forward "#+END_SRC" nil t)
21241 (match-beginning 0))) clist))))
21242 (goto-char p)
21244 ;; Now the small context
21245 (cond
21246 ((org-at-timestamp-p)
21247 (push (org-point-in-group p 0 :timestamp) clist))
21248 ((memq 'org-link faces)
21249 (push (list :link
21250 (previous-single-property-change p 'face)
21251 (next-single-property-change p 'face)) clist))
21252 ((memq 'org-special-keyword faces)
21253 (push (list :keyword
21254 (previous-single-property-change p 'face)
21255 (next-single-property-change p 'face)) clist))
21256 ((org-at-target-p)
21257 (push (org-point-in-group p 0 :target) clist)
21258 (goto-char (1- (match-beginning 0)))
21259 (when (looking-at org-radio-target-regexp)
21260 (push (org-point-in-group p 0 :radio-target) clist))
21261 (goto-char p))
21262 ((setq o (cl-some
21263 (lambda (o)
21264 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21266 (overlays-at (point))))
21267 (push (list :latex-fragment
21268 (overlay-start o) (overlay-end o)) clist)
21269 (push (list :latex-preview
21270 (overlay-start o) (overlay-end o)) clist))
21271 ((org-inside-LaTeX-fragment-p)
21272 ;; FIXME: positions wrong.
21273 (push (list :latex-fragment (point) (point)) clist)))
21275 (setq clist (nreverse (delq nil clist)))
21276 clist))
21278 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21279 "Non-nil when point is between matches of START-RE and END-RE.
21281 Also return a non-nil value when point is on one of the matches.
21283 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21284 buffer positions. Default values are the positions of headlines
21285 surrounding the point.
21287 The functions returns a cons cell whose car (resp. cdr) is the
21288 position before START-RE (resp. after END-RE)."
21289 (save-match-data
21290 (let ((pos (point))
21291 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21292 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21293 beg end)
21294 (save-excursion
21295 ;; Point is on a block when on START-RE or if START-RE can be
21296 ;; found before it...
21297 (and (or (org-in-regexp start-re)
21298 (re-search-backward start-re limit-up t))
21299 (setq beg (match-beginning 0))
21300 ;; ... and END-RE after it...
21301 (goto-char (match-end 0))
21302 (re-search-forward end-re limit-down t)
21303 (> (setq end (match-end 0)) pos)
21304 ;; ... without another START-RE in-between.
21305 (goto-char (match-beginning 0))
21306 (not (re-search-backward start-re (1+ beg) t))
21307 ;; Return value.
21308 (cons beg end))))))
21310 (defun org-in-block-p (names)
21311 "Non-nil when point belongs to a block whose name belongs to NAMES.
21313 NAMES is a list of strings containing names of blocks.
21315 Return first block name matched, or nil. Beware that in case of
21316 nested blocks, the returned name may not belong to the closest
21317 block from point."
21318 (save-match-data
21319 (catch 'exit
21320 (let ((case-fold-search t)
21321 (lim-up (save-excursion (outline-previous-heading)))
21322 (lim-down (save-excursion (outline-next-heading))))
21323 (dolist (name names)
21324 (let ((n (regexp-quote name)))
21325 (when (org-between-regexps-p
21326 (concat "^[ \t]*#\\+begin_" n)
21327 (concat "^[ \t]*#\\+end_" n)
21328 lim-up lim-down)
21329 (throw 'exit n)))))
21330 nil)))
21332 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21333 "Call `multi-occur' with buffers for all agenda files."
21334 (interactive "sOrg-files matching: ")
21335 (let* ((files (org-agenda-files))
21336 (tnames (mapcar #'file-truename files))
21337 (extra org-agenda-text-search-extra-files))
21338 (when (eq (car extra) 'agenda-archives)
21339 (setq extra (cdr extra))
21340 (setq files (org-add-archive-files files)))
21341 (dolist (f extra)
21342 (unless (member (file-truename f) tnames)
21343 (unless (member f files) (setq files (append files (list f))))
21344 (setq tnames (append tnames (list (file-truename f))))))
21345 (multi-occur
21346 (mapcar (lambda (x)
21347 (with-current-buffer
21348 ;; FIXME: Why not just (find-file-noselect x)?
21349 ;; Is it to avoid the "revert buffer" prompt?
21350 (or (get-file-buffer x) (find-file-noselect x))
21351 (widen)
21352 (current-buffer)))
21353 files)
21354 regexp)))
21356 (add-hook 'occur-mode-find-occurrence-hook
21357 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21359 (defun org-occur-link-in-agenda-files ()
21360 "Create a link and search for it in the agendas.
21361 The link is not stored in `org-stored-links', it is just created
21362 for the search purpose."
21363 (interactive)
21364 (let ((link (condition-case nil
21365 (org-store-link nil)
21366 (error "Unable to create a link to here"))))
21367 (org-occur-in-agenda-files (regexp-quote link))))
21369 (defun org-back-over-empty-lines ()
21370 "Move backwards over whitespace, to the beginning of the first empty line.
21371 Returns the number of empty lines passed."
21372 (let ((pos (point)))
21373 (if (cdr (assq 'heading org-blank-before-new-entry))
21374 (skip-chars-backward " \t\n\r")
21375 (unless (eobp)
21376 (forward-line -1)))
21377 (beginning-of-line 2)
21378 (goto-char (min (point) pos))
21379 (count-lines (point) pos)))
21381 (defun org-switch-to-buffer-other-window (&rest args)
21382 "Switch to buffer in a second window on the current frame.
21383 In particular, do not allow pop-up frames.
21384 Returns the newly created buffer."
21385 (org-no-popups
21386 (apply 'switch-to-buffer-other-window args)))
21388 (defun org-replace-escapes (string table)
21389 "Replace %-escapes in STRING with values in TABLE.
21390 TABLE is an association list with keys like \"%a\" and string values.
21391 The sequences in STRING may contain normal field width and padding information,
21392 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21393 so values can contain further %-escapes if they are define later in TABLE."
21394 (let ((tbl (copy-alist table))
21395 (case-fold-search nil)
21396 (pchg 0)
21397 re rpl)
21398 (dolist (e tbl)
21399 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21400 (when (and (cdr e) (string-match re (cdr e)))
21401 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21402 (safe "SREF"))
21403 (add-text-properties 0 3 (list 'sref sref) safe)
21404 (setcdr e (replace-match safe t t (cdr e)))))
21405 (while (string-match re string)
21406 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21407 (cdr e)))
21408 (setq string (replace-match rpl t t string))))
21409 (while (setq pchg (next-property-change pchg string))
21410 (let ((sref (get-text-property pchg 'sref string)))
21411 (when (and sref (string-match "SREF" string pchg))
21412 (setq string (replace-match sref t t string)))))
21413 string))
21415 ;;; TODO: Only called once, from ox-odt which should probably use
21416 ;;; org-export-inline-image-p or something.
21417 (defun org-file-image-p (file)
21418 "Return non-nil if FILE is an image."
21419 (save-match-data
21420 (string-match (image-file-name-regexp) file)))
21422 (defun org-get-cursor-date (&optional with-time)
21423 "Return the date at cursor in as a time.
21424 This works in the calendar and in the agenda, anywhere else it just
21425 returns the current time.
21426 If WITH-TIME is non-nil, returns the time of the event at point (in
21427 the agenda) or the current time of the day."
21428 (let (date day defd tp hod mod)
21429 (when with-time
21430 (setq tp (get-text-property (point) 'time))
21431 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21432 (setq hod (string-to-number (match-string 1 tp))
21433 mod (string-to-number (match-string 2 tp))))
21434 (or tp (let ((now (decode-time)))
21435 (setq hod (nth 2 now)
21436 mod (nth 1 now)))))
21437 (cond
21438 ((eq major-mode 'calendar-mode)
21439 (setq date (calendar-cursor-to-date)
21440 defd (encode-time 0 (or mod 0) (or hod 0)
21441 (nth 1 date) (nth 0 date) (nth 2 date))))
21442 ((eq major-mode 'org-agenda-mode)
21443 (setq day (get-text-property (point) 'day))
21444 (when day
21445 (setq date (calendar-gregorian-from-absolute day)
21446 defd (encode-time 0 (or mod 0) (or hod 0)
21447 (nth 1 date) (nth 0 date) (nth 2 date))))))
21448 (or defd (current-time))))
21450 (defun org-mark-subtree (&optional up)
21451 "Mark the current subtree.
21452 This puts point at the start of the current subtree, and mark at
21453 the end. If a numeric prefix UP is given, move up into the
21454 hierarchy of headlines by UP levels before marking the subtree."
21455 (interactive "P")
21456 (org-with-limited-levels
21457 (cond ((org-at-heading-p) (beginning-of-line))
21458 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21459 (t (outline-previous-visible-heading 1))))
21460 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21461 (if (called-interactively-p 'any)
21462 (call-interactively 'org-mark-element)
21463 (org-mark-element)))
21465 (defun org-file-newer-than-p (file time)
21466 "Non-nil if FILE is newer than TIME.
21467 FILE is a filename, as a string, TIME is a list of integers, as
21468 returned by, e.g., `current-time'."
21469 (and (file-exists-p file)
21470 ;; Only compare times up to whole seconds as some file-systems
21471 ;; (e.g. HFS+) do not retain any finer granularity. As
21472 ;; a consequence, make sure we return non-nil when the two
21473 ;; times are equal.
21474 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21475 (cl-subseq time 0 2)))))
21477 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21478 "Compile a SOURCE file using PROCESS.
21480 PROCESS is either a function or a list of shell commands, as
21481 strings. EXT is a file extension, without the leading dot, as
21482 a string. It is used to check if the process actually succeeded.
21484 PROCESS must create a file with the same base name and directory
21485 as SOURCE, but ending with EXT. The function then returns its
21486 filename. Otherwise, it raises an error. The error message can
21487 then be refined by providing string ERR-MSG, which is appended to
21488 the standard message.
21490 If PROCESS is a function, it is called with a single argument:
21491 the SOURCE file.
21493 If it is a list of commands, each of them is called using
21494 `shell-command'. By default, in each command, %b, %f, %F, %o and
21495 %O are replaced with, respectively, SOURCE base name, name, full
21496 name, directory and absolute output file name. It is possible,
21497 however, to use more place-holders by specifying them in optional
21498 argument SPEC, as an alist following the pattern
21500 (CHARACTER . REPLACEMENT-STRING).
21502 When PROCESS is a list of commands, optional argument LOG-BUF can
21503 be set to a buffer or a buffer name. `shell-command' then uses
21504 it for output."
21505 (let* ((base-name (file-name-base source))
21506 (full-name (file-truename source))
21507 (out-dir (or (file-name-directory source) "./"))
21508 (output (expand-file-name (concat base-name "." ext) out-dir))
21509 (time (current-time))
21510 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21511 (save-window-excursion
21512 (pcase process
21513 ((pred functionp) (funcall process (shell-quote-argument source)))
21514 ((pred consp)
21515 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21516 (spec (append spec
21517 `((?b . ,(shell-quote-argument base-name))
21518 (?f . ,(shell-quote-argument source))
21519 (?F . ,(shell-quote-argument full-name))
21520 (?o . ,(shell-quote-argument out-dir))
21521 (?O . ,(shell-quote-argument output))))))
21522 (dolist (command process)
21523 (shell-command (format-spec command spec) log-buf))
21524 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21525 (_ (error "No valid command to process %S%s" source err-msg))))
21526 ;; Check for process failure. Output file is expected to be
21527 ;; located in the same directory as SOURCE.
21528 (unless (org-file-newer-than-p output time)
21529 (error (format "File %S wasn't produced%s" output err-msg)))
21530 output))
21532 ;;; Indentation
21534 (defvar org-element-greater-elements)
21535 (defun org--get-expected-indentation (element contentsp)
21536 "Expected indentation column for current line, according to ELEMENT.
21537 ELEMENT is an element containing point. CONTENTSP is non-nil
21538 when indentation is to be computed according to contents of
21539 ELEMENT."
21540 (let ((type (org-element-type element))
21541 (start (org-element-property :begin element))
21542 (post-affiliated (org-element-property :post-affiliated element)))
21543 (org-with-wide-buffer
21544 (cond
21545 (contentsp
21546 (cl-case type
21547 ((diary-sexp footnote-definition) 0)
21548 ((headline inlinetask nil)
21549 (if (not org-adapt-indentation) 0
21550 (let ((level (org-current-level)))
21551 (if level (1+ level) 0))))
21552 ((item plain-list) (org-list-item-body-column post-affiliated))
21554 (goto-char start)
21555 (org-get-indentation))))
21556 ((memq type '(headline inlinetask nil))
21557 (if (org-match-line "[ \t]*$")
21558 (org--get-expected-indentation element t)
21560 ((memq type '(diary-sexp footnote-definition)) 0)
21561 ;; First paragraph of a footnote definition or an item.
21562 ;; Indent like parent.
21563 ((< (line-beginning-position) start)
21564 (org--get-expected-indentation
21565 (org-element-property :parent element) t))
21566 ;; At first line: indent according to previous sibling, if any,
21567 ;; ignoring footnote definitions and inline tasks, or parent's
21568 ;; contents.
21569 ((= (line-beginning-position) start)
21570 (catch 'exit
21571 (while t
21572 (if (= (point-min) start) (throw 'exit 0)
21573 (goto-char (1- start))
21574 (let* ((previous (org-element-at-point))
21575 (parent previous))
21576 (while (and parent (<= (org-element-property :end parent) start))
21577 (setq previous parent
21578 parent (org-element-property :parent parent)))
21579 (cond
21580 ((not previous) (throw 'exit 0))
21581 ((> (org-element-property :end previous) start)
21582 (throw 'exit (org--get-expected-indentation previous t)))
21583 ((memq (org-element-type previous)
21584 '(footnote-definition inlinetask))
21585 (setq start (org-element-property :begin previous)))
21586 (t (goto-char (org-element-property :begin previous))
21587 (throw 'exit
21588 (if (bolp) (org-get-indentation)
21589 ;; At first paragraph in an item or
21590 ;; a footnote definition.
21591 (org--get-expected-indentation
21592 (org-element-property :parent previous) t))))))))))
21593 ;; Otherwise, move to the first non-blank line above.
21595 (beginning-of-line)
21596 (let ((pos (point)))
21597 (skip-chars-backward " \r\t\n")
21598 (cond
21599 ;; Two blank lines end a footnote definition or a plain
21600 ;; list. When we indent an empty line after them, the
21601 ;; containing list or footnote definition is over, so it
21602 ;; qualifies as a previous sibling. Therefore, we indent
21603 ;; like its first line.
21604 ((and (memq type '(footnote-definition plain-list))
21605 (> (count-lines (point) pos) 2))
21606 (goto-char start)
21607 (org-get-indentation))
21608 ;; Line above is the first one of a paragraph at the
21609 ;; beginning of an item or a footnote definition. Indent
21610 ;; like parent.
21611 ((< (line-beginning-position) start)
21612 (org--get-expected-indentation
21613 (org-element-property :parent element) t))
21614 ;; Line above is the beginning of an element, i.e., point
21615 ;; was originally on the blank lines between element's start
21616 ;; and contents.
21617 ((= (line-beginning-position) post-affiliated)
21618 (org--get-expected-indentation element t))
21619 ;; POS is after contents in a greater element. Indent like
21620 ;; the beginning of the element.
21621 ((and (memq type org-element-greater-elements)
21622 (let ((cend (org-element-property :contents-end element)))
21623 (and cend (<= cend pos))))
21624 ;; As a special case, if point is at the end of a footnote
21625 ;; definition or an item, indent like the very last element
21626 ;; within. If that last element is an item, indent like
21627 ;; its contents.
21628 (if (memq type '(footnote-definition item plain-list))
21629 (let ((last (org-element-at-point)))
21630 (goto-char pos)
21631 (org--get-expected-indentation
21632 last (eq (org-element-type last) 'item)))
21633 (goto-char start)
21634 (org-get-indentation)))
21635 ;; In any other case, indent like the current line.
21636 (t (org-get-indentation)))))))))
21638 (defun org--align-node-property ()
21639 "Align node property at point.
21640 Alignment is done according to `org-property-format', which see."
21641 (when (save-excursion
21642 (beginning-of-line)
21643 (looking-at org-property-re))
21644 (replace-match
21645 (concat (match-string 4)
21646 (org-trim
21647 (format org-property-format (match-string 1) (match-string 3))))
21648 t t)))
21650 (defun org-indent-line ()
21651 "Indent line depending on context.
21653 Indentation is done according to the following rules:
21655 - Footnote definitions, diary sexps, headlines and inline tasks
21656 have to start at column 0.
21658 - On the very first line of an element, consider, in order, the
21659 next rules until one matches:
21661 1. If there's a sibling element before, ignoring footnote
21662 definitions and inline tasks, indent like its first line.
21664 2. If element has a parent, indent like its contents. More
21665 precisely, if parent is an item, indent after the
21666 description part, if any, or the bullet (see
21667 `org-list-description-max-indent'). Else, indent like
21668 parent's first line.
21670 3. Otherwise, indent relatively to current level, if
21671 `org-adapt-indentation' is non-nil, or to left margin.
21673 - On a blank line at the end of an element, indent according to
21674 the type of the element. More precisely
21676 1. If element is a plain list, an item, or a footnote
21677 definition, indent like the very last element within.
21679 2. If element is a paragraph, indent like its last non blank
21680 line.
21682 3. Otherwise, indent like its very first line.
21684 - In the code part of a source block, use language major mode
21685 to indent current line if `org-src-tab-acts-natively' is
21686 non-nil. If it is nil, do nothing.
21688 - Otherwise, indent like the first non-blank line above.
21690 The function doesn't indent an item as it could break the whole
21691 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21692 `\\[org-shiftmetaright]'.
21694 Also align node properties according to `org-property-format'."
21695 (interactive)
21696 (cond
21697 ((org-at-heading-p) 'noindent)
21699 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21700 (type (org-element-type element)))
21701 (cond ((and (memq type '(plain-list item))
21702 (= (line-beginning-position)
21703 (org-element-property :post-affiliated element)))
21704 'noindent)
21705 ((and (eq type 'latex-environment)
21706 (>= (point) (org-element-property :post-affiliated element))
21707 (< (point) (org-with-wide-buffer
21708 (goto-char (org-element-property :end element))
21709 (skip-chars-backward " \r\t\n")
21710 (line-beginning-position 2))))
21711 'noindent)
21712 ((and (eq type 'src-block)
21713 org-src-tab-acts-natively
21714 (> (line-beginning-position)
21715 (org-element-property :post-affiliated element))
21716 (< (line-beginning-position)
21717 (org-with-wide-buffer
21718 (goto-char (org-element-property :end element))
21719 (skip-chars-backward " \r\t\n")
21720 (line-beginning-position))))
21721 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21723 (let ((column (org--get-expected-indentation element nil)))
21724 ;; Preserve current column.
21725 (if (<= (current-column) (current-indentation))
21726 (indent-line-to column)
21727 (save-excursion (indent-line-to column))))
21728 ;; Align node property. Also preserve current column.
21729 (when (eq type 'node-property)
21730 (let ((column (current-column)))
21731 (org--align-node-property)
21732 (org-move-to-column column)))))))))
21734 (defun org-indent-region (start end)
21735 "Indent each non-blank line in the region.
21736 Called from a program, START and END specify the region to
21737 indent. The function will not indent contents of example blocks,
21738 verse blocks and export blocks as leading white spaces are
21739 assumed to be significant there."
21740 (interactive "r")
21741 (save-excursion
21742 (goto-char start)
21743 (skip-chars-forward " \r\t\n")
21744 (unless (eobp) (beginning-of-line))
21745 (let ((indent-to
21746 (lambda (ind pos)
21747 ;; Set IND as indentation for all lines between point and
21748 ;; POS. Blank lines are ignored. Leave point after POS
21749 ;; once done.
21750 (let ((limit (copy-marker pos)))
21751 (while (< (point) limit)
21752 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21753 (forward-line))
21754 (set-marker limit nil))))
21755 (end (copy-marker end)))
21756 (while (< (point) end)
21757 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21758 (let* ((element (org-element-at-point))
21759 (type (org-element-type element))
21760 (element-end (copy-marker (org-element-property :end element)))
21761 (ind (org--get-expected-indentation element nil)))
21762 (cond
21763 ;; Element indented as a single block. Example blocks
21764 ;; preserving indentation are a special case since the
21765 ;; "contents" must not be indented whereas the block
21766 ;; boundaries can.
21767 ((or (memq type '(export-block latex-environment))
21768 (and (eq type 'example-block)
21769 (not
21770 (or org-src-preserve-indentation
21771 (org-element-property :preserve-indent element)))))
21772 (let ((offset (- ind (org-get-indentation))))
21773 (unless (zerop offset)
21774 (indent-rigidly (org-element-property :begin element)
21775 (org-element-property :end element)
21776 offset)))
21777 (goto-char element-end))
21778 ;; Elements indented line wise. Be sure to exclude
21779 ;; example blocks (preserving indentation) and source
21780 ;; blocks from this category as they are treated
21781 ;; specially later.
21782 ((or (memq type '(paragraph table table-row))
21783 (not (or (org-element-property :contents-begin element)
21784 (memq type '(example-block src-block)))))
21785 (when (eq type 'node-property)
21786 (org--align-node-property)
21787 (beginning-of-line))
21788 (funcall indent-to ind (min element-end end)))
21789 ;; Elements consisting of three parts: before the
21790 ;; contents, the contents, and after the contents. The
21791 ;; contents are treated specially, according to the
21792 ;; element type, or not indented at all. Other parts are
21793 ;; indented as a single block.
21795 (let* ((post (copy-marker
21796 (org-element-property :post-affiliated element)))
21797 (cbeg
21798 (copy-marker
21799 (cond
21800 ((not (org-element-property :contents-begin element))
21801 ;; Fake contents for source blocks.
21802 (org-with-wide-buffer
21803 (goto-char post)
21804 (line-beginning-position 2)))
21805 ((memq type '(footnote-definition item plain-list))
21806 ;; Contents in these elements could start on
21807 ;; the same line as the beginning of the
21808 ;; element. Make sure we start indenting
21809 ;; from the second line.
21810 (org-with-wide-buffer
21811 (goto-char post)
21812 (end-of-line)
21813 (skip-chars-forward " \r\t\n")
21814 (if (eobp) (point) (line-beginning-position))))
21815 (t (org-element-property :contents-begin element)))))
21816 (cend (copy-marker
21817 (or (org-element-property :contents-end element)
21818 ;; Fake contents for source blocks.
21819 (org-with-wide-buffer
21820 (goto-char element-end)
21821 (skip-chars-backward " \r\t\n")
21822 (line-beginning-position)))
21823 t)))
21824 ;; Do not change items indentation individually as it
21825 ;; might break the list as a whole. On the other
21826 ;; hand, when at a plain list, indent it as a whole.
21827 (cond ((eq type 'plain-list)
21828 (let ((offset (- ind (org-get-indentation))))
21829 (unless (zerop offset)
21830 (indent-rigidly (org-element-property :begin element)
21831 (org-element-property :end element)
21832 offset))
21833 (goto-char cbeg)))
21834 ((eq type 'item) (goto-char cbeg))
21835 (t (funcall indent-to ind (min cbeg end))))
21836 (when (< (point) end)
21837 (cl-case type
21838 ((example-block verse-block))
21839 (src-block
21840 ;; In a source block, indent source code
21841 ;; according to language major mode, but only if
21842 ;; `org-src-tab-acts-natively' is non-nil.
21843 (when (and (< (point) end) org-src-tab-acts-natively)
21844 (ignore-errors
21845 (org-babel-do-in-edit-buffer
21846 (indent-region (point-min) (point-max))))))
21847 (t (org-indent-region (point) (min cend end))))
21848 (goto-char (min cend end))
21849 (when (< (point) end)
21850 (funcall indent-to ind (min element-end end))))
21851 (set-marker post nil)
21852 (set-marker cbeg nil)
21853 (set-marker cend nil))))
21854 (set-marker element-end nil))))
21855 (set-marker end nil))))
21857 (defun org-indent-drawer ()
21858 "Indent the drawer at point."
21859 (interactive)
21860 (unless (save-excursion
21861 (beginning-of-line)
21862 (looking-at-p org-drawer-regexp))
21863 (user-error "Not at a drawer"))
21864 (let ((element (org-element-at-point)))
21865 (unless (memq (org-element-type element) '(drawer property-drawer))
21866 (user-error "Not at a drawer"))
21867 (org-with-wide-buffer
21868 (org-indent-region (org-element-property :begin element)
21869 (org-element-property :end element))))
21870 (message "Drawer at point indented"))
21872 (defun org-indent-block ()
21873 "Indent the block at point."
21874 (interactive)
21875 (unless (save-excursion
21876 (beginning-of-line)
21877 (let ((case-fold-search t))
21878 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21879 (user-error "Not at a block"))
21880 (let ((element (org-element-at-point)))
21881 (unless (memq (org-element-type element)
21882 '(comment-block center-block dynamic-block example-block
21883 export-block quote-block special-block
21884 src-block verse-block))
21885 (user-error "Not at a block"))
21886 (org-with-wide-buffer
21887 (org-indent-region (org-element-property :begin element)
21888 (org-element-property :end element))))
21889 (message "Block at point indented"))
21892 ;;; Filling
21894 ;; We use our own fill-paragraph and auto-fill functions.
21896 ;; `org-fill-paragraph' relies on adaptive filling and context
21897 ;; checking. Appropriate `fill-prefix' is computed with
21898 ;; `org-adaptive-fill-function'.
21900 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21901 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21902 ;; `org-adaptive-fill-function' value. Internally,
21903 ;; `org-comment-line-break-function' breaks the line.
21905 ;; `org-setup-filling' installs filling and auto-filling related
21906 ;; variables during `org-mode' initialization.
21908 (defun org-setup-filling ()
21909 (require 'org-element)
21910 ;; Prevent auto-fill from inserting unwanted new items.
21911 (when (boundp 'fill-nobreak-predicate)
21912 (setq-local
21913 fill-nobreak-predicate
21914 (org-uniquify
21915 (append fill-nobreak-predicate
21916 '(org-fill-line-break-nobreak-p
21917 org-fill-n-macro-as-item-nobreak-p
21918 org-fill-paragraph-with-timestamp-nobreak-p)))))
21919 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21920 (setq-local paragraph-start paragraph-ending)
21921 (setq-local paragraph-separate paragraph-ending))
21922 (setq-local fill-paragraph-function 'org-fill-paragraph)
21923 (setq-local auto-fill-inhibit-regexp nil)
21924 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21925 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21926 (setq-local comment-line-break-function 'org-comment-line-break-function))
21928 (defun org-fill-line-break-nobreak-p ()
21929 "Non-nil when a new line at point would create an Org line break."
21930 (save-excursion
21931 (skip-chars-backward "[ \t]")
21932 (skip-chars-backward "\\\\")
21933 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21935 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21936 "Non-nil when a new line at point would split a timestamp."
21937 (and (org-at-timestamp-p 'lax)
21938 (not (looking-at org-ts-regexp-both))))
21940 (defun org-fill-n-macro-as-item-nobreak-p ()
21941 "Non-nil when a new line at point would create a new list."
21942 ;; During export, a "n" macro followed by a dot or a closing
21943 ;; parenthesis can end up being parsed as a new list item.
21944 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21946 (defvar orgtbl-line-start-regexp) ; From org-table.el
21947 (defun org-adaptive-fill-function ()
21948 "Compute a fill prefix for the current line.
21949 Return fill prefix, as a string, or nil if current line isn't
21950 meant to be filled. For convenience, if `adaptive-fill-regexp'
21951 matches in paragraphs or comments, use it."
21952 (org-with-wide-buffer
21953 (unless (org-at-heading-p)
21954 (let* ((p (line-beginning-position))
21955 (element (save-excursion
21956 (beginning-of-line)
21957 (org-element-at-point)))
21958 (type (org-element-type element))
21959 (post-affiliated (org-element-property :post-affiliated element)))
21960 (unless (< p post-affiliated)
21961 (cl-case type
21962 (comment
21963 (save-excursion
21964 (beginning-of-line)
21965 (looking-at "[ \t]*")
21966 (concat (match-string 0) "# ")))
21967 (footnote-definition "")
21968 ((item plain-list)
21969 (make-string (org-list-item-body-column post-affiliated) ?\s))
21970 (paragraph
21971 ;; Fill prefix is usually the same as the current line,
21972 ;; unless the paragraph is at the beginning of an item.
21973 (let ((parent (org-element-property :parent element)))
21974 (save-excursion
21975 (beginning-of-line)
21976 (cond ((eq (org-element-type parent) 'item)
21977 (make-string (org-list-item-body-column
21978 (org-element-property :begin parent))
21979 ?\s))
21980 ((and adaptive-fill-regexp
21981 ;; Locally disable
21982 ;; `adaptive-fill-function' to let
21983 ;; `fill-context-prefix' handle
21984 ;; `adaptive-fill-regexp' variable.
21985 (let (adaptive-fill-function)
21986 (fill-context-prefix
21987 post-affiliated
21988 (org-element-property :end element)))))
21989 ((looking-at "[ \t]+") (match-string 0))
21990 (t "")))))
21991 (comment-block
21992 ;; Only fill contents if P is within block boundaries.
21993 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21994 (forward-line)
21995 (point)))
21996 (cend (save-excursion
21997 (goto-char (org-element-property :end element))
21998 (skip-chars-backward " \r\t\n")
21999 (line-beginning-position))))
22000 (when (and (>= p cbeg) (< p cend))
22001 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22002 (match-string 0)
22003 ""))))))))))
22005 (defun org-fill-element (&optional justify)
22006 "Fill element at point, when applicable.
22008 This function only applies to comment blocks, comments, example
22009 blocks and paragraphs. Also, as a special case, re-align table
22010 when point is at one.
22012 If JUSTIFY is non-nil (interactively, with prefix argument),
22013 justify as well. If `sentence-end-double-space' is non-nil, then
22014 period followed by one space does not end a sentence, so don't
22015 break a line there. The variable `fill-column' controls the
22016 width for filling.
22018 For convenience, when point is at a plain list, an item or
22019 a footnote definition, try to fill the first paragraph within."
22020 (with-syntax-table org-mode-transpose-word-syntax-table
22021 ;; Move to end of line in order to get the first paragraph within
22022 ;; a plain list or a footnote definition.
22023 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22024 ;; First check if point is in a blank line at the beginning of
22025 ;; the buffer. In that case, ignore filling.
22026 (cl-case (org-element-type element)
22027 ;; Use major mode filling function is src blocks.
22028 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22029 ;; Align Org tables, leave table.el tables as-is.
22030 (table-row (org-table-align) t)
22031 (table
22032 (when (eq (org-element-property :type element) 'org)
22033 (save-excursion
22034 (goto-char (org-element-property :post-affiliated element))
22035 (org-table-align)))
22037 (paragraph
22038 ;; Paragraphs may contain `line-break' type objects.
22039 (let ((beg (max (point-min)
22040 (org-element-property :contents-begin element)))
22041 (end (min (point-max)
22042 (org-element-property :contents-end element))))
22043 ;; Do nothing if point is at an affiliated keyword.
22044 (if (< (line-end-position) beg) t
22045 ;; Fill paragraph, taking line breaks into account.
22046 (save-excursion
22047 (goto-char beg)
22048 (let ((cuts (list beg)))
22049 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22050 (when (eq 'line-break
22051 (org-element-type
22052 (save-excursion (backward-char)
22053 (org-element-context))))
22054 (push (point) cuts)))
22055 (dolist (c (delq end cuts))
22056 (fill-region-as-paragraph c end justify)
22057 (setq end c))))
22058 t)))
22059 ;; Contents of `comment-block' type elements should be
22060 ;; filled as plain text, but only if point is within block
22061 ;; markers.
22062 (comment-block
22063 (let* ((case-fold-search t)
22064 (beg (save-excursion
22065 (goto-char (org-element-property :begin element))
22066 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22067 (forward-line)
22068 (point)))
22069 (end (save-excursion
22070 (goto-char (org-element-property :end element))
22071 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22072 (line-beginning-position))))
22073 (if (or (< (point) beg) (> (point) end)) t
22074 (fill-region-as-paragraph
22075 (save-excursion (end-of-line)
22076 (re-search-backward "^[ \t]*$" beg 'move)
22077 (line-beginning-position))
22078 (save-excursion (beginning-of-line)
22079 (re-search-forward "^[ \t]*$" end 'move)
22080 (line-beginning-position))
22081 justify))))
22082 ;; Fill comments.
22083 (comment
22084 (let ((begin (org-element-property :post-affiliated element))
22085 (end (org-element-property :end element)))
22086 (when (and (>= (point) begin) (<= (point) end))
22087 (let ((begin (save-excursion
22088 (end-of-line)
22089 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22090 (progn (forward-line) (point))
22091 begin)))
22092 (end (save-excursion
22093 (end-of-line)
22094 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22095 (1- (line-beginning-position))
22096 (skip-chars-backward " \r\t\n")
22097 (line-end-position)))))
22098 ;; Do not fill comments when at a blank line.
22099 (when (> end begin)
22100 (let ((fill-prefix
22101 (save-excursion
22102 (beginning-of-line)
22103 (looking-at "[ \t]*#")
22104 (let ((comment-prefix (match-string 0)))
22105 (goto-char (match-end 0))
22106 (if (looking-at adaptive-fill-regexp)
22107 (concat comment-prefix (match-string 0))
22108 (concat comment-prefix " "))))))
22109 (save-excursion
22110 (fill-region-as-paragraph begin end justify))))))
22112 ;; Ignore every other element.
22113 (otherwise t)))))
22115 (defun org-fill-paragraph (&optional justify region)
22116 "Fill element at point, when applicable.
22118 This function only applies to comment blocks, comments, example
22119 blocks and paragraphs. Also, as a special case, re-align table
22120 when point is at one.
22122 For convenience, when point is at a plain list, an item or
22123 a footnote definition, try to fill the first paragraph within.
22125 If JUSTIFY is non-nil (interactively, with prefix argument),
22126 justify as well. If `sentence-end-double-space' is non-nil, then
22127 period followed by one space does not end a sentence, so don't
22128 break a line there. The variable `fill-column' controls the
22129 width for filling.
22131 The REGION argument is non-nil if called interactively; in that
22132 case, if Transient Mark mode is enabled and the mark is active,
22133 fill each of the elements in the active region, instead of just
22134 filling the current element."
22135 (interactive (progn
22136 (barf-if-buffer-read-only)
22137 (list (if current-prefix-arg 'full) t)))
22138 (cond
22139 ((and region transient-mark-mode mark-active
22140 (not (eq (region-beginning) (region-end))))
22141 (let ((origin (point-marker))
22142 (start (region-beginning)))
22143 (unwind-protect
22144 (progn
22145 (goto-char (region-end))
22146 (while (> (point) start)
22147 (org-backward-paragraph)
22148 (org-fill-element justify)))
22149 (goto-char origin)
22150 (set-marker origin nil))))
22151 (t (org-fill-element justify))))
22152 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22154 (defun org-auto-fill-function ()
22155 "Auto-fill function."
22156 ;; Check if auto-filling is meaningful.
22157 (let ((fc (current-fill-column)))
22158 (when (and fc (> (current-column) fc))
22159 (let* ((fill-prefix (org-adaptive-fill-function))
22160 ;; Enforce empty fill prefix, if required. Otherwise, it
22161 ;; will be computed again.
22162 (adaptive-fill-mode (not (equal fill-prefix ""))))
22163 (when fill-prefix (do-auto-fill))))))
22165 (defun org-comment-line-break-function (&optional soft)
22166 "Break line at point and indent, continuing comment if within one.
22167 The inserted newline is marked hard if variable
22168 `use-hard-newlines' is true, unless optional argument SOFT is
22169 non-nil."
22170 (if soft (insert-and-inherit ?\n) (newline 1))
22171 (save-excursion (forward-char -1) (delete-horizontal-space))
22172 (delete-horizontal-space)
22173 (indent-to-left-margin)
22174 (insert-before-markers-and-inherit fill-prefix))
22177 ;;; Fixed Width Areas
22179 (defun org-toggle-fixed-width ()
22180 "Toggle fixed-width markup.
22182 Add or remove fixed-width markup on current line, whenever it
22183 makes sense. Return an error otherwise.
22185 If a region is active and if it contains only fixed-width areas
22186 or blank lines, remove all fixed-width markup in it. If the
22187 region contains anything else, convert all non-fixed-width lines
22188 to fixed-width ones.
22190 Blank lines at the end of the region are ignored unless the
22191 region only contains such lines."
22192 (interactive)
22193 (if (not (org-region-active-p))
22194 ;; No region:
22196 ;; Remove fixed width marker only in a fixed-with element.
22198 ;; Add fixed width maker in paragraphs, in blank lines after
22199 ;; elements or at the beginning of a headline or an inlinetask,
22200 ;; and before any one-line elements (e.g., a clock).
22201 (progn
22202 (beginning-of-line)
22203 (let* ((element (org-element-at-point))
22204 (type (org-element-type element)))
22205 (cond
22206 ((and (eq type 'fixed-width)
22207 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22208 (replace-match
22209 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22210 ((and (memq type '(babel-call clock comment diary-sexp headline
22211 horizontal-rule keyword paragraph
22212 planning))
22213 (<= (org-element-property :post-affiliated element) (point)))
22214 (skip-chars-forward " \t")
22215 (insert ": "))
22216 ((and (looking-at-p "[ \t]*$")
22217 (or (eq type 'inlinetask)
22218 (save-excursion
22219 (skip-chars-forward " \r\t\n")
22220 (<= (org-element-property :end element) (point)))))
22221 (delete-region (point) (line-end-position))
22222 (org-indent-line)
22223 (insert ": "))
22224 (t (user-error "Cannot insert a fixed-width line here")))))
22225 ;; Region active.
22226 (let* ((begin (save-excursion
22227 (goto-char (region-beginning))
22228 (line-beginning-position)))
22229 (end (copy-marker
22230 (save-excursion
22231 (goto-char (region-end))
22232 (unless (eolp) (beginning-of-line))
22233 (if (save-excursion (re-search-backward "\\S-" begin t))
22234 (progn (skip-chars-backward " \r\t\n") (point))
22235 (point)))))
22236 (all-fixed-width-p
22237 (catch 'not-all-p
22238 (save-excursion
22239 (goto-char begin)
22240 (skip-chars-forward " \r\t\n")
22241 (when (eobp) (throw 'not-all-p nil))
22242 (while (< (point) end)
22243 (let ((element (org-element-at-point)))
22244 (if (eq (org-element-type element) 'fixed-width)
22245 (goto-char (org-element-property :end element))
22246 (throw 'not-all-p nil))))
22247 t))))
22248 (if all-fixed-width-p
22249 (save-excursion
22250 (goto-char begin)
22251 (while (< (point) end)
22252 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22253 (replace-match
22254 "" nil nil nil
22255 (if (= (line-end-position) (match-end 0)) 0 1)))
22256 (forward-line)))
22257 (let ((min-ind (point-max)))
22258 ;; Find minimum indentation across all lines.
22259 (save-excursion
22260 (goto-char begin)
22261 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22262 (setq min-ind 0)
22263 (catch 'zerop
22264 (while (< (point) end)
22265 (unless (looking-at-p "[ \t]*$")
22266 (let ((ind (org-get-indentation)))
22267 (setq min-ind (min min-ind ind))
22268 (when (zerop ind) (throw 'zerop t))))
22269 (forward-line)))))
22270 ;; Loop over all lines and add fixed-width markup everywhere
22271 ;; but in fixed-width lines.
22272 (save-excursion
22273 (goto-char begin)
22274 (while (< (point) end)
22275 (cond
22276 ((org-at-heading-p)
22277 (insert ": ")
22278 (forward-line)
22279 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22280 (insert ":")
22281 (forward-line)))
22282 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22283 (let* ((element (org-element-at-point))
22284 (element-end (org-element-property :end element)))
22285 (if (eq (org-element-type element) 'fixed-width)
22286 (progn (goto-char element-end)
22287 (skip-chars-backward " \r\t\n")
22288 (forward-line))
22289 (let ((limit (min end element-end)))
22290 (while (< (point) limit)
22291 (org-move-to-column min-ind t)
22292 (insert ": ")
22293 (forward-line))))))
22295 (org-move-to-column min-ind t)
22296 (insert ": ")
22297 (forward-line)))))))
22298 (set-marker end nil))))
22301 ;;; Blocks
22303 (defun org-block-map (function &optional start end)
22304 "Call FUNCTION at the head of all source blocks in the current buffer.
22305 Optional arguments START and END can be used to limit the range."
22306 (let ((start (or start (point-min)))
22307 (end (or end (point-max))))
22308 (save-excursion
22309 (goto-char start)
22310 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22311 (save-excursion
22312 (save-match-data
22313 (goto-char (match-beginning 0))
22314 (funcall function)))))))
22316 (defun org-next-block (arg &optional backward block-regexp)
22317 "Jump to the next block.
22319 With a prefix argument ARG, jump forward ARG many blocks.
22321 When BACKWARD is non-nil, jump to the previous block.
22323 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22324 Match data is set according to this regexp when the function
22325 returns.
22327 Return point at beginning of the opening line of found block.
22328 Throw an error if no block is found."
22329 (interactive "p")
22330 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22331 (case-fold-search t)
22332 (search-fn (if backward #'re-search-backward #'re-search-forward))
22333 (count (or arg 1))
22334 (origin (point))
22335 last-element)
22336 (if backward (beginning-of-line) (end-of-line))
22337 (while (and (> count 0) (funcall search-fn re nil t))
22338 (let ((element (save-excursion
22339 (goto-char (match-beginning 0))
22340 (save-match-data (org-element-at-point)))))
22341 (when (and (memq (org-element-type element)
22342 '(center-block comment-block dynamic-block
22343 example-block export-block quote-block
22344 special-block src-block verse-block))
22345 (<= (match-beginning 0)
22346 (org-element-property :post-affiliated element)))
22347 (setq last-element element)
22348 (cl-decf count))))
22349 (if (= count 0)
22350 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22351 (save-match-data (org-show-context)))
22352 (goto-char origin)
22353 (user-error "No %s code blocks" (if backward "previous" "further")))))
22355 (defun org-previous-block (arg &optional block-regexp)
22356 "Jump to the previous block.
22357 With a prefix argument ARG, jump backward ARG many source blocks.
22358 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22359 (interactive "p")
22360 (org-next-block arg t block-regexp))
22363 ;;; Comments
22365 ;; Org comments syntax is quite complex. It requires the entire line
22366 ;; to be just a comment. Also, even with the right syntax at the
22367 ;; beginning of line, some elements (e.g., verse-block or
22368 ;; example-block) don't accept comments. Usual Emacs comment commands
22369 ;; cannot cope with those requirements. Therefore, Org replaces them.
22371 ;; Org still relies on `comment-dwim', but cannot trust
22372 ;; `comment-only-p'. So, `comment-region-function' and
22373 ;; `uncomment-region-function' both point
22374 ;; to`org-comment-or-uncomment-region'. Eventually,
22375 ;; `org-insert-comment' takes care of insertion of comments at the
22376 ;; beginning of line.
22378 ;; `org-setup-comments-handling' install comments related variables
22379 ;; during `org-mode' initialization.
22381 (defun org-setup-comments-handling ()
22382 (interactive)
22383 (setq-local comment-use-syntax nil)
22384 (setq-local comment-start "# ")
22385 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22386 (setq-local comment-insert-comment-function 'org-insert-comment)
22387 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22388 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22390 (defun org-insert-comment ()
22391 "Insert an empty comment above current line.
22392 If the line is empty, insert comment at its beginning. When
22393 point is within a source block, comment according to the related
22394 major mode."
22395 (if (let ((element (org-element-at-point)))
22396 (and (eq (org-element-type element) 'src-block)
22397 (< (save-excursion
22398 (goto-char (org-element-property :post-affiliated element))
22399 (line-end-position))
22400 (point))
22401 (> (save-excursion
22402 (goto-char (org-element-property :end element))
22403 (skip-chars-backward " \r\t\n")
22404 (line-beginning-position))
22405 (point))))
22406 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22407 (beginning-of-line)
22408 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22409 (open-line 1))
22410 (org-indent-line)
22411 (insert "# ")))
22413 (defvar comment-empty-lines) ; From newcomment.el.
22414 (defun org-comment-or-uncomment-region (beg end &rest _)
22415 "Comment or uncomment each non-blank line in the region.
22416 Uncomment each non-blank line between BEG and END if it only
22417 contains commented lines. Otherwise, comment them. If region is
22418 strictly within a source block, use appropriate comment syntax."
22419 (if (let ((element (org-element-at-point)))
22420 (and (eq (org-element-type element) 'src-block)
22421 (< (save-excursion
22422 (goto-char (org-element-property :post-affiliated element))
22423 (line-end-position))
22424 beg)
22425 (>= (save-excursion
22426 (goto-char (org-element-property :end element))
22427 (skip-chars-backward " \r\t\n")
22428 (line-beginning-position))
22429 end)))
22430 ;; Translate region boundaries for the Org buffer to the source
22431 ;; buffer.
22432 (let ((offset (- end beg)))
22433 (save-excursion
22434 (goto-char beg)
22435 (org-babel-do-in-edit-buffer
22436 (comment-or-uncomment-region (point) (+ offset (point))))))
22437 (save-restriction
22438 ;; Restrict region
22439 (narrow-to-region (save-excursion (goto-char beg)
22440 (skip-chars-forward " \r\t\n" end)
22441 (line-beginning-position))
22442 (save-excursion (goto-char end)
22443 (skip-chars-backward " \r\t\n" beg)
22444 (line-end-position)))
22445 (let ((uncommentp
22446 ;; UNCOMMENTP is non-nil when every non blank line between
22447 ;; BEG and END is a comment.
22448 (save-excursion
22449 (goto-char (point-min))
22450 (while (and (not (eobp))
22451 (let ((element (org-element-at-point)))
22452 (and (eq (org-element-type element) 'comment)
22453 (goto-char (min (point-max)
22454 (org-element-property
22455 :end element)))))))
22456 (eobp))))
22457 (if uncommentp
22458 ;; Only blank lines and comments in region: uncomment it.
22459 (save-excursion
22460 (goto-char (point-min))
22461 (while (not (eobp))
22462 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22463 (replace-match "" nil nil nil 1))
22464 (forward-line)))
22465 ;; Comment each line in region.
22466 (let ((min-indent (point-max)))
22467 ;; First find the minimum indentation across all lines.
22468 (save-excursion
22469 (goto-char (point-min))
22470 (while (and (not (eobp)) (not (zerop min-indent)))
22471 (unless (looking-at "[ \t]*$")
22472 (setq min-indent (min min-indent (current-indentation))))
22473 (forward-line)))
22474 ;; Then loop over all lines.
22475 (save-excursion
22476 (goto-char (point-min))
22477 (while (not (eobp))
22478 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22479 ;; Don't get fooled by invisible text (e.g. link path)
22480 ;; when moving to column MIN-INDENT.
22481 (let ((buffer-invisibility-spec nil))
22482 (org-move-to-column min-indent t))
22483 (insert comment-start))
22484 (forward-line)))))))))
22486 (defun org-comment-dwim (_arg)
22487 "Call the comment command you mean.
22488 Call `org-toggle-comment' if on a heading, otherwise call
22489 `comment-dwim', within a source edit buffer if needed."
22490 (interactive "*P")
22491 (cond ((org-at-heading-p)
22492 (call-interactively #'org-toggle-comment))
22493 ((org-in-src-block-p)
22494 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22495 (t (call-interactively #'comment-dwim))))
22498 ;;; Timestamps API
22500 ;; This section contains tools to operate on, or create, timestamp
22501 ;; objects, as returned by, e.g. `org-element-context'.
22503 (defun org-timestamp-from-string (s)
22504 "Convert Org timestamp S, as a string, into a timestamp object.
22505 Return nil if S is not a valid timestamp string."
22506 (when (org-string-nw-p s)
22507 (with-temp-buffer
22508 (save-excursion (insert s))
22509 (org-element-timestamp-parser))))
22511 (defun org-timestamp-from-time (time &optional with-time inactive)
22512 "Convert a time value into a timestamp object.
22514 TIME is an Emacs internal time representation, as returned, e.g.,
22515 by `current-time'.
22517 When optional argument WITH-TIME is non-nil, return a timestamp
22518 object with a time part, i.e., with hours and minutes.
22520 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22521 return an active timestamp."
22522 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22523 (org-element-create 'timestamp
22524 (list :type (if inactive 'inactive 'active)
22525 :year-start year
22526 :month-start month
22527 :day-start day
22528 :hour-start (and with-time hour)
22529 :minute-start (and with-time minute)))))
22531 (defun org-timestamp-to-time (timestamp &optional end)
22532 "Convert TIMESTAMP object into an Emacs internal time value.
22533 Use end of date range or time range when END is non-nil.
22534 Otherwise, use its start."
22535 (apply #'encode-time
22536 (cons 0
22537 (mapcar
22538 (lambda (prop) (or (org-element-property prop timestamp) 0))
22539 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22540 '(:minute-start :hour-start :day-start :month-start
22541 :year-start))))))
22543 (defun org-timestamp-has-time-p (timestamp)
22544 "Non-nil when TIMESTAMP has a time specified."
22545 (org-element-property :hour-start timestamp))
22547 (defun org-timestamp-format (timestamp format &optional end utc)
22548 "Format a TIMESTAMP object into a string.
22550 FORMAT is a format specifier to be passed to
22551 `format-time-string'.
22553 When optional argument END is non-nil, use end of date-range or
22554 time-range, if possible.
22556 When optional argument UTC is non-nil, time is be expressed as
22557 Universal Time."
22558 (format-time-string format (org-timestamp-to-time timestamp end)
22559 (and utc t)))
22561 (defun org-timestamp-split-range (timestamp &optional end)
22562 "Extract a TIMESTAMP object from a date or time range.
22564 END, when non-nil, means extract the end of the range.
22565 Otherwise, extract its start.
22567 Return a new timestamp object."
22568 (let ((type (org-element-property :type timestamp)))
22569 (if (memq type '(active inactive diary)) timestamp
22570 (let ((split-ts (org-element-copy timestamp)))
22571 ;; Set new type.
22572 (org-element-put-property
22573 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22574 ;; Copy start properties over end properties if END is
22575 ;; non-nil. Otherwise, copy end properties over `start' ones.
22576 (let ((p-alist '((:minute-start . :minute-end)
22577 (:hour-start . :hour-end)
22578 (:day-start . :day-end)
22579 (:month-start . :month-end)
22580 (:year-start . :year-end))))
22581 (dolist (p-cell p-alist)
22582 (org-element-put-property
22583 split-ts
22584 (funcall (if end #'car #'cdr) p-cell)
22585 (org-element-property
22586 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22587 ;; Eventually refresh `:raw-value'.
22588 (org-element-put-property split-ts :raw-value nil)
22589 (org-element-put-property
22590 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22592 (defun org-timestamp-translate (timestamp &optional boundary)
22593 "Translate TIMESTAMP object to custom format.
22595 Format string is defined in `org-time-stamp-custom-formats',
22596 which see.
22598 When optional argument BOUNDARY is non-nil, it is either the
22599 symbol `start' or `end'. In this case, only translate the
22600 starting or ending part of TIMESTAMP if it is a date or time
22601 range. Otherwise, translate both parts.
22603 Return timestamp as-is if `org-display-custom-times' is nil or if
22604 it has a `diary' type."
22605 (let ((type (org-element-property :type timestamp)))
22606 (if (or (not org-display-custom-times) (eq type 'diary))
22607 (org-element-interpret-data timestamp)
22608 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22609 org-time-stamp-custom-formats)))
22610 (if (and (not boundary) (memq type '(active-range inactive-range)))
22611 (concat (org-timestamp-format timestamp fmt)
22612 "--"
22613 (org-timestamp-format timestamp fmt t))
22614 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22618 ;;; Other stuff.
22620 (defvar reftex-docstruct-symbol)
22621 (defvar org--rds)
22623 (defun org-reftex-citation ()
22624 "Use reftex-citation to insert a citation into the buffer.
22625 This looks for a line like
22627 #+BIBLIOGRAPHY: foo plain option:-d
22629 and derives from it that foo.bib is the bibliography file relevant
22630 for this document. It then installs the necessary environment for RefTeX
22631 to work in this buffer and calls `reftex-citation' to insert a citation
22632 into the buffer.
22634 Export of such citations to both LaTeX and HTML is handled by the contributed
22635 package ox-bibtex by Taru Karttunen."
22636 (interactive)
22637 (let ((reftex-docstruct-symbol 'org--rds)
22638 org--rds bib)
22639 (org-with-wide-buffer
22640 (let ((case-fold-search t)
22641 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22642 (if (not (save-excursion
22643 (or (re-search-forward re nil t)
22644 (re-search-backward re nil t))))
22645 (user-error "No bibliography defined in file")
22646 (setq bib (concat (match-string 1) ".bib")
22647 org--rds (list (list 'bib bib))))))
22648 (call-interactively 'reftex-citation)))
22650 ;;;; Functions extending outline functionality
22652 (defun org-beginning-of-line (&optional n)
22653 "Go to the beginning of the current visible line.
22655 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22656 tags on the first attempt, and only move to after the tags when
22657 the cursor is already beyond the end of the headline.
22659 With argument N not nil or 1, move forward N - 1 lines first."
22660 (interactive "^p")
22661 (let ((origin (point))
22662 (special (pcase org-special-ctrl-a/e
22663 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22664 deactivate-mark)
22665 ;; First move to a visible line.
22666 (if (bound-and-true-p visual-line-mode)
22667 (beginning-of-visual-line n)
22668 (move-beginning-of-line n)
22669 ;; `move-beginning-of-line' may leave point after invisible
22670 ;; characters if line starts with such of these (e.g., with
22671 ;; a link at column 0). Really move to the beginning of the
22672 ;; current visible line.
22673 (beginning-of-line))
22674 (cond
22675 ;; No special behavior. Point is already at the beginning of
22676 ;; a line, logical or visual.
22677 ((not special))
22678 ;; `beginning-of-visual-line' left point before logical beginning
22679 ;; of line: point is at the beginning of a visual line. Bail
22680 ;; out.
22681 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22682 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22683 ;; At a headline, special position is before the title, but
22684 ;; after any TODO keyword or priority cookie.
22685 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22686 (line-end-position)))
22687 (bol (point)))
22688 (if (eq special 'reversed)
22689 (when (and (= origin bol) (eq last-command this-command))
22690 (goto-char refpos))
22691 (when (or (> origin refpos) (= origin bol))
22692 (goto-char refpos)))))
22693 ((and (looking-at org-list-full-item-re)
22694 (memq (org-element-type (save-match-data (org-element-at-point)))
22695 '(item plain-list)))
22696 ;; Set special position at first white space character after
22697 ;; bullet, and check-box, if any.
22698 (let ((after-bullet
22699 (let ((box (match-end 3)))
22700 (cond ((not box) (match-end 1))
22701 ((eq (char-after box) ?\s) (1+ box))
22702 (t box)))))
22703 (if (eq special 'reversed)
22704 (when (and (= (point) origin) (eq last-command this-command))
22705 (goto-char after-bullet))
22706 (when (or (> origin after-bullet) (= (point) origin))
22707 (goto-char after-bullet)))))
22708 ;; No special context. Point is already at beginning of line.
22709 (t nil))))
22711 (defun org-end-of-line (&optional n)
22712 "Go to the end of the line, but before ellipsis, if any.
22714 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22715 tags on the first attempt, and only move to after the tags when
22716 the cursor is already beyond the end of the headline.
22718 With argument N not nil or 1, move forward N - 1 lines first."
22719 (interactive "^p")
22720 (let ((origin (point))
22721 (special (pcase org-special-ctrl-a/e
22722 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22723 deactivate-mark)
22724 ;; First move to a visible line.
22725 (if (bound-and-true-p visual-line-mode)
22726 (beginning-of-visual-line n)
22727 (move-beginning-of-line n))
22728 (cond
22729 ;; At a headline, with tags.
22730 ((and special
22731 (save-excursion
22732 (beginning-of-line)
22733 (let ((case-fold-search nil))
22734 (looking-at org-complex-heading-regexp)))
22735 (match-end 5))
22736 (let ((tags (save-excursion
22737 (goto-char (match-beginning 5))
22738 (skip-chars-backward " \t")
22739 (point)))
22740 (visual-end (and (bound-and-true-p visual-line-mode)
22741 (save-excursion
22742 (end-of-visual-line)
22743 (point)))))
22744 ;; If `end-of-visual-line' brings us before end of line or
22745 ;; even tags, i.e., the headline spans over multiple visual
22746 ;; lines, move there.
22747 (cond ((and visual-end
22748 (< visual-end tags)
22749 (<= origin visual-end))
22750 (goto-char visual-end))
22751 ((eq special 'reversed)
22752 (if (and (= origin (line-end-position))
22753 (eq this-command last-command))
22754 (goto-char tags)
22755 (end-of-line)))
22757 (if (or (< origin tags) (= origin (line-end-position)))
22758 (goto-char tags)
22759 (end-of-line))))))
22760 ((bound-and-true-p visual-line-mode)
22761 (let ((bol (line-beginning-position)))
22762 (end-of-visual-line)
22763 ;; If `end-of-visual-line' gets us past the ellipsis at the
22764 ;; end of a line, backtrack and use `end-of-line' instead.
22765 (when (/= bol (line-beginning-position))
22766 (goto-char bol)
22767 (end-of-line))))
22768 (t (end-of-line)))))
22770 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22771 (define-key org-mode-map "\C-e" 'org-end-of-line)
22773 (defun org-backward-sentence (&optional _arg)
22774 "Go to beginning of sentence, or beginning of table field.
22775 This will call `backward-sentence' or `org-table-beginning-of-field',
22776 depending on context."
22777 (interactive)
22778 (let* ((element (org-element-at-point))
22779 (contents-begin (org-element-property :contents-begin element))
22780 (table (org-element-lineage element '(table) t)))
22781 (if (and table
22782 (> (point) contents-begin)
22783 (<= (point) (org-element-property :contents-end table)))
22784 (call-interactively #'org-table-beginning-of-field)
22785 (save-restriction
22786 (when (and contents-begin
22787 (< (point-min) contents-begin)
22788 (> (point) contents-begin))
22789 (narrow-to-region contents-begin
22790 (org-element-property :contents-end element)))
22791 (call-interactively #'backward-sentence)))))
22793 (defun org-forward-sentence (&optional _arg)
22794 "Go to end of sentence, or end of table field.
22795 This will call `forward-sentence' or `org-table-end-of-field',
22796 depending on context."
22797 (interactive)
22798 (if (and (org-at-heading-p)
22799 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22800 (save-restriction
22801 (narrow-to-region (line-beginning-position) (line-end-position))
22802 (call-interactively #'forward-sentence))
22803 (let* ((element (org-element-at-point))
22804 (contents-end (org-element-property :contents-end element))
22805 (table (org-element-lineage element '(table) t)))
22806 (if (and table
22807 (>= (point) (org-element-property :contents-begin table))
22808 (< (point) contents-end))
22809 (call-interactively #'org-table-end-of-field)
22810 (save-restriction
22811 (when (and contents-end
22812 (> (point-max) contents-end)
22813 ;; Skip blank lines between elements.
22814 (< (org-element-property :end element)
22815 (save-excursion (goto-char contents-end)
22816 (skip-chars-forward " \r\t\n"))))
22817 (narrow-to-region (org-element-property :contents-begin element)
22818 contents-end))
22819 ;; End of heading is considered as the end of a sentence.
22820 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22821 (call-interactively #'forward-sentence)))))))
22823 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22824 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22826 (defun org-kill-line (&optional _arg)
22827 "Kill line, to tags or end of line."
22828 (interactive)
22829 (cond
22830 ((or (not org-special-ctrl-k)
22831 (bolp)
22832 (not (org-at-heading-p)))
22833 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22834 org-ctrl-k-protect-subtree
22835 (or (eq org-ctrl-k-protect-subtree 'error)
22836 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22837 (user-error "C-k aborted as it would kill a hidden subtree"))
22838 (call-interactively
22839 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22840 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
22841 (kill-region (point) (match-beginning 1))
22842 (org-set-tags nil t))
22843 (t (kill-region (point) (point-at-eol)))))
22845 (define-key org-mode-map "\C-k" 'org-kill-line)
22847 (defun org-yank (&optional arg)
22848 "Yank. If the kill is a subtree, treat it specially.
22849 This command will look at the current kill and check if is a single
22850 subtree, or a series of subtrees[1]. If it passes the test, and if the
22851 cursor is at the beginning of a line or after the stars of a currently
22852 empty headline, then the yank is handled specially. How exactly depends
22853 on the value of the following variables.
22855 `org-yank-folded-subtrees'
22856 By default, this variable is non-nil, which results in
22857 subtree(s) being folded after insertion, except if doing so
22858 would swallow text after the yanked text.
22860 `org-yank-adjusted-subtrees'
22861 When non-nil (the default value is nil), the subtree will be
22862 promoted or demoted in order to fit into the local outline tree
22863 structure, which means that the level will be adjusted so that it
22864 becomes the smaller one of the two *visible* surrounding headings.
22866 Any prefix to this command will cause `yank' to be called directly with
22867 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22868 will just
22869 plainly yank the text as it is.
22871 \[1] The test checks if the first non-white line is a heading
22872 and if there are no other headings with fewer stars."
22873 (interactive "P")
22874 (org-yank-generic 'yank arg))
22876 (defun org-yank-generic (command arg)
22877 "Perform some yank-like command.
22879 This function implements the behavior described in the `org-yank'
22880 documentation. However, it has been generalized to work for any
22881 interactive command with similar behavior."
22883 ;; pretend to be command COMMAND
22884 (setq this-command command)
22886 (if arg
22887 (call-interactively command)
22889 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22890 (and (org-kill-is-subtree-p)
22891 (or (bolp)
22892 (and (looking-at "[ \t]*$")
22893 (string-match
22894 "\\`\\*+\\'"
22895 (buffer-substring (point-at-bol) (point)))))))
22896 swallowp)
22897 (cond
22898 ((and subtreep org-yank-folded-subtrees)
22899 (let ((beg (point))
22900 end)
22901 (if (and subtreep org-yank-adjusted-subtrees)
22902 (org-paste-subtree nil nil 'for-yank)
22903 (call-interactively command))
22905 (setq end (point))
22906 (goto-char beg)
22907 (when (and (bolp) subtreep
22908 (not (setq swallowp
22909 (org-yank-folding-would-swallow-text beg end))))
22910 (org-with-limited-levels
22911 (or (looking-at org-outline-regexp)
22912 (re-search-forward org-outline-regexp-bol end t))
22913 (while (and (< (point) end) (looking-at org-outline-regexp))
22914 (outline-hide-subtree)
22915 (org-cycle-show-empty-lines 'folded)
22916 (condition-case nil
22917 (outline-forward-same-level 1)
22918 (error (goto-char end))))))
22919 (when swallowp
22920 (message
22921 "Inserted text not folded because that would swallow text"))
22923 (goto-char end)
22924 (skip-chars-forward " \t\n\r")
22925 (beginning-of-line 1)
22926 (push-mark beg 'nomsg)))
22927 ((and subtreep org-yank-adjusted-subtrees)
22928 (let ((beg (point-at-bol)))
22929 (org-paste-subtree nil nil 'for-yank)
22930 (push-mark beg 'nomsg)))
22932 (call-interactively command))))))
22934 (defun org-yank-folding-would-swallow-text (beg end)
22935 "Would hide-subtree at BEG swallow any text after END?"
22936 (let (level)
22937 (org-with-limited-levels
22938 (save-excursion
22939 (goto-char beg)
22940 (when (or (looking-at org-outline-regexp)
22941 (re-search-forward org-outline-regexp-bol end t))
22942 (setq level (org-outline-level)))
22943 (goto-char end)
22944 (skip-chars-forward " \t\r\n\v\f")
22945 (not (or (eobp)
22946 (and (bolp) (looking-at-p org-outline-regexp)
22947 (<= (org-outline-level) level))))))))
22949 (define-key org-mode-map "\C-y" 'org-yank)
22951 (defun org-back-to-heading (&optional invisible-ok)
22952 "Call `outline-back-to-heading', but provide a better error message."
22953 (condition-case nil
22954 (outline-back-to-heading invisible-ok)
22955 (error (error "Before first headline at position %d in buffer %s"
22956 (point) (current-buffer)))))
22958 (defun org-before-first-heading-p ()
22959 "Before first heading?"
22960 (save-excursion
22961 (end-of-line)
22962 (null (re-search-backward org-outline-regexp-bol nil t))))
22964 (defun org-at-heading-p (&optional ignored)
22965 (outline-on-heading-p t))
22967 (defun org-in-commented-heading-p (&optional no-inheritance)
22968 "Non-nil if point is under a commented heading.
22969 This function also checks ancestors of the current headline,
22970 unless optional argument NO-INHERITANCE is non-nil."
22971 (cond
22972 ((org-before-first-heading-p) nil)
22973 ((let ((headline (nth 4 (org-heading-components))))
22974 (and headline
22975 (let ((case-fold-search nil))
22976 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22977 headline)))))
22978 (no-inheritance nil)
22980 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22982 (defun org-at-comment-p nil
22983 "Is cursor in a commented line?"
22984 (save-excursion
22985 (save-match-data
22986 (beginning-of-line)
22987 (looking-at "^[ \t]*# "))))
22989 (defun org-at-drawer-p nil
22990 "Is cursor at a drawer keyword?"
22991 (save-excursion
22992 (move-beginning-of-line 1)
22993 (looking-at org-drawer-regexp)))
22995 (defun org-at-block-p nil
22996 "Is cursor at a block keyword?"
22997 (save-excursion
22998 (move-beginning-of-line 1)
22999 (looking-at org-block-regexp)))
23001 (defun org-point-at-end-of-empty-headline ()
23002 "If point is at the end of an empty headline, return t, else nil.
23003 If the heading only contains a TODO keyword, it is still still considered
23004 empty."
23005 (let ((case-fold-search nil))
23006 (and (looking-at "[ \t]*$")
23007 org-todo-line-regexp
23008 (save-excursion
23009 (beginning-of-line)
23010 (looking-at org-todo-line-regexp)
23011 (string= (match-string 3) "")))))
23013 (defun org-at-heading-or-item-p ()
23014 (or (org-at-heading-p) (org-at-item-p)))
23016 (defun org-at-target-p ()
23017 (or (org-in-regexp org-radio-target-regexp)
23018 (org-in-regexp org-target-regexp)))
23019 ;; Compatibility alias with Org versions < 7.8.03
23020 (defalias 'org-on-target-p 'org-at-target-p)
23022 (defun org-up-heading-all (arg)
23023 "Move to the heading line of which the present line is a subheading.
23024 This function considers both visible and invisible heading lines.
23025 With argument, move up ARG levels."
23026 (outline-up-heading arg t))
23028 (defun org-up-heading-safe ()
23029 "Move to the heading line of which the present line is a subheading.
23030 This version will not throw an error. It will return the level of the
23031 headline found, or nil if no higher level is found.
23033 Also, this function will be a lot faster than `outline-up-heading',
23034 because it relies on stars being the outline starters. This can really
23035 make a significant difference in outlines with very many siblings."
23036 (when (ignore-errors (org-back-to-heading t))
23037 (let ((level-up (1- (funcall outline-level))))
23038 (and (> level-up 0)
23039 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23040 (funcall outline-level)))))
23042 (defun org-first-sibling-p ()
23043 "Is this heading the first child of its parents?"
23044 (interactive)
23045 (let ((re org-outline-regexp-bol)
23046 level l)
23047 (unless (org-at-heading-p t)
23048 (user-error "Not at a heading"))
23049 (setq level (funcall outline-level))
23050 (save-excursion
23051 (if (not (re-search-backward re nil t))
23053 (setq l (funcall outline-level))
23054 (< l level)))))
23056 (defun org-goto-sibling (&optional previous)
23057 "Goto the next sibling, even if it is invisible.
23058 When PREVIOUS is set, go to the previous sibling instead. Returns t
23059 when a sibling was found. When none is found, return nil and don't
23060 move point."
23061 (let ((fun (if previous 're-search-backward 're-search-forward))
23062 (pos (point))
23063 (re org-outline-regexp-bol)
23064 level l)
23065 (when (ignore-errors (org-back-to-heading t))
23066 (setq level (funcall outline-level))
23067 (catch 'exit
23068 (or previous (forward-char 1))
23069 (while (funcall fun re nil t)
23070 (setq l (funcall outline-level))
23071 (when (< l level) (goto-char pos) (throw 'exit nil))
23072 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23073 (goto-char pos)
23074 nil))))
23076 (defun org-show-siblings ()
23077 "Show all siblings of the current headline."
23078 (save-excursion
23079 (while (org-goto-sibling) (org-flag-heading nil)))
23080 (save-excursion
23081 (while (org-goto-sibling 'previous)
23082 (org-flag-heading nil))))
23084 (defun org-goto-first-child ()
23085 "Goto the first child, even if it is invisible.
23086 Return t when a child was found. Otherwise don't move point and
23087 return nil."
23088 (let (level (pos (point)) (re org-outline-regexp-bol))
23089 (when (ignore-errors (org-back-to-heading t))
23090 (setq level (outline-level))
23091 (forward-char 1)
23092 (if (and (re-search-forward re nil t) (> (outline-level) level))
23093 (progn (goto-char (match-beginning 0)) t)
23094 (goto-char pos) nil))))
23096 (defun org-show-hidden-entry ()
23097 "Show an entry where even the heading is hidden."
23098 (save-excursion
23099 (org-show-entry)))
23101 (defun org-flag-heading (flag &optional entry)
23102 "Flag the current heading. FLAG non-nil means make invisible.
23103 When ENTRY is non-nil, show the entire entry."
23104 (save-excursion
23105 (org-back-to-heading t)
23106 ;; Check if we should show the entire entry
23107 (if (not entry)
23108 (org-flag-region
23109 (line-end-position 0) (line-end-position) flag 'outline)
23110 (org-show-entry)
23111 (save-excursion
23112 (and (outline-next-heading)
23113 (org-flag-heading nil))))))
23115 (defun org-get-next-sibling ()
23116 "Move to next heading of the same level, and return point.
23117 If there is no such heading, return nil.
23118 This is like outline-next-sibling, but invisible headings are ok."
23119 (let ((level (funcall outline-level)))
23120 (outline-next-heading)
23121 (while (and (not (eobp)) (> (funcall outline-level) level))
23122 (outline-next-heading))
23123 (unless (or (eobp) (< (funcall outline-level) level))
23124 (point))))
23126 (defun org-get-last-sibling ()
23127 "Move to previous heading of the same level, and return point.
23128 If there is no such heading, return nil."
23129 (let ((opoint (point))
23130 (level (funcall outline-level)))
23131 (outline-previous-heading)
23132 (when (and (/= (point) opoint) (outline-on-heading-p t))
23133 (while (and (> (funcall outline-level) level)
23134 (not (bobp)))
23135 (outline-previous-heading))
23136 (unless (< (funcall outline-level) level)
23137 (point)))))
23139 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23140 "Goto to the end of a subtree."
23141 ;; This contains an exact copy of the original function, but it uses
23142 ;; `org-back-to-heading', to make it work also in invisible
23143 ;; trees. And is uses an invisible-ok argument.
23144 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23145 ;; Furthermore, when used inside Org, finding the end of a large subtree
23146 ;; with many children and grandchildren etc, this can be much faster
23147 ;; than the outline version.
23148 (org-back-to-heading invisible-ok)
23149 (let ((first t)
23150 (level (funcall outline-level)))
23151 (if (and (derived-mode-p 'org-mode) (< level 1000))
23152 ;; A true heading (not a plain list item), in Org
23153 ;; This means we can easily find the end by looking
23154 ;; only for the right number of stars. Using a regexp to do
23155 ;; this is so much faster than using a Lisp loop.
23156 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23157 (forward-char 1)
23158 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23159 ;; something else, do it the slow way
23160 (while (and (not (eobp))
23161 (or first (> (funcall outline-level) level)))
23162 (setq first nil)
23163 (outline-next-heading)))
23164 (unless to-heading
23165 (when (memq (preceding-char) '(?\n ?\^M))
23166 ;; Go to end of line before heading
23167 (forward-char -1)
23168 (when (memq (preceding-char) '(?\n ?\^M))
23169 ;; leave blank line before heading
23170 (forward-char -1)))))
23171 (point))
23173 (defun org-end-of-meta-data (&optional full)
23174 "Skip planning line and properties drawer in current entry.
23175 When optional argument FULL is non-nil, also skip empty lines,
23176 clocking lines and regular drawers at the beginning of the
23177 entry."
23178 (org-back-to-heading t)
23179 (forward-line)
23180 (when (looking-at-p org-planning-line-re) (forward-line))
23181 (when (looking-at org-property-drawer-re)
23182 (goto-char (match-end 0))
23183 (forward-line))
23184 (when (and full (not (org-at-heading-p)))
23185 (catch 'exit
23186 (let ((end (save-excursion (outline-next-heading) (point)))
23187 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23188 (while (not (eobp))
23189 (cond ((looking-at-p org-drawer-regexp)
23190 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23191 (forward-line)
23192 (throw 'exit t)))
23193 ((looking-at-p re) (forward-line))
23194 (t (throw 'exit t))))))))
23196 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23197 "Move forward to the ARG'th subheading at same level as this one.
23198 Stop at the first and last subheadings of a superior heading.
23199 Normally this only looks at visible headings, but when INVISIBLE-OK is
23200 non-nil it will also look at invisible ones."
23201 (interactive "p")
23202 (let ((backward? (and arg (< arg 0))))
23203 (if (org-before-first-heading-p)
23204 (if backward? (goto-char (point-min)) (outline-next-heading))
23205 (org-back-to-heading invisible-ok)
23206 (unless backward? (end-of-line)) ;do not match current headline
23207 (let ((level (- (match-end 0) (match-beginning 0) 1))
23208 (f (if backward? #'re-search-backward #'re-search-forward))
23209 (count (if arg (abs arg) 1))
23210 (result (point)))
23211 (while (and (> count 0)
23212 (funcall f org-outline-regexp-bol nil 'move))
23213 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23214 (cond ((< l level) (setq count 0))
23215 ((and (= l level)
23216 (or invisible-ok
23217 (not (org-invisible-p
23218 (line-beginning-position)))))
23219 (cl-decf count)
23220 (when (= l level) (setq result (point)))))))
23221 (goto-char result))
23222 (beginning-of-line))))
23224 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23225 "Move backward to the ARG'th subheading at same level as this one.
23226 Stop at the first and last subheadings of a superior heading."
23227 (interactive "p")
23228 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23230 (defun org-next-visible-heading (arg)
23231 "Move to the next visible heading.
23233 This function wraps `outline-next-visible-heading' with
23234 `org-with-limited-levels' in order to skip over inline tasks and
23235 respect customization of `org-odd-levels-only'."
23236 (interactive "p")
23237 (org-with-limited-levels
23238 (outline-next-visible-heading arg)))
23240 (defun org-previous-visible-heading (arg)
23241 "Move to the previous visible heading.
23243 This function wraps `outline-previous-visible-heading' with
23244 `org-with-limited-levels' in order to skip over inline tasks and
23245 respect customization of `org-odd-levels-only'."
23246 (interactive "p")
23247 (org-with-limited-levels
23248 (outline-previous-visible-heading arg)))
23250 (defun org-forward-paragraph ()
23251 "Move forward to beginning of next paragraph or equivalent.
23253 The function moves point to the beginning of the next visible
23254 structural element, which can be a paragraph, a table, a list
23255 item, etc. It also provides some special moves for convenience:
23257 - On an affiliated keyword, jump to the beginning of the
23258 relative element.
23259 - On an item or a footnote definition, move to the second
23260 element inside, if any.
23261 - On a table or a property drawer, jump after it.
23262 - On a verse or source block, stop after blank lines."
23263 (interactive)
23264 (unless (eobp)
23265 (let* ((deactivate-mark nil)
23266 (element (org-element-at-point))
23267 (type (org-element-type element))
23268 (post-affiliated (org-element-property :post-affiliated element))
23269 (contents-begin (org-element-property :contents-begin element))
23270 (contents-end (org-element-property :contents-end element))
23271 (end (let ((end (org-element-property :end element)) (parent element))
23272 (while (and (setq parent (org-element-property :parent parent))
23273 (= (org-element-property :contents-end parent) end))
23274 (setq end (org-element-property :end parent)))
23275 end)))
23276 (cond ((not element)
23277 (skip-chars-forward " \r\t\n")
23278 (or (eobp) (beginning-of-line)))
23279 ;; On affiliated keywords, move to element's beginning.
23280 ((< (point) post-affiliated)
23281 (goto-char post-affiliated))
23282 ;; At a table row, move to the end of the table. Similarly,
23283 ;; at a node property, move to the end of the property
23284 ;; drawer.
23285 ((memq type '(node-property table-row))
23286 (goto-char (org-element-property
23287 :end (org-element-property :parent element))))
23288 ((memq type '(property-drawer table)) (goto-char end))
23289 ;; Consider blank lines as separators in verse and source
23290 ;; blocks to ease editing.
23291 ((memq type '(src-block verse-block))
23292 (when (eq type 'src-block)
23293 (setq contents-end
23294 (save-excursion (goto-char end)
23295 (skip-chars-backward " \r\t\n")
23296 (line-beginning-position))))
23297 (beginning-of-line)
23298 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23299 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23300 (goto-char end)
23301 (skip-chars-forward " \r\t\n")
23302 (if (= (point) contents-end) (goto-char end)
23303 (beginning-of-line))))
23304 ;; With no contents, just skip element.
23305 ((not contents-begin) (goto-char end))
23306 ;; If contents are invisible, skip the element altogether.
23307 ((org-invisible-p (line-end-position))
23308 (cl-case type
23309 (headline
23310 (org-with-limited-levels (outline-next-visible-heading 1)))
23311 ;; At a plain list, make sure we move to the next item
23312 ;; instead of skipping the whole list.
23313 (plain-list (forward-char)
23314 (org-forward-paragraph))
23315 (otherwise (goto-char end))))
23316 ((>= (point) contents-end) (goto-char end))
23317 ((>= (point) contents-begin)
23318 ;; This can only happen on paragraphs and plain lists.
23319 (cl-case type
23320 (paragraph (goto-char end))
23321 ;; At a plain list, try to move to second element in
23322 ;; first item, if possible.
23323 (plain-list (end-of-line)
23324 (org-forward-paragraph))))
23325 ;; When contents start on the middle of a line (e.g. in
23326 ;; items and footnote definitions), try to reach first
23327 ;; element starting after current line.
23328 ((> (line-end-position) contents-begin)
23329 (end-of-line)
23330 (org-forward-paragraph))
23331 (t (goto-char contents-begin))))))
23333 (defun org-backward-paragraph ()
23334 "Move backward to start of previous paragraph or equivalent.
23336 The function moves point to the beginning of the current
23337 structural element, which can be a paragraph, a table, a list
23338 item, etc., or to the beginning of the previous visible one if
23339 point is already there. It also provides some special moves for
23340 convenience:
23342 - On an affiliated keyword, jump to the first one.
23343 - On a table or a property drawer, move to its beginning.
23344 - On comment, example, export, src and verse blocks, stop
23345 before blank lines."
23346 (interactive)
23347 (unless (bobp)
23348 (let* ((deactivate-mark nil)
23349 (element (org-element-at-point))
23350 (type (org-element-type element))
23351 (contents-end (org-element-property :contents-end element))
23352 (post-affiliated (org-element-property :post-affiliated element))
23353 (begin (org-element-property :begin element))
23354 (special? ;blocks handled specially
23355 (memq type '(comment-block example-block export-block src-block
23356 verse-block)))
23357 (contents-begin
23358 (if special?
23359 ;; These types have no proper contents. Fake line
23360 ;; below the block opening line as contents beginning.
23361 (save-excursion (goto-char begin) (line-beginning-position 2))
23362 (org-element-property :contents-begin element))))
23363 (cond
23364 ((not element) (goto-char (point-min)))
23365 ((= (point) begin)
23366 (backward-char)
23367 (org-backward-paragraph))
23368 ((<= (point) post-affiliated) (goto-char begin))
23369 ;; Special behavior: on a table or a property drawer, move to
23370 ;; its beginning.
23371 ((memq type '(node-property table-row))
23372 (goto-char (org-element-property
23373 :post-affiliated (org-element-property :parent element))))
23374 (special?
23375 (if (<= (point) contents-begin) (goto-char post-affiliated)
23376 ;; Inside a verse block, see blank lines as paragraph
23377 ;; separators.
23378 (let ((origin (point)))
23379 (skip-chars-backward " \r\t\n" contents-begin)
23380 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23381 (skip-chars-forward " \r\t\n" origin)
23382 (if (= (point) origin) (goto-char contents-begin)
23383 (beginning-of-line))))))
23384 ((eq type 'paragraph) (goto-char contents-begin)
23385 ;; When at first paragraph in an item or a footnote definition,
23386 ;; move directly to beginning of line.
23387 (let ((parent-contents
23388 (org-element-property
23389 :contents-begin (org-element-property :parent element))))
23390 (when (and parent-contents (= parent-contents contents-begin))
23391 (beginning-of-line))))
23392 ;; At the end of a greater element, move to the beginning of
23393 ;; the last element within.
23394 ((and contents-end (>= (point) contents-end))
23395 (goto-char (1- contents-end))
23396 (org-backward-paragraph))
23397 (t (goto-char (or post-affiliated begin))))
23398 ;; Ensure we never leave point invisible.
23399 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23401 (defun org-forward-element ()
23402 "Move forward by one element.
23403 Move to the next element at the same level, when possible."
23404 (interactive)
23405 (cond ((eobp) (user-error "Cannot move further down"))
23406 ((org-with-limited-levels (org-at-heading-p))
23407 (let ((origin (point)))
23408 (goto-char (org-end-of-subtree nil t))
23409 (unless (org-with-limited-levels (org-at-heading-p))
23410 (goto-char origin)
23411 (user-error "Cannot move further down"))))
23413 (let* ((elem (org-element-at-point))
23414 (end (org-element-property :end elem))
23415 (parent (org-element-property :parent elem)))
23416 (cond ((and parent (= (org-element-property :contents-end parent) end))
23417 (goto-char (org-element-property :end parent)))
23418 ((integer-or-marker-p end) (goto-char end))
23419 (t (message "No element at point")))))))
23421 (defun org-backward-element ()
23422 "Move backward by one element.
23423 Move to the previous element at the same level, when possible."
23424 (interactive)
23425 (cond ((bobp) (user-error "Cannot move further up"))
23426 ((org-with-limited-levels (org-at-heading-p))
23427 ;; At a headline, move to the previous one, if any, or stay
23428 ;; here.
23429 (let ((origin (point)))
23430 (org-with-limited-levels (org-backward-heading-same-level 1))
23431 ;; When current headline has no sibling above, move to its
23432 ;; parent.
23433 (when (= (point) origin)
23434 (or (org-with-limited-levels (org-up-heading-safe))
23435 (progn (goto-char origin)
23436 (user-error "Cannot move further up"))))))
23438 (let* ((elem (org-element-at-point))
23439 (beg (org-element-property :begin elem)))
23440 (cond
23441 ;; Move to beginning of current element if point isn't
23442 ;; there already.
23443 ((null beg) (message "No element at point"))
23444 ((/= (point) beg) (goto-char beg))
23445 (t (goto-char beg)
23446 (skip-chars-backward " \r\t\n")
23447 (unless (bobp)
23448 (let ((prev (org-element-at-point)))
23449 (goto-char (org-element-property :begin prev))
23450 (while (and (setq prev (org-element-property :parent prev))
23451 (<= (org-element-property :end prev) beg))
23452 (goto-char (org-element-property :begin prev)))))))))))
23454 (defun org-up-element ()
23455 "Move to upper element."
23456 (interactive)
23457 (if (org-with-limited-levels (org-at-heading-p))
23458 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23459 (let* ((elem (org-element-at-point))
23460 (parent (org-element-property :parent elem)))
23461 (if parent (goto-char (org-element-property :begin parent))
23462 (if (org-with-limited-levels (org-before-first-heading-p))
23463 (user-error "No surrounding element")
23464 (org-with-limited-levels (org-back-to-heading)))))))
23466 (defun org-down-element ()
23467 "Move to inner element."
23468 (interactive)
23469 (let ((element (org-element-at-point)))
23470 (cond
23471 ((memq (org-element-type element) '(plain-list table))
23472 (goto-char (org-element-property :contents-begin element))
23473 (forward-char))
23474 ((memq (org-element-type element) org-element-greater-elements)
23475 ;; If contents are hidden, first disclose them.
23476 (when (org-invisible-p (line-end-position)) (org-cycle))
23477 (goto-char (or (org-element-property :contents-begin element)
23478 (user-error "No content for this element"))))
23479 (t (user-error "No inner element")))))
23481 (defun org-drag-element-backward ()
23482 "Move backward element at point."
23483 (interactive)
23484 (let ((elem (or (org-element-at-point)
23485 (user-error "No element at point"))))
23486 (if (eq (org-element-type elem) 'headline)
23487 ;; Preserve point when moving a whole tree, even if point was
23488 ;; on blank lines below the headline.
23489 (let ((offset (skip-chars-backward " \t\n")))
23490 (unwind-protect (org-move-subtree-up)
23491 (forward-char (- offset))))
23492 (let ((prev-elem
23493 (save-excursion
23494 (goto-char (org-element-property :begin elem))
23495 (skip-chars-backward " \r\t\n")
23496 (unless (bobp)
23497 (let* ((beg (org-element-property :begin elem))
23498 (prev (org-element-at-point))
23499 (up prev))
23500 (while (and (setq up (org-element-property :parent up))
23501 (<= (org-element-property :end up) beg))
23502 (setq prev up))
23503 prev)))))
23504 ;; Error out if no previous element or previous element is
23505 ;; a parent of the current one.
23506 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23507 (user-error "Cannot drag element backward")
23508 (let ((pos (point)))
23509 (org-element-swap-A-B prev-elem elem)
23510 (goto-char (+ (org-element-property :begin prev-elem)
23511 (- pos (org-element-property :begin elem))))))))))
23513 (defun org-drag-element-forward ()
23514 "Move forward element at point."
23515 (interactive)
23516 (let* ((pos (point))
23517 (elem (or (org-element-at-point)
23518 (user-error "No element at point"))))
23519 (when (= (point-max) (org-element-property :end elem))
23520 (user-error "Cannot drag element forward"))
23521 (goto-char (org-element-property :end elem))
23522 (let ((next-elem (org-element-at-point)))
23523 (when (or (org-element-nested-p elem next-elem)
23524 (and (eq (org-element-type next-elem) 'headline)
23525 (not (eq (org-element-type elem) 'headline))))
23526 (goto-char pos)
23527 (user-error "Cannot drag element forward"))
23528 ;; Compute new position of point: it's shifted by NEXT-ELEM
23529 ;; body's length (without final blanks) and by the length of
23530 ;; blanks between ELEM and NEXT-ELEM.
23531 (let ((size-next (- (save-excursion
23532 (goto-char (org-element-property :end next-elem))
23533 (skip-chars-backward " \r\t\n")
23534 (forward-line)
23535 ;; Small correction if buffer doesn't end
23536 ;; with a newline character.
23537 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23538 (org-element-property :begin next-elem)))
23539 (size-blank (- (org-element-property :end elem)
23540 (save-excursion
23541 (goto-char (org-element-property :end elem))
23542 (skip-chars-backward " \r\t\n")
23543 (forward-line)
23544 (point)))))
23545 (org-element-swap-A-B elem next-elem)
23546 (goto-char (+ pos size-next size-blank))))))
23548 (defun org-drag-line-forward (arg)
23549 "Drag the line at point ARG lines forward."
23550 (interactive "p")
23551 (dotimes (_ (abs arg))
23552 (let ((c (current-column)))
23553 (if (< 0 arg)
23554 (progn
23555 (beginning-of-line 2)
23556 (transpose-lines 1)
23557 (beginning-of-line 0))
23558 (transpose-lines 1)
23559 (beginning-of-line -1))
23560 (org-move-to-column c))))
23562 (defun org-drag-line-backward (arg)
23563 "Drag the line at point ARG lines backward."
23564 (interactive "p")
23565 (org-drag-line-forward (- arg)))
23567 (defun org-mark-element ()
23568 "Put point at beginning of this element, mark at end.
23570 Interactively, if this command is repeated or (in Transient Mark
23571 mode) if the mark is active, it marks the next element after the
23572 ones already marked."
23573 (interactive)
23574 (let (deactivate-mark)
23575 (if (and (called-interactively-p 'any)
23576 (or (and (eq last-command this-command) (mark t))
23577 (and transient-mark-mode mark-active)))
23578 (set-mark
23579 (save-excursion
23580 (goto-char (mark))
23581 (goto-char (org-element-property :end (org-element-at-point)))))
23582 (let ((element (org-element-at-point)))
23583 (end-of-line)
23584 (push-mark (org-element-property :end element) t t)
23585 (goto-char (org-element-property :begin element))))))
23587 (defun org-narrow-to-element ()
23588 "Narrow buffer to current element."
23589 (interactive)
23590 (let ((elem (org-element-at-point)))
23591 (cond
23592 ((eq (car elem) 'headline)
23593 (narrow-to-region
23594 (org-element-property :begin elem)
23595 (org-element-property :end elem)))
23596 ((memq (car elem) org-element-greater-elements)
23597 (narrow-to-region
23598 (org-element-property :contents-begin elem)
23599 (org-element-property :contents-end elem)))
23601 (narrow-to-region
23602 (org-element-property :begin elem)
23603 (org-element-property :end elem))))))
23605 (defun org-transpose-element ()
23606 "Transpose current and previous elements, keeping blank lines between.
23607 Point is moved after both elements."
23608 (interactive)
23609 (org-skip-whitespace)
23610 (let ((end (org-element-property :end (org-element-at-point))))
23611 (org-drag-element-backward)
23612 (goto-char end)))
23614 (defun org-unindent-buffer ()
23615 "Un-indent the visible part of the buffer.
23616 Relative indentation (between items, inside blocks, etc.) isn't
23617 modified."
23618 (interactive)
23619 (unless (eq major-mode 'org-mode)
23620 (user-error "Cannot un-indent a buffer not in Org mode"))
23621 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23622 (unindent-tree
23623 (lambda (contents)
23624 (dolist (element (reverse contents))
23625 (if (memq (org-element-type element) '(headline section))
23626 (funcall unindent-tree (org-element-contents element))
23627 (save-excursion
23628 (save-restriction
23629 (narrow-to-region
23630 (org-element-property :begin element)
23631 (org-element-property :end element))
23632 (org-do-remove-indentation))))))))
23633 (funcall unindent-tree (org-element-contents parse-tree))))
23635 (defun org-make-options-regexp (kwds &optional extra)
23636 "Make a regular expression for keyword lines.
23637 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23638 when non-nil, is a regexp matching keywords names."
23639 (concat "^[ \t]*#\\+\\("
23640 (regexp-opt kwds)
23641 (and extra (concat (and kwds "\\|") extra))
23642 "\\):[ \t]*\\(.*\\)"))
23645 ;;; Finish up
23647 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23648 (lambda () (add-hook 'change-major-mode-hook
23649 'org-show-all 'append 'local)))
23651 (provide 'org)
23653 (run-hooks 'org-load-hook)
23655 ;;; org.el ends here