Allow org-file-contents to fetch file contents from a URL
[org-mode.git] / lisp / org.el
blob191990db75b04d4743f2a1649380bbda6a0ce0b8
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-2017 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: http://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 <http://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 ;; http://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 ;; http://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'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function
133 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
134 (declare-function org-element-at-point "org-element" ())
135 (declare-function org-element-cache-refresh "org-element" (pos))
136 (declare-function org-element-cache-reset "org-element" (&optional all))
137 (declare-function org-element-contents "org-element" (element))
138 (declare-function org-element-context "org-element" (&optional element))
139 (declare-function org-element-copy "org-element" (datum))
140 (declare-function org-element-interpret-data "org-element" (data))
141 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
142 (declare-function org-element-link-parser "org-element" ())
143 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
144 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-put-property "org-element" (element property value))
147 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
148 (declare-function org-element-type "org-element" (element))
149 (declare-function org-element-update-syntax "org-element" ())
150 (declare-function org-id-find-id-file "org-id" (id))
151 (declare-function org-id-get-create "org-id" (&optional force))
152 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
153 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
154 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
155 (declare-function org-plot/gnuplot "org-plot" (&optional params))
156 (declare-function org-table-align "org-table" ())
157 (declare-function org-table-begin "org-table" (&optional table-type))
158 (declare-function org-table-beginning-of-field "org-table" (&optional n))
159 (declare-function org-table-blank-field "org-table" ())
160 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
161 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
162 (declare-function org-table-cut-region "org-table" (beg end))
163 (declare-function org-table-edit-field "org-table" (arg))
164 (declare-function org-table-end "org-table" (&optional table-type))
165 (declare-function org-table-end-of-field "org-table" (&optional n))
166 (declare-function org-table-insert-row "org-table" (&optional arg))
167 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
168 (declare-function org-table-maybe-eval-formula "org-table" ())
169 (declare-function org-table-maybe-recalculate-line "org-table" ())
170 (declare-function org-table-next-row "org-table" ())
171 (declare-function org-table-paste-rectangle "org-table" ())
172 (declare-function org-table-recalculate "org-table" (&optional all noalign))
173 (declare-function
174 org-table-sort-lines "org-table"
175 (&optional with-case sorting-type getkey-func compare-func interactive?))
176 (declare-function org-table-wrap-region "org-table" (arg))
177 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
178 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
179 (declare-function orgtbl-mode "org-table" (&optional arg))
180 (declare-function org-export-get-backend "ox" (name))
181 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
182 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
184 (defvar ffap-url-regexp) ;Silence byte-compiler
186 (defsubst org-uniquify (list)
187 "Non-destructively remove duplicate elements from LIST."
188 (let ((res (copy-sequence list))) (delete-dups res)))
190 (defsubst org-get-at-bol (property)
191 "Get text property PROPERTY at the beginning of line."
192 (get-text-property (point-at-bol) property))
194 (defsubst org-trim (s &optional keep-lead)
195 "Remove whitespace at the beginning and the end of string S.
196 When optional argument KEEP-LEAD is non-nil, removing blank lines
197 at the beginning of the string does not affect leading indentation."
198 (replace-regexp-in-string
199 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
200 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
202 ;; load languages based on value of `org-babel-load-languages'
203 (defvar org-babel-load-languages)
205 ;;;###autoload
206 (defun org-babel-do-load-languages (sym value)
207 "Load the languages defined in `org-babel-load-languages'."
208 (set-default sym value)
209 (dolist (pair org-babel-load-languages)
210 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
211 (if active
212 (require (intern (concat "ob-" lang)))
213 (funcall 'fmakunbound
214 (intern (concat "org-babel-execute:" lang)))
215 (funcall 'fmakunbound
216 (intern (concat "org-babel-expand-body:" lang)))))))
218 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
219 ;;;###autoload
220 (defun org-babel-load-file (file &optional compile)
221 "Load Emacs Lisp source code blocks in the Org FILE.
222 This function exports the source code using `org-babel-tangle'
223 and then loads the resulting file using `load-file'. With prefix
224 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
225 file to byte-code before it is loaded."
226 (interactive "fFile to load: \nP")
227 (let* ((age (lambda (file)
228 (float-time
229 (time-subtract (current-time)
230 (nth 5 (or (file-attributes (file-truename file))
231 (file-attributes file)))))))
232 (base-name (file-name-sans-extension file))
233 (exported-file (concat base-name ".el")))
234 ;; tangle if the Org file is newer than the elisp file
235 (unless (and (file-exists-p exported-file)
236 (> (funcall age file) (funcall age exported-file)))
237 ;; Tangle-file traversal returns reversed list of tangled files
238 ;; and we want to evaluate the first target.
239 (setq exported-file
240 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
241 (message "%s %s"
242 (if compile
243 (progn (byte-compile-file exported-file 'load)
244 "Compiled and loaded")
245 (progn (load-file exported-file) "Loaded"))
246 exported-file)))
248 (defcustom org-babel-load-languages '((emacs-lisp . t))
249 "Languages which can be evaluated in Org buffers.
250 This list can be used to load support for any of the languages
251 below, note that each language will depend on a different set of
252 system executables and/or Emacs modes. When a language is
253 \"loaded\", then code blocks in that language can be evaluated
254 with `org-babel-execute-src-block' bound by default to C-c
255 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
256 be set to remove code block evaluation from the C-c C-c
257 keybinding. By default only Emacs Lisp (which has no
258 requirements) is loaded."
259 :group 'org-babel
260 :set 'org-babel-do-load-languages
261 :version "24.1"
262 :type '(alist :tag "Babel Languages"
263 :key-type
264 (choice
265 (const :tag "Awk" awk)
266 (const :tag "C" C)
267 (const :tag "R" R)
268 (const :tag "Asymptote" asymptote)
269 (const :tag "Calc" calc)
270 (const :tag "Clojure" clojure)
271 (const :tag "CSS" css)
272 (const :tag "Ditaa" ditaa)
273 (const :tag "Dot" dot)
274 (const :tag "Emacs Lisp" emacs-lisp)
275 (const :tag "Forth" forth)
276 (const :tag "Fortran" fortran)
277 (const :tag "Gnuplot" gnuplot)
278 (const :tag "Haskell" haskell)
279 (const :tag "hledger" hledger)
280 (const :tag "IO" io)
281 (const :tag "J" J)
282 (const :tag "Java" java)
283 (const :tag "Javascript" js)
284 (const :tag "LaTeX" latex)
285 (const :tag "Ledger" ledger)
286 (const :tag "Lilypond" lilypond)
287 (const :tag "Lisp" lisp)
288 (const :tag "Makefile" makefile)
289 (const :tag "Maxima" maxima)
290 (const :tag "Matlab" matlab)
291 (const :tag "Mscgen" mscgen)
292 (const :tag "Ocaml" ocaml)
293 (const :tag "Octave" octave)
294 (const :tag "Org" org)
295 (const :tag "Perl" perl)
296 (const :tag "Pico Lisp" picolisp)
297 (const :tag "PlantUML" plantuml)
298 (const :tag "Python" python)
299 (const :tag "Ruby" ruby)
300 (const :tag "Sass" sass)
301 (const :tag "Scala" scala)
302 (const :tag "Scheme" scheme)
303 (const :tag "Screen" screen)
304 (const :tag "Shell Script" shell)
305 (const :tag "Shen" shen)
306 (const :tag "Sql" sql)
307 (const :tag "Sqlite" sqlite)
308 (const :tag "Stan" stan)
309 (const :tag "ebnf2ps" ebnf2ps))
310 :value-type (boolean :tag "Activate" :value t)))
312 ;;;; Customization variables
313 (defcustom org-clone-delete-id nil
314 "Remove ID property of clones of a subtree.
315 When non-nil, clones of a subtree don't inherit the ID property.
316 Otherwise they inherit the ID property with a new unique
317 identifier."
318 :type 'boolean
319 :version "24.1"
320 :group 'org-id)
322 ;;; Version
323 (org-check-version)
325 ;;;###autoload
326 (defun org-version (&optional here full message)
327 "Show the Org version.
328 Interactively, or when MESSAGE is non-nil, show it in echo area.
329 With prefix argument, or when HERE is non-nil, insert it at point.
330 In non-interactive uses, a reduced version string is output unless
331 FULL is given."
332 (interactive (list current-prefix-arg t (not current-prefix-arg)))
333 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
334 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
335 (load-suffixes (list ".el"))
336 (org-install-dir
337 (ignore-errors (org-find-library-dir "org-loaddefs"))))
338 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
339 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
340 (let* ((load-suffixes save-load-suffixes)
341 (release (org-release))
342 (git-version (org-git-version))
343 (version (format "Org mode version %s (%s @ %s)"
344 release
345 git-version
346 (if org-install-dir
347 (if (string= org-dir org-install-dir)
348 org-install-dir
349 (concat "mixed installation! "
350 org-install-dir
351 " and "
352 org-dir))
353 "org-loaddefs.el can not be found!")))
354 (version1 (if full version release)))
355 (when here (insert version1))
356 (when message (message "%s" version1))
357 version1)))
359 (defconst org-version (org-version))
362 ;;; Syntax Constants
364 ;;;; Block
366 (defconst org-block-regexp
367 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
368 "Regular expression for hiding blocks.")
370 (defconst org-dblock-start-re
371 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
372 "Matches the start line of a dynamic block, with parameters.")
374 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
375 "Matches the end of a dynamic block.")
377 ;;;; Clock and Planning
379 (defconst org-clock-string "CLOCK:"
380 "String used as prefix for timestamps clocking work hours on an item.")
382 (defvar org-closed-string "CLOSED:"
383 "String used as the prefix for timestamps logging closing a TODO entry.")
385 (defvar org-deadline-string "DEADLINE:"
386 "String to mark deadline entries.
387 \\<org-mode-map>
388 A deadline is this string, followed by a time stamp. It must be
389 a word, terminated by a colon. You can insert a schedule keyword
390 and a timestamp with `\\[org-deadline]'.")
392 (defvar org-scheduled-string "SCHEDULED:"
393 "String to mark scheduled TODO entries.
394 \\<org-mode-map>
395 A schedule is this string, followed by a time stamp. It must be
396 a word, terminated by a colon. You can insert a schedule keyword
397 and a timestamp with `\\[org-schedule]'.")
399 (defconst org-ds-keyword-length
400 (+ 2
401 (apply #'max
402 (mapcar #'length
403 (list org-deadline-string org-scheduled-string
404 org-clock-string org-closed-string))))
405 "Maximum length of the DEADLINE and SCHEDULED keywords.")
407 (defconst org-planning-line-re
408 (concat "^[ \t]*"
409 (regexp-opt
410 (list org-closed-string org-deadline-string org-scheduled-string)
412 "Matches a line with planning info.
413 Matched keyword is in group 1.")
415 (defconst org-clock-line-re
416 (concat "^[ \t]*" org-clock-string)
417 "Matches a line with clock info.")
419 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
420 "Matches the DEADLINE keyword.")
422 (defconst org-deadline-time-regexp
423 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
424 "Matches the DEADLINE keyword together with a time stamp.")
426 (defconst org-deadline-time-hour-regexp
427 (concat "\\<" org-deadline-string
428 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
429 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
431 (defconst org-deadline-line-regexp
432 (concat "\\<\\(" org-deadline-string "\\).*")
433 "Matches the DEADLINE keyword and the rest of the line.")
435 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
436 "Matches the SCHEDULED keyword.")
438 (defconst org-scheduled-time-regexp
439 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
440 "Matches the SCHEDULED keyword together with a time stamp.")
442 (defconst org-scheduled-time-hour-regexp
443 (concat "\\<" org-scheduled-string
444 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
445 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
447 (defconst org-closed-time-regexp
448 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
449 "Matches the CLOSED keyword together with a time stamp.")
451 (defconst org-keyword-time-regexp
452 (concat "\\<"
453 (regexp-opt
454 (list org-scheduled-string org-deadline-string org-closed-string
455 org-clock-string)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 4 keywords, together with the time stamp.")
460 (defconst org-keyword-time-not-clock-regexp
461 (concat
462 "\\<"
463 (regexp-opt
464 (list org-scheduled-string org-deadline-string org-closed-string) t)
465 " *[[<]\\([^]>]+\\)[]>]")
466 "Matches any of the 3 keywords, together with the time stamp.")
468 (defconst org-maybe-keyword-time-regexp
469 (concat "\\(\\<"
470 (regexp-opt
471 (list org-scheduled-string org-deadline-string org-closed-string
472 org-clock-string)
474 "\\)?"
475 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
476 "\\|"
477 "<%%([^\r\n>]*>\\)")
478 "Matches a timestamp, possibly preceded by a keyword.")
480 (defconst org-all-time-keywords
481 (mapcar (lambda (w) (substring w 0 -1))
482 (list org-scheduled-string org-deadline-string
483 org-clock-string org-closed-string))
484 "List of time keywords.")
486 ;;;; Drawer
488 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
489 "Matches first or last line of a hidden block.
490 Group 1 contains drawer's name or \"END\".")
492 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
493 "Regular expression matching the first line of a property drawer.")
495 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
496 "Regular expression matching the last line of a property drawer.")
498 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
499 "Regular expression matching the first line of a clock drawer.")
501 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
502 "Regular expression matching the last line of a clock drawer.")
504 (defconst org-property-drawer-re
505 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
506 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
507 "[ \t]*:END:[ \t]*$")
508 "Matches an entire property drawer.")
510 (defconst org-clock-drawer-re
511 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
512 org-clock-drawer-end-re "\\)\n?")
513 "Matches an entire clock drawer.")
515 ;;;; Headline
517 (defconst org-heading-keyword-regexp-format
518 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
519 "Printf format for a regexp matching a headline with some keyword.
520 This regexp will match the headline of any node which has the
521 exact keyword that is put into the format. The keyword isn't in
522 any group by default, but the stars and the body are.")
524 (defconst org-heading-keyword-maybe-regexp-format
525 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
526 "Printf format for a regexp matching a headline, possibly with some keyword.
527 This regexp can match any headline with the specified keyword, or
528 without a keyword. The keyword isn't in any group by default,
529 but the stars and the body are.")
531 (defconst org-archive-tag "ARCHIVE"
532 "The tag that marks a subtree as archived.
533 An archived subtree does not open during visibility cycling, and does
534 not contribute to the agenda listings.")
536 (eval-and-compile
537 (defconst org-comment-string "COMMENT"
538 "Entries starting with this keyword will never be exported.
539 \\<org-mode-map>
540 An entry can be toggled between COMMENT and normal with
541 `\\[org-toggle-comment]'."))
544 ;;;; LaTeX Environments and Fragments
546 (defconst org-latex-regexps
547 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
548 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
549 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
550 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
551 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
552 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
553 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
554 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
555 "Regular expressions for matching embedded LaTeX.")
557 ;;;; Node Property
559 (defconst org-effort-property "Effort"
560 "The property that is being used to keep track of effort estimates.
561 Effort estimates given in this property need to have the format H:MM.")
563 ;;;; Table
565 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
566 "Detect an org-type or table-type table.")
568 (defconst org-table-line-regexp "^[ \t]*|"
569 "Detect an org-type table line.")
571 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
572 "Detect an org-type table line.")
574 (defconst org-table-hline-regexp "^[ \t]*|-"
575 "Detect an org-type table hline.")
577 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
578 "Detect a table-type table hline.")
580 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
581 "Detect the first line outside a table when searching from within it.
582 This works for both table types.")
584 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
585 "Detect a #+TBLFM line.")
587 ;;;; Timestamp
589 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
590 "Regular expression for fast time stamp matching.")
592 (defconst org-ts-regexp-inactive
593 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
594 "Regular expression for fast inactive time stamp matching.")
596 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
597 "Regular expression for fast time stamp matching.")
599 (defconst org-ts-regexp0
600 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
601 "Regular expression matching time strings for analysis.
602 This one does not require the space after the date, so it can be used
603 on a string that terminates immediately after the date.")
605 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
606 "Regular expression matching time strings for analysis.")
608 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
609 "Regular expression matching time stamps, with groups.")
611 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
612 "Regular expression matching time stamps (also [..]), with groups.")
614 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
615 "Regular expression matching a time stamp range.")
617 (defconst org-tr-regexp-both
618 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
619 "Regular expression matching a time stamp range.")
621 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
622 org-ts-regexp "\\)?")
623 "Regular expression matching a time stamp or time stamp range.")
625 (defconst org-tsr-regexp-both
626 (concat org-ts-regexp-both "\\(--?-?"
627 org-ts-regexp-both "\\)?")
628 "Regular expression matching a time stamp or time stamp range.
629 The time stamps may be either active or inactive.")
631 (defconst org-repeat-re
632 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
633 "Regular expression for specifying repeated events.
634 After a match, group 1 contains the repeat expression.")
636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
637 "Formats for `format-time-string' which are used for time stamps.")
640 ;;; The custom variables
642 (defgroup org nil
643 "Outline-based notes management and organizer."
644 :tag "Org"
645 :group 'outlines
646 :group 'calendar)
648 (defcustom org-mode-hook nil
649 "Mode hook for Org mode, run after the mode was turned on."
650 :group 'org
651 :type 'hook)
653 (defcustom org-load-hook nil
654 "Hook that is run after org.el has been loaded."
655 :group 'org
656 :type 'hook)
658 (defcustom org-log-buffer-setup-hook nil
659 "Hook that is run after an Org log buffer is created."
660 :group 'org
661 :version "24.1"
662 :type 'hook)
664 (defvar org-modules) ; defined below
665 (defvar org-modules-loaded nil
666 "Have the modules been loaded already?")
668 (defun org-load-modules-maybe (&optional force)
669 "Load all extensions listed in `org-modules'."
670 (when (or force (not org-modules-loaded))
671 (dolist (ext org-modules)
672 (condition-case nil (require ext)
673 (error (message "Problems while trying to load feature `%s'" ext))))
674 (setq org-modules-loaded t)))
676 (defun org-set-modules (var value)
677 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
678 (set var value)
679 (when (featurep 'org)
680 (org-load-modules-maybe 'force)
681 (org-element-cache-reset 'all)))
683 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
684 "Modules that should always be loaded together with org.el.
686 If a description starts with <C>, the file is not part of Emacs
687 and loading it will require that you have downloaded and properly
688 installed the Org mode distribution.
690 You can also use this system to load external packages (i.e. neither Org
691 core modules, nor modules from the CONTRIB directory). Just add symbols
692 to the end of the list. If the package is called org-xyz.el, then you need
693 to add the symbol `xyz', and the package must have a call to:
695 (provide \\='org-xyz)
697 For export specific modules, see also `org-export-backends'."
698 :group 'org
699 :set 'org-set-modules
700 :version "24.4"
701 :package-version '(Org . "8.0")
702 :type
703 '(set :greedy t
704 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
705 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
706 (const :tag " crypt: Encryption of subtrees" org-crypt)
707 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
708 (const :tag " docview: Links to doc-view buffers" org-docview)
709 (const :tag " eww: Store link to url of eww" org-eww)
710 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
711 (const :tag " habit: Track your consistency with habits" org-habit)
712 (const :tag " id: Global IDs for identifying entries" org-id)
713 (const :tag " info: Links to Info nodes" org-info)
714 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
715 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
716 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
717 (const :tag " mouse: Additional mouse support" org-mouse)
718 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
719 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
720 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
722 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
723 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
724 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
725 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
726 (const :tag "C collector: Collect properties into tables" org-collector)
727 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
728 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
729 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
730 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
731 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
732 (const :tag "C eval: Include command output as text" org-eval)
733 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
734 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
735 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
736 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
737 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
738 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
739 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
740 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
741 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
742 (const :tag "C man: Support for links to manpages in Org mode" org-man)
743 (const :tag "C mew: Links to Mew folders/messages" org-mew)
744 (const :tag "C mtags: Support for muse-like tags" org-mtags)
745 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
746 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
747 (const :tag "C registry: A registry for Org links" org-registry)
748 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
749 (const :tag "C secretary: Team management with org-mode" org-secretary)
750 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
751 (const :tag "C toc: Table of contents for Org buffer" org-toc)
752 (const :tag "C track: Keep up with Org mode development" org-track)
753 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
754 (const :tag "C vm: Links to VM folders/messages" org-vm)
755 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
756 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
757 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
759 (defvar org-export-registered-backends) ; From ox.el.
760 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
761 (declare-function org-export-backend-name "ox" (backend) t)
762 (defcustom org-export-backends '(ascii html icalendar latex odt)
763 "List of export back-ends that should be always available.
765 If a description starts with <C>, the file is not part of Emacs
766 and loading it will require that you have downloaded and properly
767 installed the Org mode distribution.
769 Unlike to `org-modules', libraries in this list will not be
770 loaded along with Org, but only once the export framework is
771 needed.
773 This variable needs to be set before org.el is loaded. If you
774 need to make a change while Emacs is running, use the customize
775 interface or run the following code, where VAL stands for the new
776 value of the variable, after updating it:
778 (progn
779 (setq org-export-registered-backends
780 (cl-remove-if-not
781 (lambda (backend)
782 (let ((name (org-export-backend-name backend)))
783 (or (memq name val)
784 (catch \\='parentp
785 (dolist (b val)
786 (and (org-export-derived-backend-p b name)
787 (throw \\='parentp t)))))))
788 org-export-registered-backends))
789 (let ((new-list (mapcar #\\='org-export-backend-name
790 org-export-registered-backends)))
791 (dolist (backend val)
792 (cond
793 ((not (load (format \"ox-%s\" backend) t t))
794 (message \"Problems while trying to load export back-end \\=`%s\\='\"
795 backend))
796 ((not (memq backend new-list)) (push backend new-list))))
797 (set-default \\='org-export-backends new-list)))
799 Adding a back-end to this list will also pull the back-end it
800 depends on, if any."
801 :group 'org
802 :group 'org-export
803 :version "26.1"
804 :package-version '(Org . "9.0")
805 :initialize 'custom-initialize-set
806 :set (lambda (var val)
807 (if (not (featurep 'ox)) (set-default var val)
808 ;; Any back-end not required anymore (not present in VAL and not
809 ;; a parent of any back-end in the new value) is removed from the
810 ;; list of registered back-ends.
811 (setq org-export-registered-backends
812 (cl-remove-if-not
813 (lambda (backend)
814 (let ((name (org-export-backend-name backend)))
815 (or (memq name val)
816 (catch 'parentp
817 (dolist (b val)
818 (and (org-export-derived-backend-p b name)
819 (throw 'parentp t)))))))
820 org-export-registered-backends))
821 ;; Now build NEW-LIST of both new back-ends and required
822 ;; parents.
823 (let ((new-list (mapcar #'org-export-backend-name
824 org-export-registered-backends)))
825 (dolist (backend val)
826 (cond
827 ((not (load (format "ox-%s" backend) t t))
828 (message "Problems while trying to load export back-end `%s'"
829 backend))
830 ((not (memq backend new-list)) (push backend new-list))))
831 ;; Set VAR to that list with fixed dependencies.
832 (set-default var new-list))))
833 :type '(set :greedy t
834 (const :tag " ascii Export buffer to ASCII format" ascii)
835 (const :tag " beamer Export buffer to Beamer presentation" beamer)
836 (const :tag " html Export buffer to HTML format" html)
837 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
838 (const :tag " latex Export buffer to LaTeX format" latex)
839 (const :tag " man Export buffer to MAN format" man)
840 (const :tag " md Export buffer to Markdown format" md)
841 (const :tag " odt Export buffer to ODT format" odt)
842 (const :tag " org Export buffer to Org format" org)
843 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
844 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
845 (const :tag "C deck Export buffer to deck.js presentations" deck)
846 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
847 (const :tag "C groff Export buffer to Groff format" groff)
848 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
849 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
850 (const :tag "C s5 Export buffer to s5 presentations" s5)
851 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
853 (eval-after-load 'ox
854 '(dolist (backend org-export-backends)
855 (condition-case nil (require (intern (format "ox-%s" backend)))
856 (error (message "Problems while trying to load export back-end `%s'"
857 backend)))))
859 (defcustom org-support-shift-select nil
860 "Non-nil means make shift-cursor commands select text when possible.
861 \\<org-mode-map>\
863 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
864 start selecting a region, or enlarge regions started in this way.
865 In Org mode, in special contexts, these same keys are used for
866 other purposes, important enough to compete with shift selection.
867 Org tries to balance these needs by supporting `shift-select-mode'
868 outside these special contexts, under control of this variable.
870 The default of this variable is nil, to avoid confusing behavior. Shifted
871 cursor keys will then execute Org commands in the following contexts:
872 - on a headline, changing TODO state (left/right) and priority (up/down)
873 - on a time stamp, changing the time
874 - in a plain list item, changing the bullet type
875 - in a property definition line, switching between allowed values
876 - in the BEGIN line of a clock table (changing the time block).
877 Outside these contexts, the commands will throw an error.
879 When this variable is t and the cursor is not in a special
880 context, Org mode will support shift-selection for making and
881 enlarging regions. To make this more effective, the bullet
882 cycling will no longer happen anywhere in an item line, but only
883 if the cursor is exactly on the bullet.
885 If you set this variable to the symbol `always', then the keys
886 will not be special in headlines, property lines, and item lines,
887 to make shift selection work there as well. If this is what you
888 want, you can use the following alternative commands:
889 `\\[org-todo]' and `\\[org-priority]' \
890 to change TODO state and priority,
891 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
892 can be used to switch TODO sets,
893 `\\[org-ctrl-c-minus]' to cycle item bullet types,
894 and properties can be edited by hand or in column view.
896 However, when the cursor is on a timestamp, shift-cursor commands
897 will still edit the time stamp - this is just too good to give up."
898 :group 'org
899 :type '(choice
900 (const :tag "Never" nil)
901 (const :tag "When outside special context" t)
902 (const :tag "Everywhere except timestamps" always)))
904 (defcustom org-loop-over-headlines-in-active-region nil
905 "Shall some commands act upon headlines in the active region?
907 When set to t, some commands will be performed in all headlines
908 within the active region.
910 When set to `start-level', some commands will be performed in all
911 headlines within the active region, provided that these headlines
912 are of the same level than the first one.
914 When set to a string, those commands will be performed on the
915 matching headlines within the active region. Such string must be
916 a tags/property/todo match as it is used in the agenda tags view.
918 The list of commands is: `org-schedule', `org-deadline',
919 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
920 `org-archive-to-archive-sibling'. The archiving commands skip
921 already archived entries."
922 :type '(choice (const :tag "Don't loop" nil)
923 (const :tag "All headlines in active region" t)
924 (const :tag "In active region, headlines at the same level than the first one" start-level)
925 (string :tag "Tags/Property/Todo matcher"))
926 :version "24.1"
927 :group 'org-todo
928 :group 'org-archive)
930 (defgroup org-startup nil
931 "Options concerning startup of Org mode."
932 :tag "Org Startup"
933 :group 'org)
935 (defcustom org-startup-folded t
936 "Non-nil means entering Org mode will switch to OVERVIEW.
938 This can also be configured on a per-file basis by adding one of
939 the following lines anywhere in the buffer:
941 #+STARTUP: fold (or `overview', this is equivalent)
942 #+STARTUP: nofold (or `showall', this is equivalent)
943 #+STARTUP: content
944 #+STARTUP: showeverything
946 Set `org-agenda-inhibit-startup' to a non-nil value if you want
947 to ignore this option when Org opens agenda files for the first
948 time."
949 :group 'org-startup
950 :type '(choice
951 (const :tag "nofold: show all" nil)
952 (const :tag "fold: overview" t)
953 (const :tag "content: all headlines" content)
954 (const :tag "show everything, even drawers" showeverything)))
956 (defcustom org-startup-truncated t
957 "Non-nil means entering Org mode will set `truncate-lines'.
958 This is useful since some lines containing links can be very long and
959 uninteresting. Also tables look terrible when wrapped.
961 The variable `org-startup-truncated' allows to configure
962 truncation for Org mode different to the other modes that use the
963 variable `truncate-lines' and as a shortcut instead of putting
964 the variable `truncate-lines' into the `org-mode-hook'. If one
965 wants to configure truncation for Org mode not statically but
966 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
967 the variable `truncate-lines' has to be used because in such a
968 case it is too late to set the variable `org-startup-truncated'."
969 :group 'org-startup
970 :type 'boolean)
972 (defcustom org-startup-indented nil
973 "Non-nil means turn on `org-indent-mode' on startup.
974 This can also be configured on a per-file basis by adding one of
975 the following lines anywhere in the buffer:
977 #+STARTUP: indent
978 #+STARTUP: noindent"
979 :group 'org-structure
980 :type '(choice
981 (const :tag "Not" nil)
982 (const :tag "Globally (slow on startup in large files)" t)))
984 (defcustom org-use-sub-superscripts t
985 "Non-nil means interpret \"_\" and \"^\" for display.
987 If you want to control how Org exports those characters, see
988 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
989 used to be an alias for `org-export-with-sub-superscripts' in
990 Org <8.0, it is not anymore.
992 When this option is turned on, you can use TeX-like syntax for
993 sub- and superscripts within the buffer. Several characters after
994 \"_\" or \"^\" will be considered as a single item - so grouping
995 with {} is normally not needed. For example, the following things
996 will be parsed as single sub- or superscripts:
998 10^24 or 10^tau several digits will be considered 1 item.
999 10^-12 or 10^-tau a leading sign with digits or a word
1000 x^2-y^3 will be read as x^2 - y^3, because items are
1001 terminated by almost any nonword/nondigit char.
1002 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1004 Still, ambiguity is possible. So when in doubt, use {} to enclose
1005 the sub/superscript. If you set this variable to the symbol `{}',
1006 the braces are *required* in order to trigger interpretations as
1007 sub/superscript. This can be helpful in documents that need \"_\"
1008 frequently in plain text."
1009 :group 'org-startup
1010 :version "24.4"
1011 :package-version '(Org . "8.0")
1012 :type '(choice
1013 (const :tag "Always interpret" t)
1014 (const :tag "Only with braces" {})
1015 (const :tag "Never interpret" nil)))
1017 (defcustom org-startup-with-beamer-mode nil
1018 "Non-nil means turn on `org-beamer-mode' on startup.
1019 This can also be configured on a per-file basis by adding one of
1020 the following lines anywhere in the buffer:
1022 #+STARTUP: beamer"
1023 :group 'org-startup
1024 :version "24.1"
1025 :type 'boolean)
1027 (defcustom org-startup-align-all-tables nil
1028 "Non-nil means align all tables when visiting a file.
1029 This is useful when the column width in tables is forced with <N> cookies
1030 in table fields. Such tables will look correct only after the first re-align.
1031 This can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: align
1034 #+STARTUP: noalign"
1035 :group 'org-startup
1036 :type 'boolean)
1038 (defcustom org-startup-with-inline-images nil
1039 "Non-nil means show inline images when loading a new Org file.
1040 This can also be configured on a per-file basis by adding one of
1041 the following lines anywhere in the buffer:
1042 #+STARTUP: inlineimages
1043 #+STARTUP: noinlineimages"
1044 :group 'org-startup
1045 :version "24.1"
1046 :type 'boolean)
1048 (defcustom org-startup-with-latex-preview nil
1049 "Non-nil means preview LaTeX fragments when loading a new Org file.
1051 This can also be configured on a per-file basis by adding one of
1052 the following lines anywhere in the buffer:
1053 #+STARTUP: latexpreview
1054 #+STARTUP: nolatexpreview"
1055 :group 'org-startup
1056 :version "24.4"
1057 :package-version '(Org . "8.0")
1058 :type 'boolean)
1060 (defcustom org-insert-mode-line-in-empty-file nil
1061 "Non-nil means insert the first line setting Org mode in empty files.
1062 When the function `org-mode' is called interactively in an empty file, this
1063 normally means that the file name does not automatically trigger Org mode.
1064 To ensure that the file will always be in Org mode in the future, a
1065 line enforcing Org mode will be inserted into the buffer, if this option
1066 has been set."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-replace-disputed-keys nil
1071 "Non-nil means use alternative key bindings for some keys.
1072 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1073 These keys are also used by other packages like shift-selection-mode'
1074 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1075 If you want to use Org mode together with one of these other modes,
1076 or more generally if you would like to move some Org mode commands to
1077 other keys, set this variable and configure the keys with the variable
1078 `org-disputed-keys'.
1080 This option is only relevant at load-time of Org mode, and must be set
1081 *before* org.el is loaded. Changing it requires a restart of Emacs to
1082 become effective."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defcustom org-use-extra-keys nil
1087 "Non-nil means use extra key sequence definitions for certain commands.
1088 This happens automatically if `window-system' is nil. This
1089 variable lets you do the same manually. You must set it before
1090 loading Org."
1091 :group 'org-startup
1092 :type 'boolean)
1094 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1096 (defcustom org-disputed-keys
1097 '(([(shift up)] . [(meta p)])
1098 ([(shift down)] . [(meta n)])
1099 ([(shift left)] . [(meta -)])
1100 ([(shift right)] . [(meta +)])
1101 ([(control shift right)] . [(meta shift +)])
1102 ([(control shift left)] . [(meta shift -)]))
1103 "Keys for which Org mode and other modes compete.
1104 This is an alist, cars are the default keys, second element specifies
1105 the alternative to use when `org-replace-disputed-keys' is t.
1107 Keys can be specified in any syntax supported by `define-key'.
1108 The value of this option takes effect only at Org mode startup,
1109 therefore you'll have to restart Emacs to apply it after changing."
1110 :group 'org-startup
1111 :type 'alist)
1113 (defun org-key (key)
1114 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1115 Or return the original if not disputed."
1116 (when org-replace-disputed-keys
1117 (let* ((nkey (key-description key))
1118 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1119 org-disputed-keys)))
1120 (setq key (if x (cdr x) key))))
1121 key)
1123 (defun org-defkey (keymap key def)
1124 "Define a key, possibly translated, as returned by `org-key'."
1125 (define-key keymap (org-key key) def))
1127 (defcustom org-ellipsis nil
1128 "The ellipsis to use in the Org mode outline.
1130 When nil, just use the standard three dots.
1131 When a string, use that string instead.
1133 The change affects only Org mode (which will then use its own display table).
1134 Changing this requires executing `\\[org-mode]' in a buffer to become
1135 effective."
1136 :group 'org-startup
1137 :type '(choice (const :tag "Default" nil)
1138 (string :tag "String" :value "...#"))
1139 :safe #'string-or-null-p)
1141 (defvar org-display-table nil
1142 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1144 (defgroup org-keywords nil
1145 "Keywords in Org mode."
1146 :tag "Org Keywords"
1147 :group 'org)
1149 (defcustom org-closed-keep-when-no-todo nil
1150 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1151 :group 'org-todo
1152 :group 'org-keywords
1153 :version "24.4"
1154 :package-version '(Org . "8.0")
1155 :type 'boolean)
1157 (defgroup org-structure nil
1158 "Options concerning the general structure of Org files."
1159 :tag "Org Structure"
1160 :group 'org)
1162 (defgroup org-reveal-location nil
1163 "Options about how to make context of a location visible."
1164 :tag "Org Reveal Location"
1165 :group 'org-structure)
1167 (defcustom org-show-context-detail '((agenda . local)
1168 (bookmark-jump . lineage)
1169 (isearch . lineage)
1170 (default . ancestors))
1171 "Alist between context and visibility span when revealing a location.
1173 \\<org-mode-map>Some actions may move point into invisible
1174 locations. As a consequence, Org always expose a neighborhood
1175 around point. How much is shown depends on the initial action,
1176 or context. Valid contexts are
1178 agenda when exposing an entry from the agenda
1179 org-goto when using the command `org-goto' (`\\[org-goto]')
1180 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1181 tags-tree when constructing a sparse tree based on tags matches
1182 link-search when exposing search matches associated with a link
1183 mark-goto when exposing the jump goal of a mark
1184 bookmark-jump when exposing a bookmark location
1185 isearch when exiting from an incremental search
1186 default default for all contexts not set explicitly
1188 Allowed visibility spans are
1190 minimal show current headline; if point is not on headline,
1191 also show entry
1193 local show current headline, entry and next headline
1195 ancestors show current headline and its direct ancestors; if
1196 point is not on headline, also show entry
1198 lineage show current headline, its direct ancestors and all
1199 their children; if point is not on headline, also show
1200 entry and first child
1202 tree show current headline, its direct ancestors and all
1203 their children; if point is not on headline, also show
1204 entry and all children
1206 canonical show current headline, its direct ancestors along with
1207 their entries and children; if point is not located on
1208 the headline, also show current entry and all children
1210 As special cases, a nil or t value means show all contexts in
1211 `minimal' or `canonical' view, respectively.
1213 Some views can make displayed information very compact, but also
1214 make it harder to edit the location of the match. In such
1215 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1216 more context."
1217 :group 'org-reveal-location
1218 :version "26.1"
1219 :package-version '(Org . "9.0")
1220 :type '(choice
1221 (const :tag "Canonical" t)
1222 (const :tag "Minimal" nil)
1223 (repeat :greedy t :tag "Individual contexts"
1224 (cons
1225 (choice :tag "Context"
1226 (const agenda)
1227 (const org-goto)
1228 (const occur-tree)
1229 (const tags-tree)
1230 (const link-search)
1231 (const mark-goto)
1232 (const bookmark-jump)
1233 (const isearch)
1234 (const default))
1235 (choice :tag "Detail level"
1236 (const minimal)
1237 (const local)
1238 (const ancestors)
1239 (const lineage)
1240 (const tree)
1241 (const canonical))))))
1243 (defcustom org-indirect-buffer-display 'other-window
1244 "How should indirect tree buffers be displayed?
1246 This applies to indirect buffers created with the commands
1247 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1249 Valid values are:
1250 current-window Display in the current window
1251 other-window Just display in another window.
1252 dedicated-frame Create one new frame, and re-use it each time.
1253 new-frame Make a new frame each time. Note that in this case
1254 previously-made indirect buffers are kept, and you need to
1255 kill these buffers yourself."
1256 :group 'org-structure
1257 :group 'org-agenda-windows
1258 :type '(choice
1259 (const :tag "In current window" current-window)
1260 (const :tag "In current frame, other window" other-window)
1261 (const :tag "Each time a new frame" new-frame)
1262 (const :tag "One dedicated frame" dedicated-frame)))
1264 (defcustom org-use-speed-commands nil
1265 "Non-nil means activate single letter commands at beginning of a headline.
1266 This may also be a function to test for appropriate locations where speed
1267 commands should be active.
1269 For example, to activate speed commands when the point is on any
1270 star at the beginning of the headline, you can do this:
1272 (setq org-use-speed-commands
1273 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1274 :group 'org-structure
1275 :type '(choice
1276 (const :tag "Never" nil)
1277 (const :tag "At beginning of headline stars" t)
1278 (function)))
1280 (defcustom org-speed-commands-user nil
1281 "Alist of additional speed commands.
1282 This list will be checked before `org-speed-commands-default'
1283 when the variable `org-use-speed-commands' is non-nil
1284 and when the cursor is at the beginning of a headline.
1285 The car if each entry is a string with a single letter, which must
1286 be assigned to `self-insert-command' in the global map.
1287 The cdr is either a command to be called interactively, a function
1288 to be called, or a form to be evaluated.
1289 An entry that is just a list with a single string will be interpreted
1290 as a descriptive headline that will be added when listing the speed
1291 commands in the Help buffer using the `?' speed command."
1292 :group 'org-structure
1293 :type '(repeat :value ("k" . ignore)
1294 (choice :value ("k" . ignore)
1295 (list :tag "Descriptive Headline" (string :tag "Headline"))
1296 (cons :tag "Letter and Command"
1297 (string :tag "Command letter")
1298 (choice
1299 (function)
1300 (sexp))))))
1302 (defcustom org-bookmark-names-plist
1303 '(:last-capture "org-capture-last-stored"
1304 :last-refile "org-refile-last-stored"
1305 :last-capture-marker "org-capture-last-stored-marker")
1306 "Names for bookmarks automatically set by some Org commands.
1307 This can provide strings as names for a number of bookmarks Org sets
1308 automatically. The following keys are currently implemented:
1309 :last-capture
1310 :last-capture-marker
1311 :last-refile
1312 When a key does not show up in the property list, the corresponding bookmark
1313 is not set."
1314 :group 'org-structure
1315 :type 'plist)
1317 (defgroup org-cycle nil
1318 "Options concerning visibility cycling in Org mode."
1319 :tag "Org Cycle"
1320 :group 'org-structure)
1322 (defcustom org-cycle-skip-children-state-if-no-children t
1323 "Non-nil means skip CHILDREN state in entries that don't have any."
1324 :group 'org-cycle
1325 :type 'boolean)
1327 (defcustom org-cycle-max-level nil
1328 "Maximum level which should still be subject to visibility cycling.
1329 Levels higher than this will, for cycling, be treated as text, not a headline.
1330 When `org-odd-levels-only' is set, a value of N in this variable actually
1331 means 2N-1 stars as the limiting headline.
1332 When nil, cycle all levels.
1333 Note that the limiting level of cycling is also influenced by
1334 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1335 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1336 than its value."
1337 :group 'org-cycle
1338 :type '(choice
1339 (const :tag "No limit" nil)
1340 (integer :tag "Maximum level")))
1342 (defcustom org-hide-block-startup nil
1343 "Non-nil means entering Org mode will fold all blocks.
1344 This can also be set in on a per-file basis with
1346 #+STARTUP: hideblocks
1347 #+STARTUP: showblocks"
1348 :group 'org-startup
1349 :group 'org-cycle
1350 :type 'boolean)
1352 (defcustom org-cycle-global-at-bob nil
1353 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1355 This makes it possible to do global cycling without having to use `S-TAB'
1356 or `\\[universal-argument] TAB'. For this special case to work, the first \
1357 line of the buffer
1358 must not be a headline -- it may be empty or some other text.
1360 When used in this way, `org-cycle-hook' is disabled temporarily to make
1361 sure the cursor stays at the beginning of the buffer.
1363 When this option is nil, don't do anything special at the beginning of
1364 the buffer."
1365 :group 'org-cycle
1366 :type 'boolean)
1368 (defcustom org-cycle-level-after-item/entry-creation t
1369 "Non-nil means cycle entry level or item indentation in new empty entries.
1371 When the cursor is at the end of an empty headline, i.e., with only stars
1372 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1373 and then all possible ancestor states, before returning to the original state.
1374 This makes data entry extremely fast: M-RET to create a new headline,
1375 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1377 When the cursor is at the end of an empty plain list item, one TAB will
1378 make it a subitem, two or more tabs will back up to make this an item
1379 higher up in the item hierarchy."
1380 :group 'org-cycle
1381 :type 'boolean)
1383 (defcustom org-cycle-emulate-tab t
1384 "Where should `org-cycle' emulate TAB.
1385 nil Never
1386 white Only in completely white lines
1387 whitestart Only at the beginning of lines, before the first non-white char
1388 t Everywhere except in headlines
1389 exc-hl-bol Everywhere except at the start of a headline
1390 If TAB is used in a place where it does not emulate TAB, the current subtree
1391 visibility is cycled."
1392 :group 'org-cycle
1393 :type '(choice (const :tag "Never" nil)
1394 (const :tag "Only in completely white lines" white)
1395 (const :tag "Before first char in a line" whitestart)
1396 (const :tag "Everywhere except in headlines" t)
1397 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1399 (defcustom org-cycle-separator-lines 2
1400 "Number of empty lines needed to keep an empty line between collapsed trees.
1401 If you leave an empty line between the end of a subtree and the following
1402 headline, this empty line is hidden when the subtree is folded.
1403 Org mode will leave (exactly) one empty line visible if the number of
1404 empty lines is equal or larger to the number given in this variable.
1405 So the default 2 means at least 2 empty lines after the end of a subtree
1406 are needed to produce free space between a collapsed subtree and the
1407 following headline.
1409 If the number is negative, and the number of empty lines is at least -N,
1410 all empty lines are shown.
1412 Special case: when 0, never leave empty lines in collapsed view."
1413 :group 'org-cycle
1414 :type 'integer)
1415 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1417 (defcustom org-pre-cycle-hook nil
1418 "Hook that is run before visibility cycling is happening.
1419 The function(s) in this hook must accept a single argument which indicates
1420 the new state that will be set right after running this hook. The
1421 argument is a symbol. Before a global state change, it can have the values
1422 `overview', `content', or `all'. Before a local state change, it can have
1423 the values `folded', `children', or `subtree'."
1424 :group 'org-cycle
1425 :type 'hook)
1427 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1428 org-cycle-hide-drawers
1429 org-cycle-show-empty-lines
1430 org-optimize-window-after-visibility-change)
1431 "Hook that is run after `org-cycle' has changed the buffer visibility.
1432 The function(s) in this hook must accept a single argument which indicates
1433 the new state that was set by the most recent `org-cycle' command. The
1434 argument is a symbol. After a global state change, it can have the values
1435 `overview', `contents', or `all'. After a local state change, it can have
1436 the values `folded', `children', or `subtree'."
1437 :group 'org-cycle
1438 :type 'hook
1439 :version "26.1"
1440 :package-version '(Org . "8.3"))
1442 (defgroup org-edit-structure nil
1443 "Options concerning structure editing in Org mode."
1444 :tag "Org Edit Structure"
1445 :group 'org-structure)
1447 (defcustom org-odd-levels-only nil
1448 "Non-nil means skip even levels and only use odd levels for the outline.
1449 This has the effect that two stars are being added/taken away in
1450 promotion/demotion commands. It also influences how levels are
1451 handled by the exporters.
1452 Changing it requires restart of `font-lock-mode' to become effective
1453 for fontification also in regions already fontified.
1454 You may also set this on a per-file basis by adding one of the following
1455 lines to the buffer:
1457 #+STARTUP: odd
1458 #+STARTUP: oddeven"
1459 :group 'org-edit-structure
1460 :group 'org-appearance
1461 :type 'boolean)
1463 (defcustom org-adapt-indentation t
1464 "Non-nil means adapt indentation to outline node level.
1466 When this variable is set, Org assumes that you write outlines by
1467 indenting text in each node to align with the headline (after the
1468 stars). The following issues are influenced by this variable:
1470 - The indentation is increased by one space in a demotion
1471 command, and decreased by one in a promotion command. However,
1472 in the latter case, if shifting some line in the entry body
1473 would alter document structure (e.g., insert a new headline),
1474 indentation is not changed at all.
1476 - Property drawers and planning information is inserted indented
1477 when this variable is set. When nil, they will not be indented.
1479 - TAB indents a line relative to current level. The lines below
1480 a headline will be indented when this variable is set.
1482 Note that this is all about true indentation, by adding and
1483 removing space characters. See also `org-indent.el' which does
1484 level-dependent indentation in a virtual way, i.e. at display
1485 time in Emacs."
1486 :group 'org-edit-structure
1487 :type 'boolean)
1489 (defcustom org-special-ctrl-a/e nil
1490 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1492 When t, `C-a' will bring back the cursor to the beginning of the
1493 headline text, i.e. after the stars and after a possible TODO
1494 keyword. In an item, this will be the position after bullet and
1495 check-box, if any. When the cursor is already at that position,
1496 another `C-a' will bring it to the beginning of the line.
1498 `C-e' will jump to the end of the headline, ignoring the presence
1499 of tags in the headline. A second `C-e' will then jump to the
1500 true end of the line, after any tags. This also means that, when
1501 this variable is non-nil, `C-e' also will never jump beyond the
1502 end of the heading of a folded section, i.e. not after the
1503 ellipses.
1505 When set to the symbol `reversed', the first `C-a' or `C-e' works
1506 normally, going to the true line boundary first. Only a directly
1507 following, identical keypress will bring the cursor to the
1508 special positions.
1510 This may also be a cons cell where the behavior for `C-a' and
1511 `C-e' is set separately."
1512 :group 'org-edit-structure
1513 :type '(choice
1514 (const :tag "off" nil)
1515 (const :tag "on: after stars/bullet and before tags first" t)
1516 (const :tag "reversed: true line boundary first" reversed)
1517 (cons :tag "Set C-a and C-e separately"
1518 (choice :tag "Special C-a"
1519 (const :tag "off" nil)
1520 (const :tag "on: after stars/bullet first" t)
1521 (const :tag "reversed: before stars/bullet first" reversed))
1522 (choice :tag "Special C-e"
1523 (const :tag "off" nil)
1524 (const :tag "on: before tags first" t)
1525 (const :tag "reversed: after tags first" reversed)))))
1526 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1528 (defcustom org-special-ctrl-k nil
1529 "Non-nil means `C-k' will behave specially in headlines.
1530 When nil, `C-k' will call the default `kill-line' command.
1531 When t, the following will happen while the cursor is in the headline:
1533 - When the cursor is at the beginning of a headline, kill the entire
1534 line and possible the folded subtree below the line.
1535 - When in the middle of the headline text, kill the headline up to the tags.
1536 - When after the headline text, kill the tags."
1537 :group 'org-edit-structure
1538 :type 'boolean)
1540 (defcustom org-ctrl-k-protect-subtree nil
1541 "Non-nil means, do not delete a hidden subtree with C-k.
1542 When set to the symbol `error', simply throw an error when C-k is
1543 used to kill (part-of) a headline that has hidden text behind it.
1544 Any other non-nil value will result in a query to the user, if it is
1545 OK to kill that hidden subtree. When nil, kill without remorse."
1546 :group 'org-edit-structure
1547 :version "24.1"
1548 :type '(choice
1549 (const :tag "Do not protect hidden subtrees" nil)
1550 (const :tag "Protect hidden subtrees with a security query" t)
1551 (const :tag "Never kill a hidden subtree with C-k" error)))
1553 (defcustom org-special-ctrl-o t
1554 "Non-nil means, make `C-o' insert a row in tables."
1555 :group 'org-edit-structure
1556 :type 'boolean)
1558 (defcustom org-catch-invisible-edits nil
1559 "Check if in invisible region before inserting or deleting a character.
1560 Valid values are:
1562 nil Do not check, so just do invisible edits.
1563 error Throw an error and do nothing.
1564 show Make point visible, and do the requested edit.
1565 show-and-error Make point visible, then throw an error and abort the edit.
1566 smart Make point visible, and do insertion/deletion if it is
1567 adjacent to visible text and the change feels predictable.
1568 Never delete a previously invisible character or add in the
1569 middle or right after an invisible region. Basically, this
1570 allows insertion and backward-delete right before ellipses.
1571 FIXME: maybe in this case we should not even show?"
1572 :group 'org-edit-structure
1573 :version "24.1"
1574 :type '(choice
1575 (const :tag "Do not check" nil)
1576 (const :tag "Throw error when trying to edit" error)
1577 (const :tag "Unhide, but do not do the edit" show-and-error)
1578 (const :tag "Show invisible part and do the edit" show)
1579 (const :tag "Be smart and do the right thing" smart)))
1581 (defcustom org-yank-folded-subtrees t
1582 "Non-nil means when yanking subtrees, fold them.
1583 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1584 it starts with a heading and all other headings in it are either children
1585 or siblings, then fold all the subtrees. However, do this only if no
1586 text after the yank would be swallowed into a folded tree by this action."
1587 :group 'org-edit-structure
1588 :type 'boolean)
1590 (defcustom org-yank-adjusted-subtrees nil
1591 "Non-nil means when yanking subtrees, adjust the level.
1592 With this setting, `org-paste-subtree' is used to insert the subtree, see
1593 this function for details."
1594 :group 'org-edit-structure
1595 :type 'boolean)
1597 (defcustom org-M-RET-may-split-line '((default . t))
1598 "Non-nil means M-RET will split the line at the cursor position.
1599 When nil, it will go to the end of the line before making a
1600 new line.
1601 You may also set this option in a different way for different
1602 contexts. Valid contexts are:
1604 headline when creating a new headline
1605 item when creating a new item
1606 table in a table field
1607 default the value to be used for all contexts not explicitly
1608 customized"
1609 :group 'org-structure
1610 :group 'org-table
1611 :type '(choice
1612 (const :tag "Always" t)
1613 (const :tag "Never" nil)
1614 (repeat :greedy t :tag "Individual contexts"
1615 (cons
1616 (choice :tag "Context"
1617 (const headline)
1618 (const item)
1619 (const table)
1620 (const default))
1621 (boolean)))))
1624 (defcustom org-insert-heading-respect-content nil
1625 "Non-nil means insert new headings after the current subtree.
1626 \\<org-mode-map>
1627 When nil, the new heading is created directly after the current line.
1628 The commands `\\[org-insert-heading-respect-content]' and \
1629 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1630 for the duration of the command."
1631 :group 'org-structure
1632 :type 'boolean)
1634 (defcustom org-blank-before-new-entry '((heading . auto)
1635 (plain-list-item . auto))
1636 "Should `org-insert-heading' leave a blank line before new heading/item?
1637 The value is an alist, with `heading' and `plain-list-item' as CAR,
1638 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1639 which case Org will look at the surrounding headings/items and try to
1640 make an intelligent decision whether to insert a blank line or not."
1641 :group 'org-edit-structure
1642 :type '(list
1643 (cons (const heading)
1644 (choice (const :tag "Never" nil)
1645 (const :tag "Always" t)
1646 (const :tag "Auto" auto)))
1647 (cons (const plain-list-item)
1648 (choice (const :tag "Never" nil)
1649 (const :tag "Always" t)
1650 (const :tag "Auto" auto)))))
1652 (defcustom org-insert-heading-hook nil
1653 "Hook being run after inserting a new heading."
1654 :group 'org-edit-structure
1655 :type 'hook)
1657 (defcustom org-enable-fixed-width-editor t
1658 "Non-nil means lines starting with \":\" are treated as fixed-width.
1659 This currently only means they are never auto-wrapped.
1660 When nil, such lines will be treated like ordinary lines."
1661 :group 'org-edit-structure
1662 :type 'boolean)
1664 (defcustom org-goto-auto-isearch t
1665 "Non-nil means typing characters in `org-goto' starts incremental search.
1666 When nil, you can use these keybindings to navigate the buffer:
1668 q Quit the org-goto interface
1669 n Go to the next visible heading
1670 p Go to the previous visible heading
1671 f Go one heading forward on same level
1672 b Go one heading backward on same level
1673 u Go one heading up"
1674 :group 'org-edit-structure
1675 :type 'boolean)
1677 (defgroup org-sparse-trees nil
1678 "Options concerning sparse trees in Org mode."
1679 :tag "Org Sparse Trees"
1680 :group 'org-structure)
1682 (defcustom org-highlight-sparse-tree-matches t
1683 "Non-nil means highlight all matches that define a sparse tree.
1684 The highlights will automatically disappear the next time the buffer is
1685 changed by an edit command."
1686 :group 'org-sparse-trees
1687 :type 'boolean)
1689 (defcustom org-remove-highlights-with-change t
1690 "Non-nil means any change to the buffer will remove temporary highlights.
1691 \\<org-mode-map>\
1692 Such highlights are created by `org-occur' and `org-clock-display'.
1693 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1694 to get rid of the highlights.
1695 The highlights created by `org-toggle-latex-fragment' always need
1696 `\\[org-toggle-latex-fragment]' to be removed."
1697 :group 'org-sparse-trees
1698 :group 'org-time
1699 :type 'boolean)
1701 (defcustom org-occur-case-fold-search t
1702 "Non-nil means `org-occur' should be case-insensitive.
1703 If set to `smart' the search will be case-insensitive only if it
1704 doesn't specify any upper case character."
1705 :group 'org-sparse-trees
1706 :version "26.1"
1707 :type '(choice
1708 (const :tag "Case-sensitive" nil)
1709 (const :tag "Case-insensitive" t)
1710 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1712 (defcustom org-occur-hook '(org-first-headline-recenter)
1713 "Hook that is run after `org-occur' has constructed a sparse tree.
1714 This can be used to recenter the window to show as much of the structure
1715 as possible."
1716 :group 'org-sparse-trees
1717 :type 'hook)
1719 (defgroup org-imenu-and-speedbar nil
1720 "Options concerning imenu and speedbar in Org mode."
1721 :tag "Org Imenu and Speedbar"
1722 :group 'org-structure)
1724 (defcustom org-imenu-depth 2
1725 "The maximum level for Imenu access to Org headlines.
1726 This also applied for speedbar access."
1727 :group 'org-imenu-and-speedbar
1728 :type 'integer)
1730 (defgroup org-table nil
1731 "Options concerning tables in Org mode."
1732 :tag "Org Table"
1733 :group 'org)
1735 (defcustom org-enable-table-editor 'optimized
1736 "Non-nil means lines starting with \"|\" are handled by the table editor.
1737 When nil, such lines will be treated like ordinary lines.
1739 When equal to the symbol `optimized', the table editor will be optimized to
1740 do the following:
1741 - Automatic overwrite mode in front of whitespace in table fields.
1742 This makes the structure of the table stay in tact as long as the edited
1743 field does not exceed the column width.
1744 - Minimize the number of realigns. Normally, the table is aligned each time
1745 TAB or RET are pressed to move to another field. With optimization this
1746 happens only if changes to a field might have changed the column width.
1747 Optimization requires replacing the functions `self-insert-command',
1748 `delete-char', and `backward-delete-char' in Org buffers, with a
1749 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1750 good at guessing when a re-align will be necessary, but you can always
1751 force one with `\\[org-ctrl-c-ctrl-c]'.
1753 If you would like to use the optimized version in Org mode, but the
1754 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1756 This variable can be used to turn on and off the table editor during a session,
1757 but in order to toggle optimization, a restart is required.
1759 See also the variable `org-table-auto-blank-field'."
1760 :group 'org-table
1761 :type '(choice
1762 (const :tag "off" nil)
1763 (const :tag "on" t)
1764 (const :tag "on, optimized" optimized)))
1766 (defcustom org-self-insert-cluster-for-undo nil
1767 "Non-nil means cluster self-insert commands for undo when possible.
1768 If this is set, then, like in the Emacs command loop, 20 consecutive
1769 characters will be undone together.
1770 This is configurable, because there is some impact on typing performance."
1771 :group 'org-table
1772 :type 'boolean)
1774 (defcustom org-table-tab-recognizes-table.el t
1775 "Non-nil means TAB will automatically notice a table.el table.
1776 When it sees such a table, it moves point into it and - if necessary -
1777 calls `table-recognize-table'."
1778 :group 'org-table-editing
1779 :type 'boolean)
1781 (defgroup org-link nil
1782 "Options concerning links in Org mode."
1783 :tag "Org Link"
1784 :group 'org)
1786 (defvar-local org-link-abbrev-alist-local nil
1787 "Buffer-local version of `org-link-abbrev-alist', which see.
1788 The value of this is taken from the #+LINK lines.")
1790 (defcustom org-link-parameters
1791 '(("doi" :follow org--open-doi-link)
1792 ("elisp" :follow org--open-elisp-link)
1793 ("file" :complete org-file-complete-link)
1794 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1795 ("help" :follow org--open-help-link)
1796 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1797 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1798 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1799 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1800 ("shell" :follow org--open-shell-link))
1801 "An alist of properties that defines all the links in Org mode.
1802 The key in each association is a string of the link type.
1803 Subsequent optional elements make up a p-list of link properties.
1805 :follow - A function that takes the link path as an argument.
1807 :export - A function that takes the link path, description and
1808 export-backend as arguments.
1810 :store - A function responsible for storing the link. See the
1811 function `org-store-link-functions'.
1813 :complete - A function that inserts a link with completion. The
1814 function takes one optional prefix arg.
1816 :face - A face for the link, or a function that returns a face.
1817 The function takes one argument which is the link path. The
1818 default face is `org-link'.
1820 :mouse-face - The mouse-face. The default is `highlight'.
1822 :display - `full' will not fold the link in descriptive
1823 display. Default is `org-link'.
1825 :help-echo - A string or function that takes (window object position)
1826 as arguments and returns a string.
1828 :keymap - A keymap that is active on the link. The default is
1829 `org-mouse-map'.
1831 :htmlize-link - A function for the htmlize-link. Defaults
1832 to (list :uri \"type:path\")
1834 :activate-func - A function to run at the end of font-lock
1835 activation. The function must accept (link-start link-end path bracketp)
1836 as arguments."
1837 :group 'org-link
1838 :type '(alist :tag "Link display parameters"
1839 :value-type plist)
1840 :version "26.1"
1841 :package-version '(Org . "9.1"))
1843 (defun org-link-get-parameter (type key)
1844 "Get TYPE link property for KEY.
1845 TYPE is a string and KEY is a plist keyword."
1846 (plist-get
1847 (cdr (assoc type org-link-parameters))
1848 key))
1850 (defun org-link-set-parameters (type &rest parameters)
1851 "Set link TYPE properties to PARAMETERS.
1852 PARAMETERS should be :key val pairs."
1853 (let ((data (assoc type org-link-parameters)))
1854 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1855 (push (cons type parameters) org-link-parameters)
1856 (org-make-link-regexps)
1857 (org-element-update-syntax))))
1859 (defun org-link-types ()
1860 "Return a list of known link types."
1861 (mapcar #'car org-link-parameters))
1863 (defcustom org-link-abbrev-alist nil
1864 "Alist of link abbreviations.
1865 The car of each element is a string, to be replaced at the start of a link.
1866 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1867 links in Org buffers can have an optional tag after a double colon, e.g.,
1869 [[linkkey:tag][description]]
1871 The `linkkey' must be a single word, starting with a letter, followed
1872 by letters, numbers, `-' or `_'.
1874 If REPLACE is a string, the tag will simply be appended to create the link.
1875 If the string contains \"%s\", the tag will be inserted there. If the string
1876 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1877 at that point (see the function `url-hexify-string'). If the string contains
1878 the specifier \"%(my-function)\", then the custom function `my-function' will
1879 be invoked: this function takes the tag as its only argument and must return
1880 a string.
1882 REPLACE may also be a function that will be called with the tag as the
1883 only argument to create the link, which should be returned as a string.
1885 See the manual for examples."
1886 :group 'org-link
1887 :type '(repeat
1888 (cons
1889 (string :tag "Protocol")
1890 (choice
1891 (string :tag "Format")
1892 (function)))))
1894 (defcustom org-descriptive-links t
1895 "Non-nil means Org will display descriptive links.
1896 E.g. [[http://orgmode.org][Org website]] will be displayed as
1897 \"Org Website\", hiding the link itself and just displaying its
1898 description. When set to nil, Org will display the full links
1899 literally.
1901 You can interactively set the value of this variable by calling
1902 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1903 :group 'org-link
1904 :type 'boolean)
1906 (defcustom org-link-file-path-type 'adaptive
1907 "How the path name in file links should be stored.
1908 Valid values are:
1910 relative Relative to the current directory, i.e. the directory of the file
1911 into which the link is being inserted.
1912 absolute Absolute path, if possible with ~ for home directory.
1913 noabbrev Absolute path, no abbreviation of home directory.
1914 adaptive Use relative path for files in the current directory and sub-
1915 directories of it. For other files, use an absolute path."
1916 :group 'org-link
1917 :type '(choice
1918 (const relative)
1919 (const absolute)
1920 (const noabbrev)
1921 (const adaptive)))
1923 (defvaralias 'org-activate-links 'org-highlight-links)
1924 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1925 "Types of links that should be highlighted in Org files.
1927 This is a list of symbols, each one of them leading to the
1928 highlighting of a certain link type.
1930 You can still open links that are not highlighted.
1932 In principle, it does not hurt to turn on highlighting for all
1933 link types. There may be a small gain when turning off unused
1934 link types. The types are:
1936 bracket The recommended [[link][description]] or [[link]] links with hiding.
1937 angle Links in angular brackets that may contain whitespace like
1938 <bbdb:Carsten Dominik>.
1939 plain Plain links in normal text, no whitespace, like http://google.com.
1940 radio Text that is matched by a radio target, see manual for details.
1941 tag Tag settings in a headline (link to tag search).
1942 date Time stamps (link to calendar).
1943 footnote Footnote labels.
1945 If you set this variable during an Emacs session, use `org-mode-restart'
1946 in the Org buffer so that the change takes effect."
1947 :group 'org-link
1948 :group 'org-appearance
1949 :type '(set :greedy t
1950 (const :tag "Double bracket links" bracket)
1951 (const :tag "Angular bracket links" angle)
1952 (const :tag "Plain text links" plain)
1953 (const :tag "Radio target matches" radio)
1954 (const :tag "Tags" tag)
1955 (const :tag "Timestamps" date)
1956 (const :tag "Footnotes" footnote)))
1958 (defcustom org-make-link-description-function nil
1959 "Function to use for generating link descriptions from links.
1960 When nil, the link location will be used. This function must take
1961 two parameters: the first one is the link, the second one is the
1962 description generated by `org-insert-link'. The function should
1963 return the description to use."
1964 :group 'org-link
1965 :type '(choice (const nil) (function)))
1967 (defgroup org-link-store nil
1968 "Options concerning storing links in Org mode."
1969 :tag "Org Store Link"
1970 :group 'org-link)
1972 (defcustom org-url-hexify-p t
1973 "When non-nil, hexify URL when creating a link."
1974 :type 'boolean
1975 :version "24.3"
1976 :group 'org-link-store)
1978 (defcustom org-email-link-description-format "Email %c: %.30s"
1979 "Format of the description part of a link to an email or usenet message.
1980 The following %-escapes will be replaced by corresponding information:
1982 %F full \"From\" field
1983 %f name, taken from \"From\" field, address if no name
1984 %T full \"To\" field
1985 %t first name in \"To\" field, address if no name
1986 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1987 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1988 %s subject
1989 %d date
1990 %m message-id.
1992 You may use normal field width specification between the % and the letter.
1993 This is for example useful to limit the length of the subject.
1995 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1996 :group 'org-link-store
1997 :type 'string)
1999 (defcustom org-from-is-user-regexp
2000 (let (r1 r2)
2001 (when (and user-mail-address (not (string= user-mail-address "")))
2002 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
2003 (when (and user-full-name (not (string= user-full-name "")))
2004 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
2005 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
2006 "Regexp matched against the \"From:\" header of an email or usenet message.
2007 It should match if the message is from the user him/herself."
2008 :group 'org-link-store
2009 :type 'regexp)
2011 (defcustom org-context-in-file-links t
2012 "Non-nil means file links from `org-store-link' contain context.
2013 \\<org-mode-map>
2014 A search string will be added to the file name with :: as separator
2015 and used to find the context when the link is activated by the command
2016 `org-open-at-point'. When this option is t, the entire active region
2017 will be placed in the search string of the file link. If set to a
2018 positive integer, only the first n lines of context will be stored.
2020 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2021 \\[org-store-link]')
2022 negates this setting for the duration of the command."
2023 :group 'org-link-store
2024 :type '(choice boolean integer))
2026 (defcustom org-keep-stored-link-after-insertion nil
2027 "Non-nil means keep link in list for entire session.
2028 \\<org-mode-map>
2029 The command `org-store-link' adds a link pointing to the current
2030 location to an internal list. These links accumulate during a session.
2031 The command `org-insert-link' can be used to insert links into any
2032 Org file (offering completion for all stored links).
2034 When this option is nil, every link which has been inserted once using
2035 `\\[org-insert-link]' will be removed from the list, to make completing the \
2036 unused
2037 links more efficient."
2038 :group 'org-link-store
2039 :type 'boolean)
2041 (defgroup org-link-follow nil
2042 "Options concerning following links in Org mode."
2043 :tag "Org Follow Link"
2044 :group 'org-link)
2046 (defcustom org-link-translation-function nil
2047 "Function to translate links with different syntax to Org syntax.
2048 This can be used to translate links created for example by the Planner
2049 or emacs-wiki packages to Org syntax.
2050 The function must accept two parameters, a TYPE containing the link
2051 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2052 which is everything after the link protocol. It should return a cons
2053 with possibly modified values of type and path.
2054 Org contains a function for this, so if you set this variable to
2055 `org-translate-link-from-planner', you should be able follow many
2056 links created by planner."
2057 :group 'org-link-follow
2058 :type '(choice (const nil) (function)))
2060 (defcustom org-follow-link-hook nil
2061 "Hook that is run after a link has been followed."
2062 :group 'org-link-follow
2063 :type 'hook)
2065 (defcustom org-tab-follows-link nil
2066 "Non-nil means on links TAB will follow the link.
2067 Needs to be set before org.el is loaded.
2068 This really should not be used, it does not make sense, and the
2069 implementation is bad."
2070 :group 'org-link-follow
2071 :type 'boolean)
2073 (defcustom org-return-follows-link nil
2074 "Non-nil means on links RET will follow the link.
2075 In tables, the special behavior of RET has precedence."
2076 :group 'org-link-follow
2077 :type 'boolean)
2079 (defcustom org-mouse-1-follows-link
2080 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2081 "Non-nil means mouse-1 on a link will follow the link.
2082 A longer mouse click will still set point. Needs to be set
2083 before org.el is loaded."
2084 :group 'org-link-follow
2085 :version "24.4"
2086 :package-version '(Org . "8.3")
2087 :type '(choice
2088 (const :tag "A double click follows the link" double)
2089 (const :tag "Unconditionally follow the link with mouse-1" t)
2090 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2092 (defcustom org-mark-ring-length 4
2093 "Number of different positions to be recorded in the ring.
2094 Changing this requires a restart of Emacs to work correctly."
2095 :group 'org-link-follow
2096 :type 'integer)
2098 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2099 "Non-nil means internal fuzzy links can only match headlines.
2101 When nil, the a fuzzy link may point to a target or a named
2102 construct in the document. When set to the special value
2103 `query-to-create', offer to create a new headline when none
2104 matched.
2106 Spaces and statistics cookies are ignored during heading searches."
2107 :group 'org-link-follow
2108 :version "24.1"
2109 :type '(choice
2110 (const :tag "Use fuzzy text search" nil)
2111 (const :tag "Match only exact headline" t)
2112 (const :tag "Match exact headline or query to create it"
2113 query-to-create))
2114 :safe #'symbolp)
2116 (defcustom org-link-frame-setup
2117 '((vm . vm-visit-folder-other-frame)
2118 (vm-imap . vm-visit-imap-folder-other-frame)
2119 (gnus . org-gnus-no-new-news)
2120 (file . find-file-other-window)
2121 (wl . wl-other-frame))
2122 "Setup the frame configuration for following links.
2123 When following a link with Emacs, it may often be useful to display
2124 this link in another window or frame. This variable can be used to
2125 set this up for the different types of links.
2126 For VM, use any of
2127 `vm-visit-folder'
2128 `vm-visit-folder-other-window'
2129 `vm-visit-folder-other-frame'
2130 For Gnus, use any of
2131 `gnus'
2132 `gnus-other-frame'
2133 `org-gnus-no-new-news'
2134 For FILE, use any of
2135 `find-file'
2136 `find-file-other-window'
2137 `find-file-other-frame'
2138 For Wanderlust use any of
2139 `wl'
2140 `wl-other-frame'
2141 For the calendar, use the variable `calendar-setup'.
2142 For BBDB, it is currently only possible to display the matches in
2143 another window."
2144 :group 'org-link-follow
2145 :type '(list
2146 (cons (const vm)
2147 (choice
2148 (const vm-visit-folder)
2149 (const vm-visit-folder-other-window)
2150 (const vm-visit-folder-other-frame)))
2151 (cons (const vm-imap)
2152 (choice
2153 (const vm-visit-imap-folder)
2154 (const vm-visit-imap-folder-other-window)
2155 (const vm-visit-imap-folder-other-frame)))
2156 (cons (const gnus)
2157 (choice
2158 (const gnus)
2159 (const gnus-other-frame)
2160 (const org-gnus-no-new-news)))
2161 (cons (const file)
2162 (choice
2163 (const find-file)
2164 (const find-file-other-window)
2165 (const find-file-other-frame)))
2166 (cons (const wl)
2167 (choice
2168 (const wl)
2169 (const wl-other-frame)))))
2171 (defcustom org-display-internal-link-with-indirect-buffer nil
2172 "Non-nil means use indirect buffer to display infile links.
2173 Activating internal links (from one location in a file to another location
2174 in the same file) normally just jumps to the location. When the link is
2175 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2176 is displayed in
2177 another window. When this option is set, the other window actually displays
2178 an indirect buffer clone of the current buffer, to avoid any visibility
2179 changes to the current buffer."
2180 :group 'org-link-follow
2181 :type 'boolean)
2183 (defcustom org-open-non-existing-files nil
2184 "Non-nil means `org-open-file' will open non-existing files.
2185 When nil, an error will be generated.
2186 This variable applies only to external applications because they
2187 might choke on non-existing files. If the link is to a file that
2188 will be opened in Emacs, the variable is ignored."
2189 :group 'org-link-follow
2190 :type 'boolean)
2192 (defcustom org-open-directory-means-index-dot-org nil
2193 "Non-nil means a link to a directory really means to index.org.
2194 When nil, following a directory link will run dired or open a finder/explorer
2195 window on that directory."
2196 :group 'org-link-follow
2197 :type 'boolean)
2199 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2200 "Non-nil means ask for confirmation before executing shell links.
2201 Shell links can be dangerous: just think about a link
2203 [[shell:rm -rf ~/*][Google Search]]
2205 This link would show up in your Org document as \"Google Search\",
2206 but really it would remove your entire home directory.
2207 Therefore we advise against setting this variable to nil.
2208 Just change it to `y-or-n-p' if you want to confirm with a
2209 single keystroke rather than having to type \"yes\"."
2210 :group 'org-link-follow
2211 :type '(choice
2212 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2213 (const :tag "with y-or-n (faster)" y-or-n-p)
2214 (const :tag "no confirmation (dangerous)" nil)))
2215 (put 'org-confirm-shell-link-function
2216 'safe-local-variable
2217 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2219 (defcustom org-confirm-shell-link-not-regexp ""
2220 "A regexp to skip confirmation for shell links."
2221 :group 'org-link-follow
2222 :version "24.1"
2223 :type 'regexp)
2225 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2226 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2227 Elisp links can be dangerous: just think about a link
2229 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2231 This link would show up in your Org document as \"Google Search\",
2232 but really it would remove your entire home directory.
2233 Therefore we advise against setting this variable to nil.
2234 Just change it to `y-or-n-p' if you want to confirm with a
2235 single keystroke rather than having to type \"yes\"."
2236 :group 'org-link-follow
2237 :type '(choice
2238 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2239 (const :tag "with y-or-n (faster)" y-or-n-p)
2240 (const :tag "no confirmation (dangerous)" nil)))
2241 (put 'org-confirm-shell-link-function
2242 'safe-local-variable
2243 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2245 (defcustom org-confirm-elisp-link-not-regexp ""
2246 "A regexp to skip confirmation for Elisp links."
2247 :group 'org-link-follow
2248 :version "24.1"
2249 :type 'regexp)
2251 (defconst org-file-apps-defaults-gnu
2252 '((remote . emacs)
2253 (system . mailcap)
2254 (t . mailcap))
2255 "Default file applications on a UNIX or GNU/Linux system.
2256 See `org-file-apps'.")
2258 (defconst org-file-apps-defaults-macosx
2259 '((remote . emacs)
2260 (system . "open %s")
2261 ("ps.gz" . "gv %s")
2262 ("eps.gz" . "gv %s")
2263 ("dvi" . "xdvi %s")
2264 ("fig" . "xfig %s")
2265 (t . "open %s"))
2266 "Default file applications on a macOS system.
2267 The system \"open\" is known as a default, but we use X11 applications
2268 for some files for which the OS does not have a good default.
2269 See `org-file-apps'.")
2271 (defconst org-file-apps-defaults-windowsnt
2272 (list '(remote . emacs)
2273 (cons 'system (lambda (file _path)
2274 (with-no-warnings (w32-shell-execute "open" file))))
2275 (cons t (lambda (file _path)
2276 (with-no-warnings (w32-shell-execute "open" file)))))
2277 "Default file applications on a Windows NT system.
2278 The system \"open\" is used for most files.
2279 See `org-file-apps'.")
2281 (defcustom org-file-apps
2282 '((auto-mode . emacs)
2283 ("\\.mm\\'" . default)
2284 ("\\.x?html?\\'" . default)
2285 ("\\.pdf\\'" . default))
2286 "External applications for opening `file:path' items in a document.
2287 \\<org-mode-map>\
2289 Org mode uses system defaults for different file types, but
2290 you can use this variable to set the application for a given file
2291 extension. The entries in this list are cons cells where the car identifies
2292 files and the cdr the corresponding command.
2294 Possible values for the file identifier are:
2296 \"string\" A string as a file identifier can be interpreted in different
2297 ways, depending on its contents:
2299 - Alphanumeric characters only:
2300 Match links with this file extension.
2301 Example: (\"pdf\" . \"evince %s\")
2302 to open PDFs with evince.
2304 - Regular expression: Match links where the
2305 filename matches the regexp. If you want to
2306 use groups here, use shy groups.
2308 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2309 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2310 to open *.html and *.xhtml with firefox.
2312 - Regular expression which contains (non-shy) groups:
2313 Match links where the whole link, including \"::\", and
2314 anything after that, matches the regexp.
2315 In a custom command string, %1, %2, etc. are replaced with
2316 the parts of the link that were matched by the groups.
2317 For backwards compatibility, if a command string is given
2318 that does not use any of the group matches, this case is
2319 handled identically to the second one (i.e. match against
2320 file name only).
2321 In a custom function, you can access the group matches with
2322 (match-string n link).
2324 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2325 \"evince -p %1 %s\")
2326 to open [[file:document.pdf::5]] with evince at page 5.
2328 `directory' Matches a directory
2329 `remote' Matches a remote file, accessible through tramp or efs.
2330 Remote files most likely should be visited through Emacs
2331 because external applications cannot handle such paths.
2332 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2333 so all files Emacs knows how to handle. Using this with
2334 command `emacs' will open most files in Emacs. Beware that this
2335 will also open html files inside Emacs, unless you add
2336 (\"html\" . default) to the list as well.
2337 `system' The system command to open files, like `open' on Windows
2338 and macOS, and mailcap under GNU/Linux. This is the command
2339 that will be selected if you call `org-open-at-point' with a
2340 double prefix argument (`\\[universal-argument] \
2341 \\[universal-argument] \\[org-open-at-point]').
2342 t Default for files not matched by any of the other options.
2344 Possible values for the command are:
2346 `emacs' The file will be visited by the current Emacs process.
2347 `default' Use the default application for this file type, which is the
2348 association for t in the list, most likely in the system-specific
2349 part. This can be used to overrule an unwanted setting in the
2350 system-specific variable.
2351 `system' Use the system command for opening files, like \"open\".
2352 This command is specified by the entry whose car is `system'.
2353 Most likely, the system-specific version of this variable
2354 does define this command, but you can overrule/replace it
2355 here.
2356 `mailcap' Use command specified in the mailcaps.
2357 string A command to be executed by a shell; %s will be replaced
2358 by the path to the file.
2359 function A Lisp function, which will be called with two arguments:
2360 the file path and the original link string, without the
2361 \"file:\" prefix.
2363 For more examples, see the system specific constants
2364 `org-file-apps-defaults-macosx'
2365 `org-file-apps-defaults-windowsnt'
2366 `org-file-apps-defaults-gnu'."
2367 :group 'org-link-follow
2368 :type '(repeat
2369 (cons (choice :value ""
2370 (string :tag "Extension")
2371 (const :tag "System command to open files" system)
2372 (const :tag "Default for unrecognized files" t)
2373 (const :tag "Remote file" remote)
2374 (const :tag "Links to a directory" directory)
2375 (const :tag "Any files that have Emacs modes"
2376 auto-mode))
2377 (choice :value ""
2378 (const :tag "Visit with Emacs" emacs)
2379 (const :tag "Use default" default)
2380 (const :tag "Use the system command" system)
2381 (string :tag "Command")
2382 (function :tag "Function")))))
2384 (defcustom org-doi-server-url "http://dx.doi.org/"
2385 "The URL of the DOI server."
2386 :type 'string
2387 :version "24.3"
2388 :group 'org-link-follow)
2390 (defgroup org-refile nil
2391 "Options concerning refiling entries in Org mode."
2392 :tag "Org Refile"
2393 :group 'org)
2395 (defcustom org-directory "~/org"
2396 "Directory with Org files.
2397 This is just a default location to look for Org files. There is no need
2398 at all to put your files into this directory. It is used in the
2399 following situations:
2401 1. When a capture template specifies a target file that is not an
2402 absolute path. The path will then be interpreted relative to
2403 `org-directory'
2404 2. When the value of variable `org-agenda-files' is a single file, any
2405 relative paths in this file will be taken as relative to
2406 `org-directory'."
2407 :group 'org-refile
2408 :group 'org-capture
2409 :type 'directory)
2411 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2412 "Default target for storing notes.
2413 Used as a fall back file for org-capture.el, for templates that
2414 do not specify a target file."
2415 :group 'org-refile
2416 :group 'org-capture
2417 :type 'file)
2419 (defcustom org-goto-interface 'outline
2420 "The default interface to be used for `org-goto'.
2421 Allowed values are:
2422 outline The interface shows an outline of the relevant file
2423 and the correct heading is found by moving through
2424 the outline or by searching with incremental search.
2425 outline-path-completion Headlines in the current buffer are offered via
2426 completion. This is the interface also used by
2427 the refile command."
2428 :group 'org-refile
2429 :type '(choice
2430 (const :tag "Outline" outline)
2431 (const :tag "Outline-path-completion" outline-path-completion)))
2433 (defcustom org-goto-max-level 5
2434 "Maximum target level when running `org-goto' with refile interface."
2435 :group 'org-refile
2436 :type 'integer)
2438 (defcustom org-reverse-note-order nil
2439 "Non-nil means store new notes at the beginning of a file or entry.
2440 When nil, new notes will be filed to the end of a file or entry.
2441 This can also be a list with cons cells of regular expressions that
2442 are matched against file names, and values."
2443 :group 'org-capture
2444 :group 'org-refile
2445 :type '(choice
2446 (const :tag "Reverse always" t)
2447 (const :tag "Reverse never" nil)
2448 (repeat :tag "By file name regexp"
2449 (cons regexp boolean))))
2451 (defcustom org-log-refile nil
2452 "Information to record when a task is refiled.
2454 Possible values are:
2456 nil Don't add anything
2457 time Add a time stamp to the task
2458 note Prompt for a note and add it with template `org-log-note-headings'
2460 This option can also be set with on a per-file-basis with
2462 #+STARTUP: nologrefile
2463 #+STARTUP: logrefile
2464 #+STARTUP: lognoterefile
2466 You can have local logging settings for a subtree by setting the LOGGING
2467 property to one or more of these keywords.
2469 When bulk-refiling from the agenda, the value `note' is forbidden and
2470 will temporarily be changed to `time'."
2471 :group 'org-refile
2472 :group 'org-progress
2473 :version "24.1"
2474 :type '(choice
2475 (const :tag "No logging" nil)
2476 (const :tag "Record timestamp" time)
2477 (const :tag "Record timestamp with note." note)))
2479 (defcustom org-refile-targets nil
2480 "Targets for refiling entries with `\\[org-refile]'.
2481 This is a list of cons cells. Each cell contains:
2482 - a specification of the files to be considered, either a list of files,
2483 or a symbol whose function or variable value will be used to retrieve
2484 a file name or a list of file names. If you use `org-agenda-files' for
2485 that, all agenda files will be scanned for targets. Nil means consider
2486 headings in the current buffer.
2487 - A specification of how to find candidate refile targets. This may be
2488 any of:
2489 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2490 This tag has to be present in all target headlines, inheritance will
2491 not be considered.
2492 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2493 todo keyword.
2494 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2495 headlines that are refiling targets.
2496 - a cons cell (:level . N). Any headline of level N is considered a target.
2497 Note that, when `org-odd-levels-only' is set, level corresponds to
2498 order in hierarchy, not to the number of stars.
2499 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2500 Note that, when `org-odd-levels-only' is set, level corresponds to
2501 order in hierarchy, not to the number of stars.
2503 Each element of this list generates a set of possible targets.
2504 The union of these sets is presented (with completion) to
2505 the user by `org-refile'.
2507 You can set the variable `org-refile-target-verify-function' to a function
2508 to verify each headline found by the simple criteria above.
2510 When this variable is nil, all top-level headlines in the current buffer
2511 are used, equivalent to the value `((nil . (:level . 1))'."
2512 :group 'org-refile
2513 :type '(repeat
2514 (cons
2515 (choice :value org-agenda-files
2516 (const :tag "All agenda files" org-agenda-files)
2517 (const :tag "Current buffer" nil)
2518 (function) (variable) (file))
2519 (choice :tag "Identify target headline by"
2520 (cons :tag "Specific tag" (const :value :tag) (string))
2521 (cons :tag "TODO keyword" (const :value :todo) (string))
2522 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2523 (cons :tag "Level number" (const :value :level) (integer))
2524 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2526 (defcustom org-refile-target-verify-function nil
2527 "Function to verify if the headline at point should be a refile target.
2528 The function will be called without arguments, with point at the
2529 beginning of the headline. It should return t and leave point
2530 where it is if the headline is a valid target for refiling.
2532 If the target should not be selected, the function must return nil.
2533 In addition to this, it may move point to a place from where the search
2534 should be continued. For example, the function may decide that the entire
2535 subtree of the current entry should be excluded and move point to the end
2536 of the subtree."
2537 :group 'org-refile
2538 :type '(choice
2539 (const nil)
2540 (function)))
2542 (defcustom org-refile-use-cache nil
2543 "Non-nil means cache refile targets to speed up the process.
2544 \\<org-mode-map>\
2545 The cache for a particular file will be updated automatically when
2546 the buffer has been killed, or when any of the marker used for flagging
2547 refile targets no longer points at a live buffer.
2548 If you have added new entries to a buffer that might themselves be targets,
2549 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2550 if you find that easier, \
2551 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2552 \\[org-refile]'."
2553 :group 'org-refile
2554 :version "24.1"
2555 :type 'boolean)
2557 (defcustom org-refile-use-outline-path nil
2558 "Non-nil means provide refile targets as paths.
2559 So a level 3 headline will be available as level1/level2/level3.
2561 When the value is `file', also include the file name (without directory)
2562 into the path. In this case, you can also stop the completion after
2563 the file name, to get entries inserted as top level in the file.
2565 When `full-file-path', include the full file path.
2567 When `buffer-name', use the buffer name."
2568 :group 'org-refile
2569 :type '(choice
2570 (const :tag "Not" nil)
2571 (const :tag "Yes" t)
2572 (const :tag "Start with file name" file)
2573 (const :tag "Start with full file path" full-file-path)
2574 (const :tag "Start with buffer name" buffer-name)))
2576 (defcustom org-outline-path-complete-in-steps t
2577 "Non-nil means complete the outline path in hierarchical steps.
2578 When Org uses the refile interface to select an outline path (see
2579 `org-refile-use-outline-path'), the completion of the path can be
2580 done in a single go, or it can be done in steps down the headline
2581 hierarchy. Going in steps is probably the best if you do not use
2582 a special completion package like `ido' or `icicles'. However,
2583 when using these packages, going in one step can be very fast,
2584 while still showing the whole path to the entry."
2585 :group 'org-refile
2586 :type 'boolean)
2588 (defcustom org-refile-allow-creating-parent-nodes nil
2589 "Non-nil means allow the creation of new nodes as refile targets.
2590 New nodes are then created by adding \"/new node name\" to the completion
2591 of an existing node. When the value of this variable is `confirm',
2592 new node creation must be confirmed by the user (recommended).
2593 When nil, the completion must match an existing entry.
2595 Note that, if the new heading is not seen by the criteria
2596 listed in `org-refile-targets', multiple instances of the same
2597 heading would be created by trying again to file under the new
2598 heading."
2599 :group 'org-refile
2600 :type '(choice
2601 (const :tag "Never" nil)
2602 (const :tag "Always" t)
2603 (const :tag "Prompt for confirmation" confirm)))
2605 (defcustom org-refile-active-region-within-subtree nil
2606 "Non-nil means also refile active region within a subtree.
2608 By default `org-refile' doesn't allow refiling regions if they
2609 don't contain a set of subtrees, but it might be convenient to
2610 do so sometimes: in that case, the first line of the region is
2611 converted to a headline before refiling."
2612 :group 'org-refile
2613 :version "24.1"
2614 :type 'boolean)
2616 (defgroup org-todo nil
2617 "Options concerning TODO items in Org mode."
2618 :tag "Org TODO"
2619 :group 'org)
2621 (defgroup org-progress nil
2622 "Options concerning Progress logging in Org mode."
2623 :tag "Org Progress"
2624 :group 'org-time)
2626 (defvar org-todo-interpretation-widgets
2627 '((:tag "Sequence (cycling hits every state)" sequence)
2628 (:tag "Type (cycling directly to DONE)" type))
2629 "The available interpretation symbols for customizing `org-todo-keywords'.
2630 Interested libraries should add to this list.")
2632 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2633 "List of TODO entry keyword sequences and their interpretation.
2634 \\<org-mode-map>This is a list of sequences.
2636 Each sequence starts with a symbol, either `sequence' or `type',
2637 indicating if the keywords should be interpreted as a sequence of
2638 action steps, or as different types of TODO items. The first
2639 keywords are states requiring action - these states will select a headline
2640 for inclusion into the global TODO list Org produces. If one of the
2641 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2642 signify that no further action is necessary. If \"|\" is not found,
2643 the last keyword is treated as the only DONE state of the sequence.
2645 The command `\\[org-todo]' cycles an entry through these states, and one
2646 additional state where no keyword is present. For details about this
2647 cycling, see the manual.
2649 TODO keywords and interpretation can also be set on a per-file basis with
2650 the special #+SEQ_TODO and #+TYP_TODO lines.
2652 Each keyword can optionally specify a character for fast state selection
2653 \(in combination with the variable `org-use-fast-todo-selection')
2654 and specifiers for state change logging, using the same syntax that
2655 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2656 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2657 indicates to record a time stamp each time this state is selected.
2659 Each keyword may also specify if a timestamp or a note should be
2660 recorded when entering or leaving the state, by adding additional
2661 characters in the parenthesis after the keyword. This looks like this:
2662 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2663 record only the time of the state change. With X and Y being either
2664 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2665 Y when leaving the state if and only if the *target* state does not
2666 define X. You may omit any of the fast-selection key or X or /Y,
2667 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2669 For backward compatibility, this variable may also be just a list
2670 of keywords. In this case the interpretation (sequence or type) will be
2671 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2672 :group 'org-todo
2673 :group 'org-keywords
2674 :type '(choice
2675 (repeat :tag "Old syntax, just keywords"
2676 (string :tag "Keyword"))
2677 (repeat :tag "New syntax"
2678 (cons
2679 (choice
2680 :tag "Interpretation"
2681 ;;Quick and dirty way to see
2682 ;;`org-todo-interpretations'. This takes the
2683 ;;place of item arguments
2684 :convert-widget
2685 (lambda (widget)
2686 (widget-put widget
2687 :args (mapcar
2688 (lambda (x)
2689 (widget-convert
2690 (cons 'const x)))
2691 org-todo-interpretation-widgets))
2692 widget))
2693 (repeat
2694 (string :tag "Keyword"))))))
2696 (defvar-local org-todo-keywords-1 nil
2697 "All TODO and DONE keywords active in a buffer.")
2698 (defvar org-todo-keywords-for-agenda nil)
2699 (defvar org-done-keywords-for-agenda nil)
2700 (defvar org-todo-keyword-alist-for-agenda nil)
2701 (defvar org-tag-alist-for-agenda nil
2702 "Alist of all tags from all agenda files.")
2703 (defvar org-tag-groups-alist-for-agenda nil
2704 "Alist of all groups tags from all current agenda files.")
2705 (defvar-local org-tag-groups-alist nil)
2706 (defvar org-agenda-contributing-files nil)
2707 (defvar-local org-current-tag-alist nil
2708 "Alist of all tag groups in current buffer.
2709 This variable takes into consideration `org-tag-alist',
2710 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2711 (defvar-local org-not-done-keywords nil)
2712 (defvar-local org-done-keywords nil)
2713 (defvar-local org-todo-heads nil)
2714 (defvar-local org-todo-sets nil)
2715 (defvar-local org-todo-log-states nil)
2716 (defvar-local org-todo-kwd-alist nil)
2717 (defvar-local org-todo-key-alist nil)
2718 (defvar-local org-todo-key-trigger nil)
2720 (defcustom org-todo-interpretation 'sequence
2721 "Controls how TODO keywords are interpreted.
2722 This variable is in principle obsolete and is only used for
2723 backward compatibility, if the interpretation of todo keywords is
2724 not given already in `org-todo-keywords'. See that variable for
2725 more information."
2726 :group 'org-todo
2727 :group 'org-keywords
2728 :type '(choice (const sequence)
2729 (const type)))
2731 (defcustom org-use-fast-todo-selection t
2732 "\\<org-mode-map>\
2733 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2734 This variable describes if and under what circumstances the cycling
2735 mechanism for TODO keywords will be replaced by a single-key, direct
2736 selection scheme.
2738 When nil, fast selection is never used.
2740 When the symbol `prefix', it will be used when `org-todo' is called
2741 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2742 in an Org buffer, and
2743 `\\[universal-argument] t' in an agenda buffer.
2745 When t, fast selection is used by default. In this case, the prefix
2746 argument forces cycling instead.
2748 In all cases, the special interface is only used if access keys have
2749 actually been assigned by the user, i.e. if keywords in the configuration
2750 are followed by a letter in parenthesis, like TODO(t)."
2751 :group 'org-todo
2752 :type '(choice
2753 (const :tag "Never" nil)
2754 (const :tag "By default" t)
2755 (const :tag "Only with C-u C-c C-t" prefix)))
2757 (defcustom org-provide-todo-statistics t
2758 "Non-nil means update todo statistics after insert and toggle.
2759 ALL-HEADLINES means update todo statistics by including headlines
2760 with no TODO keyword as well, counting them as not done.
2761 A list of TODO keywords means the same, but skip keywords that are
2762 not in this list.
2763 When set to a list of two lists, the first list contains keywords
2764 to consider as TODO keywords, the second list contains keywords
2765 to consider as DONE keywords.
2767 When this is set, todo statistics is updated in the parent of the
2768 current entry each time a todo state is changed."
2769 :group 'org-todo
2770 :type '(choice
2771 (const :tag "Yes, only for TODO entries" t)
2772 (const :tag "Yes, including all entries" all-headlines)
2773 (repeat :tag "Yes, for TODOs in this list"
2774 (string :tag "TODO keyword"))
2775 (list :tag "Yes, for TODOs and DONEs in these lists"
2776 (repeat (string :tag "TODO keyword"))
2777 (repeat (string :tag "DONE keyword")))
2778 (other :tag "No TODO statistics" nil)))
2780 (defcustom org-hierarchical-todo-statistics t
2781 "Non-nil means TODO statistics covers just direct children.
2782 When nil, all entries in the subtree are considered.
2783 This has only an effect if `org-provide-todo-statistics' is set.
2784 To set this to nil for only a single subtree, use a COOKIE_DATA
2785 property and include the word \"recursive\" into the value."
2786 :group 'org-todo
2787 :type 'boolean)
2789 (defcustom org-after-todo-state-change-hook nil
2790 "Hook which is run after the state of a TODO item was changed.
2791 The new state (a string with a TODO keyword, or nil) is available in the
2792 Lisp variable `org-state'."
2793 :group 'org-todo
2794 :type 'hook)
2796 (defvar org-blocker-hook nil
2797 "Hook for functions that are allowed to block a state change.
2799 Functions in this hook should not modify the buffer.
2800 Each function gets as its single argument a property list,
2801 see `org-trigger-hook' for more information about this list.
2803 If any of the functions in this hook returns nil, the state change
2804 is blocked.")
2806 (defvar org-trigger-hook nil
2807 "Hook for functions that are triggered by a state change.
2809 Each function gets as its single argument a property list with at
2810 least the following elements:
2812 (:type type-of-change :position pos-at-entry-start
2813 :from old-state :to new-state)
2815 Depending on the type, more properties may be present.
2817 This mechanism is currently implemented for:
2819 TODO state changes
2820 ------------------
2821 :type todo-state-change
2822 :from previous state (keyword as a string), or nil, or a symbol
2823 `todo' or `done', to indicate the general type of state.
2824 :to new state, like in :from")
2826 (defcustom org-enforce-todo-dependencies nil
2827 "Non-nil means undone TODO entries will block switching the parent to DONE.
2828 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2829 be blocked if any prior sibling is not yet done.
2830 Finally, if the parent is blocked because of ordered siblings of its own,
2831 the child will also be blocked."
2832 :set (lambda (var val)
2833 (set var val)
2834 (if val
2835 (add-hook 'org-blocker-hook
2836 'org-block-todo-from-children-or-siblings-or-parent)
2837 (remove-hook 'org-blocker-hook
2838 'org-block-todo-from-children-or-siblings-or-parent)))
2839 :group 'org-todo
2840 :type 'boolean)
2842 (defcustom org-enforce-todo-checkbox-dependencies nil
2843 "Non-nil means unchecked boxes will block switching the parent to DONE.
2844 When this is nil, checkboxes have no influence on switching TODO states.
2845 When non-nil, you first need to check off all check boxes before the TODO
2846 entry can be switched to DONE.
2847 This variable needs to be set before org.el is loaded, and you need to
2848 restart Emacs after a change to make the change effective. The only way
2849 to change is while Emacs is running is through the customize interface."
2850 :set (lambda (var val)
2851 (set var val)
2852 (if val
2853 (add-hook 'org-blocker-hook
2854 'org-block-todo-from-checkboxes)
2855 (remove-hook 'org-blocker-hook
2856 'org-block-todo-from-checkboxes)))
2857 :group 'org-todo
2858 :type 'boolean)
2860 (defcustom org-treat-insert-todo-heading-as-state-change nil
2861 "Non-nil means inserting a TODO heading is treated as state change.
2862 So when the command `\\[org-insert-todo-heading]' is used, state change
2863 logging will apply if appropriate. When nil, the new TODO item will
2864 be inserted directly, and no logging will take place."
2865 :group 'org-todo
2866 :type 'boolean)
2868 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2869 "Non-nil means switching TODO states with S-cursor counts as state change.
2870 This is the default behavior. However, setting this to nil allows a
2871 convenient way to select a TODO state and bypass any logging associated
2872 with that."
2873 :group 'org-todo
2874 :type 'boolean)
2876 (defcustom org-todo-state-tags-triggers nil
2877 "Tag changes that should be triggered by TODO state changes.
2878 This is a list. Each entry is
2880 (state-change (tag . flag) .......)
2882 State-change can be a string with a state, and empty string to indicate the
2883 state that has no TODO keyword, or it can be one of the symbols `todo'
2884 or `done', meaning any not-done or done state, respectively."
2885 :group 'org-todo
2886 :group 'org-tags
2887 :type '(repeat
2888 (cons (choice :tag "When changing to"
2889 (const :tag "Not-done state" todo)
2890 (const :tag "Done state" done)
2891 (string :tag "State"))
2892 (repeat
2893 (cons :tag "Tag action"
2894 (string :tag "Tag")
2895 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2897 (defcustom org-log-done nil
2898 "Information to record when a task moves to the DONE state.
2900 Possible values are:
2902 nil Don't add anything, just change the keyword
2903 time Add a time stamp to the task
2904 note Prompt for a note and add it with template `org-log-note-headings'
2906 This option can also be set with on a per-file-basis with
2908 #+STARTUP: nologdone
2909 #+STARTUP: logdone
2910 #+STARTUP: lognotedone
2912 You can have local logging settings for a subtree by setting the LOGGING
2913 property to one or more of these keywords."
2914 :group 'org-todo
2915 :group 'org-progress
2916 :type '(choice
2917 (const :tag "No logging" nil)
2918 (const :tag "Record CLOSED timestamp" time)
2919 (const :tag "Record CLOSED timestamp with note." note)))
2921 ;; Normalize old uses of org-log-done.
2922 (cond
2923 ((eq org-log-done t) (setq org-log-done 'time))
2924 ((and (listp org-log-done) (memq 'done org-log-done))
2925 (setq org-log-done 'note)))
2927 (defcustom org-log-reschedule nil
2928 "Information to record when the scheduling date of a tasks is modified.
2930 Possible values are:
2932 nil Don't add anything, just change the date
2933 time Add a time stamp to the task
2934 note Prompt for a note and add it with template `org-log-note-headings'
2936 This option can also be set with on a per-file-basis with
2938 #+STARTUP: nologreschedule
2939 #+STARTUP: logreschedule
2940 #+STARTUP: lognotereschedule"
2941 :group 'org-todo
2942 :group 'org-progress
2943 :type '(choice
2944 (const :tag "No logging" nil)
2945 (const :tag "Record timestamp" time)
2946 (const :tag "Record timestamp with note." note)))
2948 (defcustom org-log-redeadline nil
2949 "Information to record when the deadline date of a tasks is modified.
2951 Possible values are:
2953 nil Don't add anything, just change the date
2954 time Add a time stamp to the task
2955 note Prompt for a note and add it with template `org-log-note-headings'
2957 This option can also be set with on a per-file-basis with
2959 #+STARTUP: nologredeadline
2960 #+STARTUP: logredeadline
2961 #+STARTUP: lognoteredeadline
2963 You can have local logging settings for a subtree by setting the LOGGING
2964 property to one or more of these keywords."
2965 :group 'org-todo
2966 :group 'org-progress
2967 :type '(choice
2968 (const :tag "No logging" nil)
2969 (const :tag "Record timestamp" time)
2970 (const :tag "Record timestamp with note." note)))
2972 (defcustom org-log-note-clock-out nil
2973 "Non-nil means record a note when clocking out of an item.
2974 This can also be configured on a per-file basis by adding one of
2975 the following lines anywhere in the buffer:
2977 #+STARTUP: lognoteclock-out
2978 #+STARTUP: nolognoteclock-out"
2979 :group 'org-todo
2980 :group 'org-progress
2981 :type 'boolean)
2983 (defcustom org-log-done-with-time t
2984 "Non-nil means the CLOSED time stamp will contain date and time.
2985 When nil, only the date will be recorded."
2986 :group 'org-progress
2987 :type 'boolean)
2989 (defcustom org-log-note-headings
2990 '((done . "CLOSING NOTE %t")
2991 (state . "State %-12s from %-12S %t")
2992 (note . "Note taken on %t")
2993 (reschedule . "Rescheduled from %S on %t")
2994 (delschedule . "Not scheduled, was %S on %t")
2995 (redeadline . "New deadline from %S on %t")
2996 (deldeadline . "Removed deadline, was %S on %t")
2997 (refile . "Refiled on %t")
2998 (clock-out . ""))
2999 "Headings for notes added to entries.
3001 The value is an alist, with the car being a symbol indicating the
3002 note context, and the cdr is the heading to be used. The heading
3003 may also be the empty string. The following placeholders can be
3004 used:
3006 %t a time stamp.
3007 %T an active time stamp instead the default inactive one
3008 %d a short-format time stamp.
3009 %D an active short-format time stamp.
3010 %s the new TODO state or time stamp (inactive), in double quotes.
3011 %S the old TODO state or time stamp (inactive), in double quotes.
3012 %u the user name.
3013 %U full user name.
3015 In fact, it is not a good idea to change the `state' entry,
3016 because Agenda Log mode depends on the format of these entries."
3017 :group 'org-todo
3018 :group 'org-progress
3019 :type '(list :greedy t
3020 (cons (const :tag "Heading when closing an item" done) string)
3021 (cons (const :tag
3022 "Heading when changing todo state (todo sequence only)"
3023 state) string)
3024 (cons (const :tag "Heading when just taking a note" note) string)
3025 (cons (const :tag "Heading when rescheduling" reschedule) string)
3026 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3027 (cons (const :tag "Heading when changing deadline" redeadline) string)
3028 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3029 (cons (const :tag "Heading when refiling" refile) string)
3030 (cons (const :tag "Heading when clocking out" clock-out) string)))
3032 (unless (assq 'note org-log-note-headings)
3033 (push '(note . "%t") org-log-note-headings))
3035 (defcustom org-log-into-drawer nil
3036 "Non-nil means insert state change notes and time stamps into a drawer.
3037 When nil, state changes notes will be inserted after the headline and
3038 any scheduling and clock lines, but not inside a drawer.
3040 The value of this variable should be the name of the drawer to use.
3041 LOGBOOK is proposed as the default drawer for this purpose, you can
3042 also set this to a string to define the drawer of your choice.
3044 A value of t is also allowed, representing \"LOGBOOK\".
3046 A value of t or nil can also be set with on a per-file-basis with
3048 #+STARTUP: logdrawer
3049 #+STARTUP: nologdrawer
3051 If this variable is set, `org-log-state-notes-insert-after-drawers'
3052 will be ignored.
3054 You can set the property LOG_INTO_DRAWER to overrule this setting for
3055 a subtree.
3057 Do not check directly this variable in a Lisp program. Call
3058 function `org-log-into-drawer' instead."
3059 :group 'org-todo
3060 :group 'org-progress
3061 :type '(choice
3062 (const :tag "Not into a drawer" nil)
3063 (const :tag "LOGBOOK" t)
3064 (string :tag "Other")))
3066 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3068 (defun org-log-into-drawer ()
3069 "Name of the log drawer, as a string, or nil.
3070 This is the value of `org-log-into-drawer'. However, if the
3071 current entry has or inherits a LOG_INTO_DRAWER property, it will
3072 be used instead of the default value."
3073 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3074 (cond ((equal p "nil") nil)
3075 ((equal p "t") "LOGBOOK")
3076 ((stringp p) p)
3077 (p "LOGBOOK")
3078 ((stringp org-log-into-drawer) org-log-into-drawer)
3079 (org-log-into-drawer "LOGBOOK"))))
3081 (defcustom org-log-state-notes-insert-after-drawers nil
3082 "Non-nil means insert state change notes after any drawers in entry.
3083 Only the drawers that *immediately* follow the headline and the
3084 deadline/scheduled line are skipped.
3085 When nil, insert notes right after the heading and perhaps the line
3086 with deadline/scheduling if present.
3088 This variable will have no effect if `org-log-into-drawer' is
3089 set."
3090 :group 'org-todo
3091 :group 'org-progress
3092 :type 'boolean)
3094 (defcustom org-log-states-order-reversed t
3095 "Non-nil means the latest state note will be directly after heading.
3096 When nil, the state change notes will be ordered according to time.
3098 This option can also be set with on a per-file-basis with
3100 #+STARTUP: logstatesreversed
3101 #+STARTUP: nologstatesreversed"
3102 :group 'org-todo
3103 :group 'org-progress
3104 :type 'boolean)
3106 (defcustom org-todo-repeat-to-state nil
3107 "The TODO state to which a repeater should return the repeating task.
3108 By default this is the first task in a TODO sequence, or the previous state
3109 in a TODO_TYP set. But you can specify another task here.
3110 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3111 :group 'org-todo
3112 :version "24.1"
3113 :type '(choice (const :tag "Head of sequence" nil)
3114 (string :tag "Specific state")))
3116 (defcustom org-log-repeat 'time
3117 "Non-nil means record moving through the DONE state when triggering repeat.
3118 An auto-repeating task is immediately switched back to TODO when
3119 marked DONE. If you are not logging state changes (by adding \"@\"
3120 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3121 record a closing note, there will be no record of the task moving
3122 through DONE. This variable forces taking a note anyway.
3124 nil Don't force a record
3125 time Record a time stamp
3126 note Prompt for a note and add it with template `org-log-note-headings'
3128 This option can also be set with on a per-file-basis with
3130 #+STARTUP: nologrepeat
3131 #+STARTUP: logrepeat
3132 #+STARTUP: lognoterepeat
3134 You can have local logging settings for a subtree by setting the LOGGING
3135 property to one or more of these keywords."
3136 :group 'org-todo
3137 :group 'org-progress
3138 :type '(choice
3139 (const :tag "Don't force a record" nil)
3140 (const :tag "Force recording the DONE state" time)
3141 (const :tag "Force recording a note with the DONE state" note)))
3144 (defgroup org-priorities nil
3145 "Priorities in Org mode."
3146 :tag "Org Priorities"
3147 :group 'org-todo)
3149 (defcustom org-enable-priority-commands t
3150 "Non-nil means priority commands are active.
3151 When nil, these commands will be disabled, so that you never accidentally
3152 set a priority."
3153 :group 'org-priorities
3154 :type 'boolean)
3156 (defcustom org-highest-priority ?A
3157 "The highest priority of TODO items. A character like ?A, ?B etc.
3158 Must have a smaller ASCII number than `org-lowest-priority'."
3159 :group 'org-priorities
3160 :type 'character)
3162 (defcustom org-lowest-priority ?C
3163 "The lowest priority of TODO items. A character like ?A, ?B etc.
3164 Must have a larger ASCII number than `org-highest-priority'."
3165 :group 'org-priorities
3166 :type 'character)
3168 (defcustom org-default-priority ?B
3169 "The default priority of TODO items.
3170 This is the priority an item gets if no explicit priority is given.
3171 When starting to cycle on an empty priority the first step in the cycle
3172 depends on `org-priority-start-cycle-with-default'. The resulting first
3173 step priority must not exceed the range from `org-highest-priority' to
3174 `org-lowest-priority' which means that `org-default-priority' has to be
3175 in this range exclusive or inclusive the range boundaries. Else the
3176 first step refuses to set the default and the second will fall back
3177 to (depending on the command used) the highest or lowest priority."
3178 :group 'org-priorities
3179 :type 'character)
3181 (defcustom org-priority-start-cycle-with-default t
3182 "Non-nil means start with default priority when starting to cycle.
3183 When this is nil, the first step in the cycle will be (depending on the
3184 command used) one higher or lower than the default priority.
3185 See also `org-default-priority'."
3186 :group 'org-priorities
3187 :type 'boolean)
3189 (defcustom org-get-priority-function nil
3190 "Function to extract the priority from a string.
3191 The string is normally the headline. If this is nil Org computes the
3192 priority from the priority cookie like [#A] in the headline. It returns
3193 an integer, increasing by 1000 for each priority level.
3194 The user can set a different function here, which should take a string
3195 as an argument and return the numeric priority."
3196 :group 'org-priorities
3197 :version "24.1"
3198 :type '(choice
3199 (const nil)
3200 (function)))
3202 (defgroup org-time nil
3203 "Options concerning time stamps and deadlines in Org mode."
3204 :tag "Org Time"
3205 :group 'org)
3207 (defcustom org-time-stamp-rounding-minutes '(0 5)
3208 "Number of minutes to round time stamps to.
3209 \\<org-mode-map>\
3210 These are two values, the first applies when first creating a time stamp.
3211 The second applies when changing it with the commands `S-up' and `S-down'.
3212 When changing the time stamp, this means that it will change in steps
3213 of N minutes, as given by the second value.
3215 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3216 numbers should be factors of 60, so for example 5, 10, 15.
3218 When this is larger than 1, you can still force an exact time stamp by using
3219 a double prefix argument to a time stamp command like \
3220 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3221 and by using a prefix arg to `S-up/down' to specify the exact number
3222 of minutes to shift."
3223 :group 'org-time
3224 :get (lambda (var) ; Make sure both elements are there
3225 (if (integerp (default-value var))
3226 (list (default-value var) 5)
3227 (default-value var)))
3228 :type '(list
3229 (integer :tag "when inserting times")
3230 (integer :tag "when modifying times")))
3232 ;; Normalize old customizations of this variable.
3233 (when (integerp org-time-stamp-rounding-minutes)
3234 (setq org-time-stamp-rounding-minutes
3235 (list org-time-stamp-rounding-minutes
3236 org-time-stamp-rounding-minutes)))
3238 (defcustom org-display-custom-times nil
3239 "Non-nil means overlay custom formats over all time stamps.
3240 The formats are defined through the variable `org-time-stamp-custom-formats'.
3241 To turn this on on a per-file basis, insert anywhere in the file:
3242 #+STARTUP: customtime"
3243 :group 'org-time
3244 :set 'set-default
3245 :type 'sexp)
3246 (make-variable-buffer-local 'org-display-custom-times)
3248 (defcustom org-time-stamp-custom-formats
3249 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3250 "Custom formats for time stamps. See `format-time-string' for the syntax.
3251 These are overlaid over the default ISO format if the variable
3252 `org-display-custom-times' is set. Time like %H:%M should be at the
3253 end of the second format. The custom formats are also honored by export
3254 commands, if custom time display is turned on at the time of export."
3255 :group 'org-time
3256 :type 'sexp)
3258 (defun org-time-stamp-format (&optional long inactive)
3259 "Get the right format for a time string."
3260 (let ((f (if long (cdr org-time-stamp-formats)
3261 (car org-time-stamp-formats))))
3262 (if inactive
3263 (concat "[" (substring f 1 -1) "]")
3264 f)))
3266 (defcustom org-deadline-warning-days 14
3267 "Number of days before expiration during which a deadline becomes active.
3268 This variable governs the display in sparse trees and in the agenda.
3269 When 0 or negative, it means use this number (the absolute value of it)
3270 even if a deadline has a different individual lead time specified.
3272 Custom commands can set this variable in the options section."
3273 :group 'org-time
3274 :group 'org-agenda-daily/weekly
3275 :type 'integer)
3277 (defcustom org-scheduled-delay-days 0
3278 "Number of days before a scheduled item becomes active.
3279 This variable governs the display in sparse trees and in the agenda.
3280 The default value (i.e. 0) means: don't delay scheduled item.
3281 When negative, it means use this number (the absolute value of it)
3282 even if a scheduled item has a different individual delay time
3283 specified.
3285 Custom commands can set this variable in the options section."
3286 :group 'org-time
3287 :group 'org-agenda-daily/weekly
3288 :version "24.4"
3289 :package-version '(Org . "8.0")
3290 :type 'integer)
3292 (defcustom org-read-date-prefer-future t
3293 "Non-nil means assume future for incomplete date input from user.
3294 This affects the following situations:
3295 1. The user gives a month but not a year.
3296 For example, if it is April and you enter \"feb 2\", this will be read
3297 as Feb 2, *next* year. \"May 5\", however, will be this year.
3298 2. The user gives a day, but no month.
3299 For example, if today is the 15th, and you enter \"3\", Org will read
3300 this as the third of *next* month. However, if you enter \"17\",
3301 it will be considered as *this* month.
3303 If you set this variable to the symbol `time', then also the following
3304 will work:
3306 3. If the user gives a time.
3307 If the time is before now, it will be interpreted as tomorrow.
3309 Currently none of this works for ISO week specifications.
3311 When this option is nil, the current day, month and year will always be
3312 used as defaults.
3314 See also `org-agenda-jump-prefer-future'."
3315 :group 'org-time
3316 :type '(choice
3317 (const :tag "Never" nil)
3318 (const :tag "Check month and day" t)
3319 (const :tag "Check month, day, and time" time)))
3321 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3322 "Should the agenda jump command prefer the future for incomplete dates?
3323 The default is to do the same as configured in `org-read-date-prefer-future'.
3324 But you can also set a deviating value here.
3325 This may t or nil, or the symbol `org-read-date-prefer-future'."
3326 :group 'org-agenda
3327 :group 'org-time
3328 :version "24.1"
3329 :type '(choice
3330 (const :tag "Use org-read-date-prefer-future"
3331 org-read-date-prefer-future)
3332 (const :tag "Never" nil)
3333 (const :tag "Always" t)))
3335 (defcustom org-read-date-force-compatible-dates t
3336 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3338 Depending on the system Emacs is running on, certain dates cannot
3339 be represented with the type used internally to represent time.
3340 Dates between 1970-1-1 and 2038-1-1 can always be represented
3341 correctly. Some systems allow for earlier dates, some for later,
3342 some for both. One way to find out it to insert any date into an
3343 Org buffer, putting the cursor on the year and hitting S-up and
3344 S-down to test the range.
3346 When this variable is set to t, the date/time prompt will not let
3347 you specify dates outside the 1970-2037 range, so it is certain that
3348 these dates will work in whatever version of Emacs you are
3349 running, and also that you can move a file from one Emacs implementation
3350 to another. WHenever Org is forcing the year for you, it will display
3351 a message and beep.
3353 When this variable is nil, Org will check if the date is
3354 representable in the specific Emacs implementation you are using.
3355 If not, it will force a year, usually the current year, and beep
3356 to remind you. Currently this setting is not recommended because
3357 the likelihood that you will open your Org files in an Emacs that
3358 has limited date range is not negligible.
3360 A workaround for this problem is to use diary sexp dates for time
3361 stamps outside of this range."
3362 :group 'org-time
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-read-date-display-live t
3367 "Non-nil means display current interpretation of date prompt live.
3368 This display will be in an overlay, in the minibuffer."
3369 :group 'org-time
3370 :type 'boolean)
3372 (defcustom org-read-date-popup-calendar t
3373 "Non-nil means pop up a calendar when prompting for a date.
3374 In the calendar, the date can be selected with mouse-1. However, the
3375 minibuffer will also be active, and you can simply enter the date as well.
3376 When nil, only the minibuffer will be available."
3377 :group 'org-time
3378 :type 'boolean)
3379 (defvaralias 'org-popup-calendar-for-date-prompt
3380 'org-read-date-popup-calendar)
3382 (defcustom org-extend-today-until 0
3383 "The hour when your day really ends. Must be an integer.
3384 This has influence for the following applications:
3385 - When switching the agenda to \"today\". It it is still earlier than
3386 the time given here, the day recognized as TODAY is actually yesterday.
3387 - When a date is read from the user and it is still before the time given
3388 here, the current date and time will be assumed to be yesterday, 23:59.
3389 Also, timestamps inserted in capture templates follow this rule.
3391 IMPORTANT: This is a feature whose implementation is and likely will
3392 remain incomplete. Really, it is only here because past midnight seems to
3393 be the favorite working time of John Wiegley :-)"
3394 :group 'org-time
3395 :type 'integer)
3397 (defcustom org-use-effective-time nil
3398 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3399 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3400 \"effective time\" of any timestamps between midnight and 8am will be
3401 23:59 of the previous day."
3402 :group 'org-time
3403 :version "24.1"
3404 :type 'boolean)
3406 (defcustom org-use-last-clock-out-time-as-effective-time nil
3407 "When non-nil, use the last clock out time for `org-todo'.
3408 Note that this option has precedence over the combined use of
3409 `org-use-effective-time' and `org-extend-today-until'."
3410 :group 'org-time
3411 :version "24.4"
3412 :package-version '(Org . "8.0")
3413 :type 'boolean)
3415 (defcustom org-edit-timestamp-down-means-later nil
3416 "Non-nil means S-down will increase the time in a time stamp.
3417 When nil, S-up will increase."
3418 :group 'org-time
3419 :type 'boolean)
3421 (defcustom org-calendar-follow-timestamp-change t
3422 "Non-nil means make the calendar window follow timestamp changes.
3423 When a timestamp is modified and the calendar window is visible, it will be
3424 moved to the new date."
3425 :group 'org-time
3426 :type 'boolean)
3428 (defgroup org-tags nil
3429 "Options concerning tags in Org mode."
3430 :tag "Org Tags"
3431 :group 'org)
3433 (defcustom org-tag-alist nil
3434 "Default tags available in Org files.
3436 The value of this variable is an alist. Associations either:
3438 (TAG)
3439 (TAG . SELECT)
3440 (SPECIAL)
3442 where TAG is a tag as a string, SELECT is character, used to
3443 select that tag through the fast tag selection interface, and
3444 SPECIAL is one of the following keywords: `:startgroup',
3445 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3446 `:newline'. These keywords are used to define a hierarchy of
3447 tags. See manual for details.
3449 When this variable is nil, Org mode bases tag input on what is
3450 already in the buffer. The value can be overridden locally by
3451 using a TAGS keyword, e.g.,
3453 #+TAGS: tag1 tag2
3455 See also `org-tag-persistent-alist' to sidestep this behavior."
3456 :group 'org-tags
3457 :type '(repeat
3458 (choice
3459 (cons (string :tag "Tag name")
3460 (character :tag "Access char"))
3461 (const :tag "Start radio group" (:startgroup))
3462 (const :tag "Start tag group, non distinct" (:startgrouptag))
3463 (const :tag "Group tags delimiter" (:grouptags))
3464 (const :tag "End radio group" (:endgroup))
3465 (const :tag "End tag group, non distinct" (:endgrouptag))
3466 (const :tag "New line" (:newline)))))
3468 (defcustom org-tag-persistent-alist nil
3469 "Tags always available in Org files.
3471 The value of this variable is an alist. Associations either:
3473 (TAG)
3474 (TAG . SELECT)
3475 (SPECIAL)
3477 where TAG is a tag as a string, SELECT is a character, used to
3478 select that tag through the fast tag selection interface, and
3479 SPECIAL is one of the following keywords: `:startgroup',
3480 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3481 `:newline'. These keywords are used to define a hierarchy of
3482 tags. See manual for details.
3484 Unlike to `org-tag-alist', tags defined in this variable do not
3485 depend on a local TAGS keyword. Instead, to disable these tags
3486 on a per-file basis, insert anywhere in the file:
3488 #+STARTUP: noptag"
3489 :group 'org-tags
3490 :type '(repeat
3491 (choice
3492 (cons (string :tag "Tag name")
3493 (character :tag "Access char"))
3494 (const :tag "Start radio group" (:startgroup))
3495 (const :tag "Start tag group, non distinct" (:startgrouptag))
3496 (const :tag "Group tags delimiter" (:grouptags))
3497 (const :tag "End radio group" (:endgroup))
3498 (const :tag "End tag group, non distinct" (:endgrouptag))
3499 (const :tag "New line" (:newline)))))
3501 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3502 "If non-nil, always offer completion for all tags of all agenda files.
3503 Instead of customizing this variable directly, you might want to
3504 set it locally for capture buffers, because there no list of
3505 tags in that file can be created dynamically (there are none).
3507 (add-hook \\='org-capture-mode-hook
3508 (lambda ()
3509 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3510 :group 'org-tags
3511 :version "24.1"
3512 :type 'boolean)
3514 (defvar org-file-tags nil
3515 "List of tags that can be inherited by all entries in the file.
3516 The tags will be inherited if the variable `org-use-tag-inheritance'
3517 says they should be.
3518 This variable is populated from #+FILETAGS lines.")
3520 (defcustom org-use-fast-tag-selection 'auto
3521 "Non-nil means use fast tag selection scheme.
3522 This is a special interface to select and deselect tags with single keys.
3523 When nil, fast selection is never used.
3524 When the symbol `auto', fast selection is used if and only if selection
3525 characters for tags have been configured, either through the variable
3526 `org-tag-alist' or through a #+TAGS line in the buffer.
3527 When t, fast selection is always used and selection keys are assigned
3528 automatically if necessary."
3529 :group 'org-tags
3530 :type '(choice
3531 (const :tag "Always" t)
3532 (const :tag "Never" nil)
3533 (const :tag "When selection characters are configured" auto)))
3535 (defcustom org-fast-tag-selection-single-key nil
3536 "Non-nil means fast tag selection exits after first change.
3537 When nil, you have to press RET to exit it.
3538 During fast tag selection, you can toggle this flag with `C-c'.
3539 This variable can also have the value `expert'. In this case, the window
3540 displaying the tags menu is not even shown, until you press C-c again."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "No" nil)
3544 (const :tag "Yes" t)
3545 (const :tag "Expert" expert)))
3547 (defvar org-fast-tag-selection-include-todo nil
3548 "Non-nil means fast tags selection interface will also offer TODO states.
3549 This is an undocumented feature, you should not rely on it.")
3551 (defcustom org-tags-column -77
3552 "The column to which tags should be indented in a headline.
3553 If this number is positive, it specifies the column. If it is negative,
3554 it means that the tags should be flushright to that column. For example,
3555 -80 works well for a normal 80 character screen.
3556 When 0, place tags directly after headline text, with only one space in
3557 between."
3558 :group 'org-tags
3559 :type 'integer)
3561 (defcustom org-auto-align-tags t
3562 "Non-nil keeps tags aligned when modifying headlines.
3563 Some operations (i.e. demoting) change the length of a headline and
3564 therefore shift the tags around. With this option turned on, after
3565 each such operation the tags are again aligned to `org-tags-column'."
3566 :group 'org-tags
3567 :type 'boolean)
3569 (defcustom org-use-tag-inheritance t
3570 "Non-nil means tags in levels apply also for sublevels.
3571 When nil, only the tags directly given in a specific line apply there.
3572 This may also be a list of tags that should be inherited, or a regexp that
3573 matches tags that should be inherited. Additional control is possible
3574 with the variable `org-tags-exclude-from-inheritance' which gives an
3575 explicit list of tags to be excluded from inheritance, even if the value of
3576 `org-use-tag-inheritance' would select it for inheritance.
3578 If this option is t, a match early-on in a tree can lead to a large
3579 number of matches in the subtree when constructing the agenda or creating
3580 a sparse tree. If you only want to see the first match in a tree during
3581 a search, check out the variable `org-tags-match-list-sublevels'."
3582 :group 'org-tags
3583 :type '(choice
3584 (const :tag "Not" nil)
3585 (const :tag "Always" t)
3586 (repeat :tag "Specific tags" (string :tag "Tag"))
3587 (regexp :tag "Tags matched by regexp")))
3589 (defcustom org-tags-exclude-from-inheritance nil
3590 "List of tags that should never be inherited.
3591 This is a way to exclude a few tags from inheritance. For way to do
3592 the opposite, to actively allow inheritance for selected tags,
3593 see the variable `org-use-tag-inheritance'."
3594 :group 'org-tags
3595 :type '(repeat (string :tag "Tag")))
3597 (defun org-tag-inherit-p (tag)
3598 "Check if TAG is one that should be inherited."
3599 (cond
3600 ((member tag org-tags-exclude-from-inheritance) nil)
3601 ((eq org-use-tag-inheritance t) t)
3602 ((not org-use-tag-inheritance) nil)
3603 ((stringp org-use-tag-inheritance)
3604 (string-match org-use-tag-inheritance tag))
3605 ((listp org-use-tag-inheritance)
3606 (member tag org-use-tag-inheritance))
3607 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3609 (defcustom org-tags-match-list-sublevels t
3610 "Non-nil means list also sublevels of headlines matching a search.
3611 This variable applies to tags/property searches, and also to stuck
3612 projects because this search is based on a tags match as well.
3614 When set to the symbol `indented', sublevels are indented with
3615 leading dots.
3617 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3618 the sublevels of a headline matching a tag search often also match
3619 the same search. Listing all of them can create very long lists.
3620 Setting this variable to nil causes subtrees of a match to be skipped.
3622 This variable is semi-obsolete and probably should always be true. It
3623 is better to limit inheritance to certain tags using the variables
3624 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3625 :group 'org-tags
3626 :type '(choice
3627 (const :tag "No, don't list them" nil)
3628 (const :tag "Yes, do list them" t)
3629 (const :tag "List them, indented with leading dots" indented)))
3631 (defcustom org-tags-sort-function nil
3632 "When set, tags are sorted using this function as a comparator."
3633 :group 'org-tags
3634 :type '(choice
3635 (const :tag "No sorting" nil)
3636 (const :tag "Alphabetical" string<)
3637 (const :tag "Reverse alphabetical" string>)
3638 (function :tag "Custom function" nil)))
3640 (defvar org-tags-history nil
3641 "History of minibuffer reads for tags.")
3642 (defvar org-last-tags-completion-table nil
3643 "The last used completion table for tags.")
3644 (defvar org-after-tags-change-hook nil
3645 "Hook that is run after the tags in a line have changed.")
3647 (defgroup org-properties nil
3648 "Options concerning properties in Org mode."
3649 :tag "Org Properties"
3650 :group 'org)
3652 (defcustom org-property-format "%-10s %s"
3653 "How property key/value pairs should be formatted by `indent-line'.
3654 When `indent-line' hits a property definition, it will format the line
3655 according to this format, mainly to make sure that the values are
3656 lined-up with respect to each other."
3657 :group 'org-properties
3658 :type 'string)
3660 (defcustom org-properties-postprocess-alist nil
3661 "Alist of properties and functions to adjust inserted values.
3662 Elements of this alist must be of the form
3664 ([string] [function])
3666 where [string] must be a property name and [function] must be a
3667 lambda expression: this lambda expression must take one argument,
3668 the value to adjust, and return the new value as a string.
3670 For example, this element will allow the property \"Remaining\"
3671 to be updated wrt the relation between the \"Effort\" property
3672 and the clock summary:
3674 ((\"Remaining\" (lambda(value)
3675 (let ((clocksum (org-clock-sum-current-item))
3676 (effort (org-duration-to-minutes
3677 (org-entry-get (point) \"Effort\"))))
3678 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3679 :group 'org-properties
3680 :version "24.1"
3681 :type '(alist :key-type (string :tag "Property")
3682 :value-type (function :tag "Function")))
3684 (defcustom org-use-property-inheritance nil
3685 "Non-nil means properties apply also for sublevels.
3687 This setting is chiefly used during property searches. Turning it on can
3688 cause significant overhead when doing a search, which is why it is not
3689 on by default.
3691 When nil, only the properties directly given in the current entry count.
3692 When t, every property is inherited. The value may also be a list of
3693 properties that should have inheritance, or a regular expression matching
3694 properties that should be inherited.
3696 However, note that some special properties use inheritance under special
3697 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3698 and the properties ending in \"_ALL\" when they are used as descriptor
3699 for valid values of a property.
3701 Note for programmers:
3702 When querying an entry with `org-entry-get', you can control if inheritance
3703 should be used. By default, `org-entry-get' looks only at the local
3704 properties. You can request inheritance by setting the inherit argument
3705 to t (to force inheritance) or to `selective' (to respect the setting
3706 in this variable)."
3707 :group 'org-properties
3708 :type '(choice
3709 (const :tag "Not" nil)
3710 (const :tag "Always" t)
3711 (repeat :tag "Specific properties" (string :tag "Property"))
3712 (regexp :tag "Properties matched by regexp")))
3714 (defun org-property-inherit-p (property)
3715 "Return a non-nil value if PROPERTY should be inherited."
3716 (cond
3717 ((eq org-use-property-inheritance t) t)
3718 ((not org-use-property-inheritance) nil)
3719 ((stringp org-use-property-inheritance)
3720 (string-match org-use-property-inheritance property))
3721 ((listp org-use-property-inheritance)
3722 (member-ignore-case property org-use-property-inheritance))
3723 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3725 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3726 "The default column format, if no other format has been defined.
3727 This variable can be set on the per-file basis by inserting a line
3729 #+COLUMNS: %25ITEM ....."
3730 :group 'org-properties
3731 :type 'string)
3733 (defcustom org-columns-ellipses ".."
3734 "The ellipses to be used when a field in column view is truncated.
3735 When this is the empty string, as many characters as possible are shown,
3736 but then there will be no visual indication that the field has been truncated.
3737 When this is a string of length N, the last N characters of a truncated
3738 field are replaced by this string. If the column is narrower than the
3739 ellipses string, only part of the ellipses string will be shown."
3740 :group 'org-properties
3741 :type 'string)
3743 (defconst org-global-properties-fixed
3744 '(("VISIBILITY_ALL" . "folded children content all")
3745 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3746 "List of property/value pairs that can be inherited by any entry.
3748 These are fixed values, for the preset properties. The user variable
3749 that can be used to add to this list is `org-global-properties'.
3751 The entries in this list are cons cells where the car is a property
3752 name and cdr is a string with the value. If the value represents
3753 multiple items like an \"_ALL\" property, separate the items by
3754 spaces.")
3756 (defcustom org-global-properties nil
3757 "List of property/value pairs that can be inherited by any entry.
3759 This list will be combined with the constant `org-global-properties-fixed'.
3761 The entries in this list are cons cells where the car is a property
3762 name and cdr is a string with the value.
3764 You can set buffer-local values for the same purpose in the variable
3765 `org-file-properties' this by adding lines like
3767 #+PROPERTY: NAME VALUE"
3768 :group 'org-properties
3769 :type '(repeat
3770 (cons (string :tag "Property")
3771 (string :tag "Value"))))
3773 (defvar-local org-file-properties nil
3774 "List of property/value pairs that can be inherited by any entry.
3775 Valid for the current buffer.
3776 This variable is populated from #+PROPERTY lines.")
3778 (defgroup org-agenda nil
3779 "Options concerning agenda views in Org mode."
3780 :tag "Org Agenda"
3781 :group 'org)
3783 (defvar-local org-category nil
3784 "Variable used by org files to set a category for agenda display.
3785 Such files should use a file variable to set it, for example
3787 # -*- mode: org; org-category: \"ELisp\"
3789 or contain a special line
3791 #+CATEGORY: ELisp
3793 If the file does not specify a category, then file's base name
3794 is used instead.")
3795 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3797 (defcustom org-agenda-files nil
3798 "The files to be used for agenda display.
3800 If an entry is a directory, all files in that directory that are matched
3801 by `org-agenda-file-regexp' will be part of the file list.
3803 If the value of the variable is not a list but a single file name, then
3804 the list of agenda files is actually stored and maintained in that file,
3805 one agenda file per line. In this file paths can be given relative to
3806 `org-directory'. Tilde expansion and environment variable substitution
3807 are also made.
3809 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3810 and removed with `\\[org-remove-file]'."
3811 :group 'org-agenda
3812 :type '(choice
3813 (repeat :tag "List of files and directories" file)
3814 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3816 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3817 "Regular expression to match files for `org-agenda-files'.
3818 If any element in the list in that variable contains a directory instead
3819 of a normal file, all files in that directory that are matched by this
3820 regular expression will be included."
3821 :group 'org-agenda
3822 :type 'regexp)
3824 (defcustom org-agenda-text-search-extra-files nil
3825 "List of extra files to be searched by text search commands.
3826 These files will be searched in addition to the agenda files by the
3827 commands `org-search-view' (`\\[org-agenda] s') \
3828 and `org-occur-in-agenda-files'.
3829 Note that these files will only be searched for text search commands,
3830 not for the other agenda views like todo lists, tag searches or the weekly
3831 agenda. This variable is intended to list notes and possibly archive files
3832 that should also be searched by these two commands.
3833 In fact, if the first element in the list is the symbol `agenda-archives',
3834 then all archive files of all agenda files will be added to the search
3835 scope."
3836 :group 'org-agenda
3837 :type '(set :greedy t
3838 (const :tag "Agenda Archives" agenda-archives)
3839 (repeat :inline t (file))))
3841 (defvaralias 'org-agenda-multi-occur-extra-files
3842 'org-agenda-text-search-extra-files)
3844 (defcustom org-agenda-skip-unavailable-files nil
3845 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3846 A nil value means to remove them, after a query, from the list."
3847 :group 'org-agenda
3848 :type 'boolean)
3850 (defcustom org-calendar-to-agenda-key [?c]
3851 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3852 The command `org-calendar-goto-agenda' will be bound to this key. The
3853 default is the character `c' because then `c' can be used to switch back and
3854 forth between agenda and calendar."
3855 :group 'org-agenda
3856 :type 'sexp)
3858 (defcustom org-calendar-insert-diary-entry-key [?i]
3859 "The key to be installed in `calendar-mode-map' for adding diary entries.
3860 This option is irrelevant until `org-agenda-diary-file' has been configured
3861 to point to an Org file. When that is the case, the command
3862 `org-agenda-diary-entry' will be bound to the key given here, by default
3863 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3864 if you want to continue doing this, you need to change this to a different
3865 key."
3866 :group 'org-agenda
3867 :type 'sexp)
3869 (defcustom org-agenda-diary-file 'diary-file
3870 "File to which to add new entries with the `i' key in agenda and calendar.
3871 When this is the symbol `diary-file', the functionality in the Emacs
3872 calendar will be used to add entries to the `diary-file'. But when this
3873 points to a file, `org-agenda-diary-entry' will be used instead."
3874 :group 'org-agenda
3875 :type '(choice
3876 (const :tag "The standard Emacs diary file" diary-file)
3877 (file :tag "Special Org file diary entries")))
3879 (eval-after-load "calendar"
3880 '(progn
3881 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3882 'org-calendar-goto-agenda)
3883 (add-hook 'calendar-mode-hook
3884 (lambda ()
3885 (unless (eq org-agenda-diary-file 'diary-file)
3886 (define-key calendar-mode-map
3887 org-calendar-insert-diary-entry-key
3888 'org-agenda-diary-entry))))))
3890 (defgroup org-latex nil
3891 "Options for embedding LaTeX code into Org mode."
3892 :tag "Org LaTeX"
3893 :group 'org)
3895 (defcustom org-format-latex-options
3896 '(:foreground default :background default :scale 1.0
3897 :html-foreground "Black" :html-background "Transparent"
3898 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3899 "Options for creating images from LaTeX fragments.
3900 This is a property list with the following properties:
3901 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3902 `default' means use the foreground of the default face.
3903 `auto' means use the foreground from the text face.
3904 :background the background color, or \"Transparent\".
3905 `default' means use the background of the default face.
3906 `auto' means use the background from the text face.
3907 :scale a scaling factor for the size of the images, to get more pixels
3908 :html-foreground, :html-background, :html-scale
3909 the same numbers for HTML export.
3910 :matchers a list indicating which matchers should be used to
3911 find LaTeX fragments. Valid members of this list are:
3912 \"begin\" find environments
3913 \"$1\" find single characters surrounded by $.$
3914 \"$\" find math expressions surrounded by $...$
3915 \"$$\" find math expressions surrounded by $$....$$
3916 \"\\(\" find math expressions surrounded by \\(...\\)
3917 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3918 :group 'org-latex
3919 :type 'plist)
3921 (defcustom org-format-latex-signal-error t
3922 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3923 When nil, just push out a message."
3924 :group 'org-latex
3925 :version "24.1"
3926 :type 'boolean)
3928 (defcustom org-latex-to-mathml-jar-file nil
3929 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3930 Use this to specify additional executable file say a jar file.
3932 When using MathToWeb as the converter, specify the full-path to
3933 your mathtoweb.jar file."
3934 :group 'org-latex
3935 :version "24.1"
3936 :type '(choice
3937 (const :tag "None" nil)
3938 (file :tag "JAR file" :must-match t)))
3940 (defcustom org-latex-to-mathml-convert-command nil
3941 "Command to convert LaTeX fragments to MathML.
3942 Replace format-specifiers in the command as noted below and use
3943 `shell-command' to convert LaTeX to MathML.
3944 %j: Executable file in fully expanded form as specified by
3945 `org-latex-to-mathml-jar-file'.
3946 %I: Input LaTeX file in fully expanded form.
3947 %i: The latex fragment to be converted.
3948 %o: Output MathML file.
3950 This command is used by `org-create-math-formula'.
3952 When using MathToWeb as the converter, set this option to
3953 \"java -jar %j -unicode -force -df %o %I\".
3955 When using LaTeXML set this option to
3956 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3957 :group 'org-latex
3958 :version "24.1"
3959 :type '(choice
3960 (const :tag "None" nil)
3961 (string :tag "\nShell command")))
3963 (defcustom org-preview-latex-default-process 'dvipng
3964 "The default process to convert LaTeX fragments to image files.
3965 All available processes and theirs documents can be found in
3966 `org-preview-latex-process-alist', which see."
3967 :group 'org-latex
3968 :version "26.1"
3969 :package-version '(Org . "9.0")
3970 :type 'symbol)
3972 (defcustom org-preview-latex-process-alist
3973 '((dvipng
3974 :programs ("latex" "dvipng")
3975 :description "dvi > png"
3976 :message "you need to install the programs: latex and dvipng."
3977 :image-input-type "dvi"
3978 :image-output-type "png"
3979 :image-size-adjust (1.0 . 1.0)
3980 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3981 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3982 (dvisvgm
3983 :programs ("latex" "dvisvgm")
3984 :description "dvi > svg"
3985 :message "you need to install the programs: latex and dvisvgm."
3986 :use-xcolor t
3987 :image-input-type "dvi"
3988 :image-output-type "svg"
3989 :image-size-adjust (1.7 . 1.5)
3990 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3991 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3992 (imagemagick
3993 :programs ("latex" "convert")
3994 :description "pdf > png"
3995 :message "you need to install the programs: latex and imagemagick."
3996 :use-xcolor t
3997 :image-input-type "pdf"
3998 :image-output-type "png"
3999 :image-size-adjust (1.0 . 1.0)
4000 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4001 :image-converter
4002 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4003 "Definitions of external processes for LaTeX previewing.
4004 Org mode can use some external commands to generate TeX snippet's images for
4005 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4006 `org-create-formula-image' how to call them.
4008 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4009 PROPERTIES accepts the following attributes:
4011 :programs list of strings, required programs.
4012 :description string, describe the process.
4013 :message string, message it when required programs cannot be found.
4014 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4015 :image-output-type string, output file type of image converter (e.g., \"png\").
4016 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4017 deal with background and foreground color of image.
4018 Otherwise, dvipng style background and foregroud color
4019 format are generated. You may then refer to them in
4020 command options with \"%F\" and \"%B\".
4021 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4022 image size showed in buffer and the cdr element is for
4023 HTML file. This option is only useful for process
4024 developers, users should use variable
4025 `org-format-latex-options' instead.
4026 :post-clean list of strings, files matched are to be cleaned up once
4027 the image is generated. When nil, the files with \".dvi\",
4028 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4029 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4030 be cleaned up.
4031 :latex-header list of strings, the LaTeX header of the snippet file.
4032 When nil, the fallback value is used instead, which is
4033 controlled by `org-format-latex-header',
4034 `org-latex-default-packages-alist' and
4035 `org-latex-packages-alist', which see.
4036 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4037 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4038 replaced with values defined below.
4039 :image-converter list of image converter commands strings. Each of them is
4040 given to the shell and supports any of the following
4041 place-holders defined below.
4043 Place-holders used by `:image-converter' and `:latex-compiler':
4045 %f input file name
4046 %b base name of input file
4047 %o base directory of input file
4048 %O absolute output file name
4050 Place-holders only used by `:image-converter':
4052 %F foreground of image
4053 %B background of image
4054 %D dpi, which is used to adjust image size by some processing commands.
4055 %S the image size scale ratio, which is used to adjust image size by some
4056 processing commands."
4057 :group 'org-latex
4058 :version "26.1"
4059 :package-version '(Org . "9.0")
4060 :type '(alist :tag "LaTeX to image backends"
4061 :value-type (plist)))
4063 (defcustom org-preview-latex-image-directory "ltximg/"
4064 "Path to store latex preview images.
4065 A relative path here creates many directories relative to the
4066 processed org files paths. An absolute path puts all preview
4067 images at the same place."
4068 :group 'org-latex
4069 :version "26.1"
4070 :package-version '(Org . "9.0")
4071 :type 'string)
4073 (defun org-format-latex-mathml-available-p ()
4074 "Return t if `org-latex-to-mathml-convert-command' is usable."
4075 (save-match-data
4076 (when (and (boundp 'org-latex-to-mathml-convert-command)
4077 org-latex-to-mathml-convert-command)
4078 (let ((executable (car (split-string
4079 org-latex-to-mathml-convert-command))))
4080 (when (executable-find executable)
4081 (if (string-match
4082 "%j" org-latex-to-mathml-convert-command)
4083 (file-readable-p org-latex-to-mathml-jar-file)
4084 t))))))
4086 (defcustom org-format-latex-header "\\documentclass{article}
4087 \\usepackage[usenames]{color}
4088 \[PACKAGES]
4089 \[DEFAULT-PACKAGES]
4090 \\pagestyle{empty} % do not remove
4091 % The settings below are copied from fullpage.sty
4092 \\setlength{\\textwidth}{\\paperwidth}
4093 \\addtolength{\\textwidth}{-3cm}
4094 \\setlength{\\oddsidemargin}{1.5cm}
4095 \\addtolength{\\oddsidemargin}{-2.54cm}
4096 \\setlength{\\evensidemargin}{\\oddsidemargin}
4097 \\setlength{\\textheight}{\\paperheight}
4098 \\addtolength{\\textheight}{-\\headheight}
4099 \\addtolength{\\textheight}{-\\headsep}
4100 \\addtolength{\\textheight}{-\\footskip}
4101 \\addtolength{\\textheight}{-3cm}
4102 \\setlength{\\topmargin}{1.5cm}
4103 \\addtolength{\\topmargin}{-2.54cm}"
4104 "The document header used for processing LaTeX fragments.
4105 It is imperative that this header make sure that no page number
4106 appears on the page. The package defined in the variables
4107 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4108 will either replace the placeholder \"[PACKAGES]\" in this
4109 header, or they will be appended."
4110 :group 'org-latex
4111 :type 'string)
4113 (defun org-set-packages-alist (var val)
4114 "Set the packages alist and make sure it has 3 elements per entry."
4115 (set var (mapcar (lambda (x)
4116 (if (and (consp x) (= (length x) 2))
4117 (list (car x) (nth 1 x) t)
4119 val)))
4121 (defun org-get-packages-alist (var)
4122 "Get the packages alist and make sure it has 3 elements per entry."
4123 (mapcar (lambda (x)
4124 (if (and (consp x) (= (length x) 2))
4125 (list (car x) (nth 1 x) t)
4127 (default-value var)))
4129 (defcustom org-latex-default-packages-alist
4130 '(("AUTO" "inputenc" t ("pdflatex"))
4131 ("T1" "fontenc" t ("pdflatex"))
4132 ("" "graphicx" t)
4133 ("" "grffile" t)
4134 ("" "longtable" nil)
4135 ("" "wrapfig" nil)
4136 ("" "rotating" nil)
4137 ("normalem" "ulem" t)
4138 ("" "amsmath" t)
4139 ("" "textcomp" t)
4140 ("" "amssymb" t)
4141 ("" "capt-of" nil)
4142 ("" "hyperref" nil))
4143 "Alist of default packages to be inserted in the header.
4145 Change this only if one of the packages here causes an
4146 incompatibility with another package you are using.
4148 The packages in this list are needed by one part or another of
4149 Org mode to function properly:
4151 - inputenc, fontenc: for basic font and character selection
4152 - graphicx: for including images
4153 - grffile: allow periods and spaces in graphics file names
4154 - longtable: For multipage tables
4155 - wrapfig: for figure placement
4156 - rotating: for sideways figures and tables
4157 - ulem: for underline and strike-through
4158 - amsmath: for subscript and superscript and math environments
4159 - textcomp, amssymb: for various symbols used
4160 for interpreting the entities in `org-entities'. You can skip
4161 some of these packages if you don't use any of their symbols.
4162 - capt-of: for captions outside of floats
4163 - hyperref: for cross references
4165 Therefore you should not modify this variable unless you know
4166 what you are doing. The one reason to change it anyway is that
4167 you might be loading some other package that conflicts with one
4168 of the default packages. Each element is either a cell or
4169 a string.
4171 A cell is of the format
4173 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4175 If SNIPPET-FLAG is non-nil, the package also needs to be included
4176 when compiling LaTeX snippets into images for inclusion into
4177 non-LaTeX output. COMPILERS is a list of compilers that should
4178 include the package, see `org-latex-compiler'. If the document
4179 compiler is not in the list, and the list is non-nil, the package
4180 will not be inserted in the final document.
4182 A string will be inserted as-is in the header of the document."
4183 :group 'org-latex
4184 :group 'org-export-latex
4185 :set 'org-set-packages-alist
4186 :get 'org-get-packages-alist
4187 :version "26.1"
4188 :package-version '(Org . "8.3")
4189 :type '(repeat
4190 (choice
4191 (list :tag "options/package pair"
4192 (string :tag "options")
4193 (string :tag "package")
4194 (boolean :tag "Snippet"))
4195 (string :tag "A line of LaTeX"))))
4197 (defcustom org-latex-packages-alist nil
4198 "Alist of packages to be inserted in every LaTeX header.
4200 These will be inserted after `org-latex-default-packages-alist'.
4201 Each element is either a cell or a string.
4203 A cell is of the format:
4205 (\"options\" \"package\" SNIPPET-FLAG)
4207 SNIPPET-FLAG, when non-nil, indicates that this package is also
4208 needed when turning LaTeX snippets into images for inclusion into
4209 non-LaTeX output.
4211 A string will be inserted as-is in the header of the document.
4213 Make sure that you only list packages here which:
4215 - you want in every file;
4216 - do not conflict with the setup in `org-format-latex-header';
4217 - do not conflict with the default packages in
4218 `org-latex-default-packages-alist'."
4219 :group 'org-latex
4220 :group 'org-export-latex
4221 :set 'org-set-packages-alist
4222 :get 'org-get-packages-alist
4223 :type '(repeat
4224 (choice
4225 (list :tag "options/package pair"
4226 (string :tag "options")
4227 (string :tag "package")
4228 (boolean :tag "Snippet"))
4229 (string :tag "A line of LaTeX"))))
4231 (defgroup org-appearance nil
4232 "Settings for Org mode appearance."
4233 :tag "Org Appearance"
4234 :group 'org)
4236 (defcustom org-level-color-stars-only nil
4237 "Non-nil means fontify only the stars in each headline.
4238 When nil, the entire headline is fontified.
4239 Changing it requires restart of `font-lock-mode' to become effective
4240 also in regions already fontified."
4241 :group 'org-appearance
4242 :type 'boolean)
4244 (defcustom org-hide-leading-stars nil
4245 "Non-nil means hide the first N-1 stars in a headline.
4246 This works by using the face `org-hide' for these stars. This
4247 face is white for a light background, and black for a dark
4248 background. You may have to customize the face `org-hide' to
4249 make this work.
4250 Changing it requires restart of `font-lock-mode' to become effective
4251 also in regions already fontified.
4252 You may also set this on a per-file basis by adding one of the following
4253 lines to the buffer:
4255 #+STARTUP: hidestars
4256 #+STARTUP: showstars"
4257 :group 'org-appearance
4258 :type 'boolean)
4260 (defcustom org-hidden-keywords nil
4261 "List of symbols corresponding to keywords to be hidden the org buffer.
4262 For example, a value \\='(title) for this list will make the document's title
4263 appear in the buffer without the initial #+TITLE: keyword."
4264 :group 'org-appearance
4265 :version "24.1"
4266 :type '(set (const :tag "#+AUTHOR" author)
4267 (const :tag "#+DATE" date)
4268 (const :tag "#+EMAIL" email)
4269 (const :tag "#+TITLE" title)))
4271 (defcustom org-custom-properties nil
4272 "List of properties (as strings) with a special meaning.
4273 The default use of these custom properties is to let the user
4274 hide them with `org-toggle-custom-properties-visibility'."
4275 :group 'org-properties
4276 :group 'org-appearance
4277 :version "24.3"
4278 :type '(repeat (string :tag "Property Name")))
4280 (defcustom org-fontify-done-headline nil
4281 "Non-nil means change the face of a headline if it is marked DONE.
4282 Normally, only the TODO/DONE keyword indicates the state of a headline.
4283 When this is non-nil, the headline after the keyword is set to the
4284 `org-headline-done' as an additional indication."
4285 :group 'org-appearance
4286 :type 'boolean)
4288 (defcustom org-fontify-emphasized-text t
4289 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4290 Changing this variable requires a restart of Emacs to take effect."
4291 :group 'org-appearance
4292 :type 'boolean)
4294 (defcustom org-fontify-whole-heading-line nil
4295 "Non-nil means fontify the whole line for headings.
4296 This is useful when setting a background color for the
4297 org-level-* faces."
4298 :group 'org-appearance
4299 :type 'boolean)
4301 (defcustom org-highlight-latex-and-related nil
4302 "Non-nil means highlight LaTeX related syntax in the buffer.
4303 When non nil, the value should be a list containing any of the
4304 following symbols:
4305 `latex' Highlight LaTeX snippets and environments.
4306 `script' Highlight subscript and superscript.
4307 `entities' Highlight entities."
4308 :group 'org-appearance
4309 :version "24.4"
4310 :package-version '(Org . "8.0")
4311 :type '(choice
4312 (const :tag "No highlighting" nil)
4313 (set :greedy t :tag "Highlight"
4314 (const :tag "LaTeX snippets and environments" latex)
4315 (const :tag "Subscript and superscript" script)
4316 (const :tag "Entities" entities))))
4318 (defcustom org-hide-emphasis-markers nil
4319 "Non-nil mean font-lock should hide the emphasis marker characters."
4320 :group 'org-appearance
4321 :type 'boolean)
4323 (defcustom org-hide-macro-markers nil
4324 "Non-nil mean font-lock should hide the brackets marking macro calls."
4325 :group 'org-appearance
4326 :type 'boolean)
4328 (defcustom org-pretty-entities nil
4329 "Non-nil means show entities as UTF8 characters.
4330 When nil, the \\name form remains in the buffer."
4331 :group 'org-appearance
4332 :version "24.1"
4333 :type 'boolean)
4335 (defcustom org-pretty-entities-include-sub-superscripts t
4336 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4337 :group 'org-appearance
4338 :version "24.1"
4339 :type 'boolean)
4341 (defvar org-emph-re nil
4342 "Regular expression for matching emphasis.
4343 After a match, the match groups contain these elements:
4344 0 The match of the full regular expression, including the characters
4345 before and after the proper match
4346 1 The character before the proper match, or empty at beginning of line
4347 2 The proper match, including the leading and trailing markers
4348 3 The leading marker like * or /, indicating the type of highlighting
4349 4 The text between the emphasis markers, not including the markers
4350 5 The character after the match, empty at the end of a line")
4352 (defvar org-verbatim-re nil
4353 "Regular expression for matching verbatim text.")
4355 (defvar org-emphasis-regexp-components) ; defined just below
4356 (defvar org-emphasis-alist) ; defined just below
4357 (defun org-set-emph-re (var val)
4358 "Set variable and compute the emphasis regular expression."
4359 (set var val)
4360 (when (and (boundp 'org-emphasis-alist)
4361 (boundp 'org-emphasis-regexp-components)
4362 org-emphasis-alist org-emphasis-regexp-components)
4363 (pcase-let*
4364 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4365 (body (if (<= nl 0) body
4366 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4367 (template
4368 (format (concat "\\([%s]\\|^\\)" ;before markers
4369 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4370 "\\([%s]\\|$\\)") ;after markers
4371 pre border border body border post)))
4372 (setq org-emph-re (format template "*/_+"))
4373 (setq org-verbatim-re (format template "=~")))))
4375 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4376 ;; set this option proved cumbersome. See this message/thread:
4377 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4378 (defvar org-emphasis-regexp-components
4379 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4380 "Components used to build the regular expression for emphasis.
4381 This is a list with five entries. Terminology: In an emphasis string
4382 like \" *strong word* \", we call the initial space PREMATCH, the final
4383 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4384 and \"trong wor\" is the body. The different components in this variable
4385 specify what is allowed/forbidden in each part:
4387 pre Chars allowed as prematch. Beginning of line will be allowed too.
4388 post Chars allowed as postmatch. End of line will be allowed too.
4389 border The chars *forbidden* as border characters.
4390 body-regexp A regexp like \".\" to match a body character. Don't use
4391 non-shy groups here, and don't allow newline here.
4392 newline The maximum number of newlines allowed in an emphasis exp.
4394 You need to reload Org or to restart Emacs after customizing this.")
4396 (defcustom org-emphasis-alist
4397 '(("*" bold)
4398 ("/" italic)
4399 ("_" underline)
4400 ("=" org-verbatim verbatim)
4401 ("~" org-code verbatim)
4402 ("+" (:strike-through t)))
4403 "Alist of characters and faces to emphasize text.
4404 Text starting and ending with a special character will be emphasized,
4405 for example *bold*, _underlined_ and /italic/. This variable sets the
4406 marker characters and the face to be used by font-lock for highlighting
4407 in Org buffers.
4409 You need to reload Org or to restart Emacs after customizing this."
4410 :group 'org-appearance
4411 :set 'org-set-emph-re
4412 :version "24.4"
4413 :package-version '(Org . "8.0")
4414 :type '(repeat
4415 (list
4416 (string :tag "Marker character")
4417 (choice
4418 (face :tag "Font-lock-face")
4419 (plist :tag "Face property list"))
4420 (option (const verbatim)))))
4422 (defvar org-protecting-blocks '("src" "example" "export")
4423 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4424 This is needed for font-lock setup.")
4426 ;;; Functions and variables from their packages
4427 ;; Declared here to avoid compiler warnings
4428 (defvar mark-active)
4430 ;; Various packages
4431 (declare-function calc-eval "calc" (str &optional separator &rest args))
4432 (declare-function calendar-forward-day "cal-move" (arg))
4433 (declare-function calendar-goto-date "cal-move" (date))
4434 (declare-function calendar-goto-today "cal-move" ())
4435 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4436 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4437 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4438 (declare-function cdlatex-tab "ext:cdlatex" ())
4439 (declare-function dired-get-filename
4440 "dired"
4441 (&optional localp no-error-if-not-filep))
4442 (declare-function iswitchb-read-buffer
4443 "iswitchb"
4444 (prompt &optional
4445 default require-match _predicate start matches-set))
4446 (declare-function org-agenda-change-all-lines
4447 "org-agenda"
4448 (newhead hdmarker &optional fixface just-this))
4449 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4450 "org-agenda"
4451 (&optional end))
4452 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4453 (declare-function org-agenda-format-item
4454 "org-agenda"
4455 (extra txt &optional level category tags dotime
4456 remove-re habitp))
4457 (declare-function org-agenda-maybe-redo "org-agenda" ())
4458 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4459 (declare-function org-agenda-save-markers-for-cut-and-paste
4460 "org-agenda"
4461 (beg end))
4462 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4463 (declare-function org-agenda-skip "org-agenda" ())
4464 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4465 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4466 (declare-function org-indent-mode "org-indent" (&optional arg))
4467 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4468 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4469 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4470 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4471 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4472 (declare-function parse-time-string "parse-time" (string))
4473 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4475 (defvar align-mode-rules-list)
4476 (defvar calc-embedded-close-formula)
4477 (defvar calc-embedded-open-formula)
4478 (defvar calc-embedded-open-mode)
4479 (defvar font-lock-unfontify-region-function)
4480 (defvar iswitchb-temp-buflist)
4481 (defvar org-agenda-tags-todo-honor-ignore-options)
4482 (defvar remember-data-file)
4483 (defvar texmathp-why)
4485 ;;;###autoload
4486 (defun turn-on-orgtbl ()
4487 "Unconditionally turn on `orgtbl-mode'."
4488 (require 'org-table)
4489 (orgtbl-mode 1))
4491 (defun org-at-table-p (&optional table-type)
4492 "Non-nil if the cursor is inside an Org table.
4493 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4494 If `org-enable-table-editor' is nil, return nil unconditionally."
4495 (and
4496 org-enable-table-editor
4497 (save-excursion
4498 (beginning-of-line)
4499 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4500 (or (not (derived-mode-p 'org-mode))
4501 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4502 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4504 (defun org-at-table.el-p ()
4505 "Non-nil when point is at a table.el table."
4506 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4507 (let ((element (org-element-at-point)))
4508 (and (eq (org-element-type element) 'table)
4509 (eq (org-element-property :type element) 'table.el)))))
4511 (defun org-at-table-hline-p ()
4512 "Non-nil when point is inside a hline in a table.
4513 Assume point is already in a table. If `org-enable-table-editor'
4514 is nil, return nil unconditionally."
4515 (and org-enable-table-editor
4516 (save-excursion
4517 (beginning-of-line)
4518 (looking-at org-table-hline-regexp))))
4520 (defun org-table-map-tables (function &optional quietly)
4521 "Apply FUNCTION to the start of all tables in the buffer."
4522 (org-with-wide-buffer
4523 (goto-char (point-min))
4524 (while (re-search-forward org-table-any-line-regexp nil t)
4525 (unless quietly
4526 (message "Mapping tables: %d%%"
4527 (floor (* 100.0 (point)) (buffer-size))))
4528 (beginning-of-line 1)
4529 (when (and (looking-at org-table-line-regexp)
4530 ;; Exclude tables in src/example/verbatim/clocktable blocks
4531 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4532 (save-excursion (funcall function))
4533 (or (looking-at org-table-line-regexp)
4534 (forward-char 1)))
4535 (re-search-forward org-table-any-border-regexp nil 1)))
4536 (unless quietly (message "Mapping tables: done")))
4538 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4539 (declare-function org-clock-update-mode-line "org-clock" ())
4540 (declare-function org-resolve-clocks "org-clock"
4541 (&optional also-non-dangling-p prompt last-valid))
4543 (defun org-at-TBLFM-p (&optional pos)
4544 "Non-nil when point (or POS) is in #+TBLFM line."
4545 (save-excursion
4546 (goto-char (or pos (point)))
4547 (beginning-of-line)
4548 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4549 (eq (org-element-type (org-element-at-point)) 'table))))
4551 (defvar org-clock-start-time)
4552 (defvar org-clock-marker (make-marker)
4553 "Marker recording the last clock-in.")
4554 (defvar org-clock-hd-marker (make-marker)
4555 "Marker recording the last clock-in, but the headline position.")
4556 (defvar org-clock-heading ""
4557 "The heading of the current clock entry.")
4558 (defun org-clock-is-active ()
4559 "Return the buffer where the clock is currently running.
4560 Return nil if no clock is running."
4561 (marker-buffer org-clock-marker))
4563 (defun org-check-running-clock ()
4564 "Check if the current buffer contains the running clock.
4565 If yes, offer to stop it and to save the buffer with the changes."
4566 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4567 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4568 (buffer-name))))
4569 (org-clock-out)
4570 (when (y-or-n-p "Save changed buffer?")
4571 (save-buffer))))
4573 (defun org-clocktable-try-shift (dir n)
4574 "Check if this line starts a clock table, if yes, shift the time block."
4575 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4576 (org-clocktable-shift dir n)))
4578 ;;;###autoload
4579 (defun org-clock-persistence-insinuate ()
4580 "Set up hooks for clock persistence."
4581 (require 'org-clock)
4582 (add-hook 'org-mode-hook 'org-clock-load)
4583 (add-hook 'kill-emacs-hook 'org-clock-save))
4585 (defgroup org-archive nil
4586 "Options concerning archiving in Org mode."
4587 :tag "Org Archive"
4588 :group 'org-structure)
4590 (defcustom org-archive-location "%s_archive::"
4591 "The location where subtrees should be archived.
4593 The value of this variable is a string, consisting of two parts,
4594 separated by a double-colon. The first part is a filename and
4595 the second part is a headline.
4597 When the filename is omitted, archiving happens in the same file.
4598 %s in the filename will be replaced by the current file
4599 name (without the directory part). Archiving to a different file
4600 is useful to keep archived entries from contributing to the
4601 Org Agenda.
4603 The archived entries will be filed as subtrees of the specified
4604 headline. When the headline is omitted, the subtrees are simply
4605 filed away at the end of the file, as top-level entries. Also in
4606 the heading you can use %s to represent the file name, this can be
4607 useful when using the same archive for a number of different files.
4609 Here are a few examples:
4610 \"%s_archive::\"
4611 If the current file is Projects.org, archive in file
4612 Projects.org_archive, as top-level trees. This is the default.
4614 \"::* Archived Tasks\"
4615 Archive in the current file, under the top-level headline
4616 \"* Archived Tasks\".
4618 \"~/org/archive.org::\"
4619 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4621 \"~/org/archive.org::* From %s\"
4622 Archive in file ~/org/archive.org (absolute path), under headlines
4623 \"From FILENAME\" where file name is the current file name.
4625 \"~/org/datetree.org::datetree/* Finished Tasks\"
4626 The \"datetree/\" string is special, signifying to archive
4627 items to the datetree. Items are placed in either the CLOSED
4628 date of the item, or the current date if there is no CLOSED date.
4629 The heading will be a subentry to the current date. There doesn't
4630 need to be a heading, but there always needs to be a slash after
4631 datetree. For example, to store archived items directly in the
4632 datetree, use \"~/org/datetree.org::datetree/\".
4634 \"basement::** Finished Tasks\"
4635 Archive in file ./basement (relative path), as level 3 trees
4636 below the level 2 heading \"** Finished Tasks\".
4638 You may set this option on a per-file basis by adding to the buffer a
4639 line like
4641 #+ARCHIVE: basement::** Finished Tasks
4643 You may also define it locally for a subtree by setting an ARCHIVE property
4644 in the entry. If such a property is found in an entry, or anywhere up
4645 the hierarchy, it will be used."
4646 :group 'org-archive
4647 :type 'string)
4649 (defcustom org-agenda-skip-archived-trees t
4650 "Non-nil means the agenda will skip any items located in archived trees.
4651 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4652 variable is no longer recommended, you should leave it at the value t.
4653 Instead, use the key `v' to cycle the archives-mode in the agenda."
4654 :group 'org-archive
4655 :group 'org-agenda-skip
4656 :type 'boolean)
4658 (defcustom org-columns-skip-archived-trees t
4659 "Non-nil means ignore archived trees when creating column view."
4660 :group 'org-archive
4661 :group 'org-properties
4662 :type 'boolean)
4664 (defcustom org-cycle-open-archived-trees nil
4665 "Non-nil means `org-cycle' will open archived trees.
4666 An archived tree is a tree marked with the tag ARCHIVE.
4667 When nil, archived trees will stay folded. You can still open them with
4668 normal outline commands like `show-all', but not with the cycling commands."
4669 :group 'org-archive
4670 :group 'org-cycle
4671 :type 'boolean)
4673 (defcustom org-sparse-tree-open-archived-trees nil
4674 "Non-nil means sparse tree construction shows matches in archived trees.
4675 When nil, matches in these trees are highlighted, but the trees are kept in
4676 collapsed state."
4677 :group 'org-archive
4678 :group 'org-sparse-trees
4679 :type 'boolean)
4681 (defcustom org-sparse-tree-default-date-type nil
4682 "The default date type when building a sparse tree.
4683 When this is nil, a date is a scheduled or a deadline timestamp.
4684 Otherwise, these types are allowed:
4686 all: all timestamps
4687 active: only active timestamps (<...>)
4688 inactive: only inactive timestamps ([...])
4689 scheduled: only scheduled timestamps
4690 deadline: only deadline timestamps"
4691 :type '(choice (const :tag "Scheduled or deadline" nil)
4692 (const :tag "All timestamps" all)
4693 (const :tag "Only active timestamps" active)
4694 (const :tag "Only inactive timestamps" inactive)
4695 (const :tag "Only scheduled timestamps" scheduled)
4696 (const :tag "Only deadline timestamps" deadline)
4697 (const :tag "Only closed timestamps" closed))
4698 :version "26.1"
4699 :package-version '(Org . "8.3")
4700 :group 'org-sparse-trees)
4702 (defun org-cycle-hide-archived-subtrees (state)
4703 "Re-hide all archived subtrees after a visibility state change."
4704 (when (and (not org-cycle-open-archived-trees)
4705 (not (memq state '(overview folded))))
4706 (save-excursion
4707 (let* ((globalp (memq state '(contents all)))
4708 (beg (if globalp (point-min) (point)))
4709 (end (if globalp (point-max) (org-end-of-subtree t))))
4710 (org-hide-archived-subtrees beg end)
4711 (goto-char beg)
4712 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4713 (message "%s" (substitute-command-keys
4714 "Subtree is archived and stays closed. Use \
4715 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4717 (defun org-force-cycle-archived ()
4718 "Cycle subtree even if it is archived."
4719 (interactive)
4720 (setq this-command 'org-cycle)
4721 (let ((org-cycle-open-archived-trees t))
4722 (call-interactively 'org-cycle)))
4724 (defun org-hide-archived-subtrees (beg end)
4725 "Re-hide all archived subtrees after a visibility state change."
4726 (org-with-wide-buffer
4727 (let ((case-fold-search nil)
4728 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4729 (goto-char beg)
4730 ;; Include headline point is currently on.
4731 (beginning-of-line)
4732 (while (and (< (point) end) (re-search-forward re end t))
4733 (when (member org-archive-tag (org-get-tags))
4734 (org-flag-subtree t)
4735 (org-end-of-subtree t))))))
4737 (declare-function outline-end-of-heading "outline" ())
4738 (declare-function outline-flag-region "outline" (from to flag))
4739 (defun org-flag-subtree (flag)
4740 (save-excursion
4741 (org-back-to-heading t)
4742 (outline-end-of-heading)
4743 (outline-flag-region (point)
4744 (progn (org-end-of-subtree t) (point))
4745 flag)))
4747 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4749 ;; Declare Column View Code
4751 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4752 (declare-function org-columns-compute "org-colview" (property))
4754 ;; Declare ID code
4756 (declare-function org-id-store-link "org-id")
4757 (declare-function org-id-locations-load "org-id")
4758 (declare-function org-id-locations-save "org-id")
4759 (defvar org-id-track-globally)
4761 ;;; Variables for pre-computed regular expressions, all buffer local
4763 (defvar-local org-todo-regexp nil
4764 "Matches any of the TODO state keywords.
4765 Since TODO keywords are case-sensitive, `case-fold-search' is
4766 expected to be bound to nil when matching against this regexp.")
4768 (defvar-local org-not-done-regexp nil
4769 "Matches any of the TODO state keywords except the last one.
4770 Since TODO keywords are case-sensitive, `case-fold-search' is
4771 expected to be bound to nil when matching against this regexp.")
4773 (defvar-local org-not-done-heading-regexp nil
4774 "Matches a TODO headline that is not done.
4775 Since TODO keywords are case-sensitive, `case-fold-search' is
4776 expected to be bound to nil when matching against this regexp.")
4778 (defvar-local org-todo-line-regexp nil
4779 "Matches a headline and puts TODO state into group 2 if present.
4780 Since TODO keywords are case-sensitive, `case-fold-search' is
4781 expected to be bound to nil when matching against this regexp.")
4783 (defvar-local org-complex-heading-regexp nil
4784 "Matches a headline and puts everything into groups:
4786 group 1: Stars
4787 group 2: The TODO keyword, maybe
4788 group 3: Priority cookie
4789 group 4: True headline
4790 group 5: Tags
4792 Since TODO keywords are case-sensitive, `case-fold-search' is
4793 expected to be bound to nil when matching against this regexp.")
4795 (defvar-local org-complex-heading-regexp-format nil
4796 "Printf format to make regexp to match an exact headline.
4797 This regexp will match the headline of any node which has the
4798 exact headline text that is put into the format, but may have any
4799 TODO state, priority and tags.")
4801 (defvar-local org-todo-line-tags-regexp nil
4802 "Matches a headline and puts TODO state into group 2 if present.
4803 Also put tags into group 4 if tags are present.")
4805 (defconst org-plain-time-of-day-regexp
4806 (concat
4807 "\\(\\<[012]?[0-9]"
4808 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4809 "\\(--?"
4810 "\\(\\<[012]?[0-9]"
4811 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4812 "\\)?")
4813 "Regular expression to match a plain time or time range.
4814 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4815 groups carry important information:
4816 0 the full match
4817 1 the first time, range or not
4818 8 the second time, if it is a range.")
4820 (defconst org-plain-time-extension-regexp
4821 (concat
4822 "\\(\\<[012]?[0-9]"
4823 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4824 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4825 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4826 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4827 groups carry important information:
4828 0 the full match
4829 7 hours of duration
4830 9 minutes of duration")
4832 (defconst org-stamp-time-of-day-regexp
4833 (concat
4834 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4835 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4836 "\\(--?"
4837 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4838 "Regular expression to match a timestamp time or time range.
4839 After a match, the following groups carry important information:
4840 0 the full match
4841 1 date plus weekday, for back referencing to make sure both times are on the same day
4842 2 the first time, range or not
4843 4 the second time, if it is a range.")
4845 (defconst org-startup-options
4846 '(("fold" org-startup-folded t)
4847 ("overview" org-startup-folded t)
4848 ("nofold" org-startup-folded nil)
4849 ("showall" org-startup-folded nil)
4850 ("showeverything" org-startup-folded showeverything)
4851 ("content" org-startup-folded content)
4852 ("indent" org-startup-indented t)
4853 ("noindent" org-startup-indented nil)
4854 ("hidestars" org-hide-leading-stars t)
4855 ("showstars" org-hide-leading-stars nil)
4856 ("odd" org-odd-levels-only t)
4857 ("oddeven" org-odd-levels-only nil)
4858 ("align" org-startup-align-all-tables t)
4859 ("noalign" org-startup-align-all-tables nil)
4860 ("inlineimages" org-startup-with-inline-images t)
4861 ("noinlineimages" org-startup-with-inline-images nil)
4862 ("latexpreview" org-startup-with-latex-preview t)
4863 ("nolatexpreview" org-startup-with-latex-preview nil)
4864 ("customtime" org-display-custom-times t)
4865 ("logdone" org-log-done time)
4866 ("lognotedone" org-log-done note)
4867 ("nologdone" org-log-done nil)
4868 ("lognoteclock-out" org-log-note-clock-out t)
4869 ("nolognoteclock-out" org-log-note-clock-out nil)
4870 ("logrepeat" org-log-repeat state)
4871 ("lognoterepeat" org-log-repeat note)
4872 ("logdrawer" org-log-into-drawer t)
4873 ("nologdrawer" org-log-into-drawer nil)
4874 ("logstatesreversed" org-log-states-order-reversed t)
4875 ("nologstatesreversed" org-log-states-order-reversed nil)
4876 ("nologrepeat" org-log-repeat nil)
4877 ("logreschedule" org-log-reschedule time)
4878 ("lognotereschedule" org-log-reschedule note)
4879 ("nologreschedule" org-log-reschedule nil)
4880 ("logredeadline" org-log-redeadline time)
4881 ("lognoteredeadline" org-log-redeadline note)
4882 ("nologredeadline" org-log-redeadline nil)
4883 ("logrefile" org-log-refile time)
4884 ("lognoterefile" org-log-refile note)
4885 ("nologrefile" org-log-refile nil)
4886 ("fninline" org-footnote-define-inline t)
4887 ("nofninline" org-footnote-define-inline nil)
4888 ("fnlocal" org-footnote-section nil)
4889 ("fnauto" org-footnote-auto-label t)
4890 ("fnprompt" org-footnote-auto-label nil)
4891 ("fnconfirm" org-footnote-auto-label confirm)
4892 ("fnplain" org-footnote-auto-label plain)
4893 ("fnadjust" org-footnote-auto-adjust t)
4894 ("nofnadjust" org-footnote-auto-adjust nil)
4895 ("constcgs" constants-unit-system cgs)
4896 ("constSI" constants-unit-system SI)
4897 ("noptag" org-tag-persistent-alist nil)
4898 ("hideblocks" org-hide-block-startup t)
4899 ("nohideblocks" org-hide-block-startup nil)
4900 ("beamer" org-startup-with-beamer-mode t)
4901 ("entitiespretty" org-pretty-entities t)
4902 ("entitiesplain" org-pretty-entities nil))
4903 "Variable associated with STARTUP options for org-mode.
4904 Each element is a list of three items: the startup options (as written
4905 in the #+STARTUP line), the corresponding variable, and the value to set
4906 this variable to if the option is found. An optional forth element PUSH
4907 means to push this value onto the list in the variable.")
4909 (defcustom org-group-tags t
4910 "When non-nil (the default), use group tags.
4911 This can be turned on/off through `org-toggle-tags-groups'."
4912 :group 'org-tags
4913 :group 'org-startup
4914 :type 'boolean)
4916 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4918 (defun org-toggle-tags-groups ()
4919 "Toggle support for group tags.
4920 Support for group tags is controlled by the option
4921 `org-group-tags', which is non-nil by default."
4922 (interactive)
4923 (setq org-group-tags (not org-group-tags))
4924 (cond ((and (derived-mode-p 'org-agenda-mode)
4925 org-group-tags)
4926 (org-agenda-redo))
4927 ((derived-mode-p 'org-mode)
4928 (let ((org-inhibit-startup t)) (org-mode))))
4929 (message "Groups tags support has been turned %s"
4930 (if org-group-tags "on" "off")))
4932 (defun org-set-regexps-and-options (&optional tags-only)
4933 "Precompute regular expressions used in the current buffer.
4934 When optional argument TAGS-ONLY is non-nil, only compute tags
4935 related expressions."
4936 (when (derived-mode-p 'org-mode)
4937 (let ((alist (org--setup-collect-keywords
4938 (org-make-options-regexp
4939 (append '("FILETAGS" "TAGS" "SETUPFILE")
4940 (and (not tags-only)
4941 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4942 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4943 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4944 ;; Startup options. Get this early since it does change
4945 ;; behavior for other options (e.g., tags).
4946 (let ((startup (cdr (assq 'startup alist))))
4947 (dolist (option startup)
4948 (let ((entry (assoc-string option org-startup-options t)))
4949 (when entry
4950 (let ((var (nth 1 entry))
4951 (val (nth 2 entry)))
4952 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4953 (unless (listp (symbol-value var))
4954 (set (make-local-variable var) nil))
4955 (add-to-list var val)))))))
4956 (setq-local org-file-tags
4957 (mapcar #'org-add-prop-inherited
4958 (cdr (assq 'filetags alist))))
4959 (setq org-current-tag-alist
4960 (append org-tag-persistent-alist
4961 (let ((tags (cdr (assq 'tags alist))))
4962 (if tags (org-tag-string-to-alist tags)
4963 org-tag-alist))))
4964 (setq org-tag-groups-alist
4965 (org-tag-alist-to-groups org-current-tag-alist))
4966 (unless tags-only
4967 ;; File properties.
4968 (setq-local org-file-properties (cdr (assq 'property alist)))
4969 ;; Archive location.
4970 (let ((archive (cdr (assq 'archive alist))))
4971 (when archive (setq-local org-archive-location archive)))
4972 ;; Category.
4973 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4974 (when cat
4975 (setq-local org-category (intern cat))
4976 (setq-local org-file-properties
4977 (org--update-property-plist
4978 "CATEGORY" cat org-file-properties))))
4979 ;; Columns.
4980 (let ((column (cdr (assq 'columns alist))))
4981 (when column (setq-local org-columns-default-format column)))
4982 ;; Constants.
4983 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4984 ;; Link abbreviations.
4985 (let ((links (cdr (assq 'link alist))))
4986 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4987 ;; Priorities.
4988 (let ((priorities (cdr (assq 'priorities alist))))
4989 (when priorities
4990 (setq-local org-highest-priority (nth 0 priorities))
4991 (setq-local org-lowest-priority (nth 1 priorities))
4992 (setq-local org-default-priority (nth 2 priorities))))
4993 ;; Scripts.
4994 (let ((scripts (assq 'scripts alist)))
4995 (when scripts
4996 (setq-local org-use-sub-superscripts (cdr scripts))))
4997 ;; TODO keywords.
4998 (setq-local org-todo-kwd-alist nil)
4999 (setq-local org-todo-key-alist nil)
5000 (setq-local org-todo-key-trigger nil)
5001 (setq-local org-todo-keywords-1 nil)
5002 (setq-local org-done-keywords nil)
5003 (setq-local org-todo-heads nil)
5004 (setq-local org-todo-sets nil)
5005 (setq-local org-todo-log-states nil)
5006 (let ((todo-sequences
5007 (or (nreverse (cdr (assq 'todo alist)))
5008 (let ((d (default-value 'org-todo-keywords)))
5009 (if (not (stringp (car d))) d
5010 ;; XXX: Backward compatibility code.
5011 (list (cons org-todo-interpretation d)))))))
5012 (dolist (sequence todo-sequences)
5013 (let* ((sequence (or (run-hook-with-args-until-success
5014 'org-todo-setup-filter-hook sequence)
5015 sequence))
5016 (sequence-type (car sequence))
5017 (keywords (cdr sequence))
5018 (sep (member "|" keywords))
5019 names alist)
5020 (dolist (k (remove "|" keywords))
5021 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5023 (error "Invalid TODO keyword %s" k))
5024 (let ((name (match-string 1 k))
5025 (key (match-string 2 k))
5026 (log (org-extract-log-state-settings k)))
5027 (push name names)
5028 (push (cons name (and key (string-to-char key))) alist)
5029 (when log (push log org-todo-log-states))))
5030 (let* ((names (nreverse names))
5031 (done (if sep (org-remove-keyword-keys (cdr sep))
5032 (last names)))
5033 (head (car names))
5034 (tail (list sequence-type head (car done) (org-last done))))
5035 (add-to-list 'org-todo-heads head 'append)
5036 (push names org-todo-sets)
5037 (setq org-done-keywords (append org-done-keywords done nil))
5038 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5039 (setq org-todo-key-alist
5040 (append org-todo-key-alist
5041 (and alist
5042 (append '((:startgroup))
5043 (nreverse alist)
5044 '((:endgroup))))))
5045 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5046 (setq org-todo-sets (nreverse org-todo-sets)
5047 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5048 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5049 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5050 ;; Compute the regular expressions and other local variables.
5051 ;; Using `org-outline-regexp-bol' would complicate them much,
5052 ;; because of the fixed white space at the end of that string.
5053 (unless org-done-keywords
5054 (setq org-done-keywords
5055 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5056 (setq org-not-done-keywords
5057 (org-delete-all org-done-keywords
5058 (copy-sequence org-todo-keywords-1))
5059 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5060 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5061 org-not-done-heading-regexp
5062 (format org-heading-keyword-regexp-format org-not-done-regexp)
5063 org-todo-line-regexp
5064 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5065 org-complex-heading-regexp
5066 (concat "^\\(\\*+\\)"
5067 "\\(?: +" org-todo-regexp "\\)?"
5068 "\\(?: +\\(\\[#.\\]\\)\\)?"
5069 "\\(?: +\\(.*?\\)\\)??"
5070 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5071 "[ \t]*$")
5072 org-complex-heading-regexp-format
5073 (concat "^\\(\\*+\\)"
5074 "\\(?: +" org-todo-regexp "\\)?"
5075 "\\(?: +\\(\\[#.\\]\\)\\)?"
5076 "\\(?: +"
5077 ;; Stats cookies can be stuck to body.
5078 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5079 "\\(%s\\)"
5080 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5081 "\\)"
5082 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5083 "[ \t]*$")
5084 org-todo-line-tags-regexp
5085 (concat "^\\(\\*+\\)"
5086 "\\(?: +" org-todo-regexp "\\)?"
5087 "\\(?: +\\(.*?\\)\\)??"
5088 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5089 "[ \t]*$"))
5090 (org-compute-latex-and-related-regexp)))))
5092 (defun org--setup-collect-keywords (regexp &optional files alist)
5093 "Return setup keywords values as an alist.
5095 REGEXP matches a subset of setup keywords. FILES is a list of
5096 file names already visited. It is used to avoid circular setup
5097 files. ALIST, when non-nil, is the alist computed so far.
5099 Return value contains the following keys: `archive', `category',
5100 `columns', `constants', `filetags', `link', `priorities',
5101 `property', `scripts', `startup', `tags' and `todo'."
5102 (org-with-wide-buffer
5103 (goto-char (point-min))
5104 (let ((case-fold-search t))
5105 (while (re-search-forward regexp nil t)
5106 (let ((element (org-element-at-point)))
5107 (when (eq (org-element-type element) 'keyword)
5108 (let ((key (org-element-property :key element))
5109 (value (org-element-property :value element)))
5110 (cond
5111 ((equal key "ARCHIVE")
5112 (when (org-string-nw-p value)
5113 (push (cons 'archive value) alist)))
5114 ((equal key "CATEGORY") (push (cons 'category value) alist))
5115 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5116 ((equal key "CONSTANTS")
5117 (let* ((constants (assq 'constants alist))
5118 (store (cdr constants)))
5119 (dolist (pair (org-split-string value))
5120 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5121 pair)
5122 (let* ((name (match-string 1 pair))
5123 (value (match-string 2 pair))
5124 (old (assoc name store)))
5125 (if old (setcdr old value)
5126 (push (cons name value) store)))))
5127 (if constants (setcdr constants store)
5128 (push (cons 'constants store) alist))))
5129 ((equal key "FILETAGS")
5130 (when (org-string-nw-p value)
5131 (let ((old (assq 'filetags alist))
5132 (new (apply #'nconc
5133 (mapcar (lambda (x) (org-split-string x ":"))
5134 (org-split-string value)))))
5135 (if old (setcdr old (append new (cdr old)))
5136 (push (cons 'filetags new) alist)))))
5137 ((equal key "LINK")
5138 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5139 (let ((links (assq 'link alist))
5140 (pair (cons (match-string-no-properties 1 value)
5141 (match-string-no-properties 2 value))))
5142 (if links (push pair (cdr links))
5143 (push (list 'link pair) alist)))))
5144 ((equal key "OPTIONS")
5145 (when (and (org-string-nw-p value)
5146 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5147 (push (cons 'scripts (read (match-string 1 value))) alist)))
5148 ((equal key "PRIORITIES")
5149 (push (cons 'priorities
5150 (let ((prio (org-split-string value)))
5151 (if (< (length prio) 3) '(?A ?C ?B)
5152 (mapcar #'string-to-char prio))))
5153 alist))
5154 ((equal key "PROPERTY")
5155 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5156 (let* ((property (assq 'property alist))
5157 (value (org--update-property-plist
5158 (match-string-no-properties 1 value)
5159 (match-string-no-properties 2 value)
5160 (cdr property))))
5161 (if property (setcdr property value)
5162 (push (cons 'property value) alist)))))
5163 ((equal key "STARTUP")
5164 (let ((startup (assq 'startup alist)))
5165 (if startup
5166 (setcdr startup
5167 (append (cdr startup) (org-split-string value)))
5168 (push (cons 'startup (org-split-string value)) alist))))
5169 ((equal key "TAGS")
5170 (let ((tag-cell (assq 'tags alist)))
5171 (if tag-cell
5172 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5173 (push (cons 'tags value) alist))))
5174 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5175 (let ((todo (assq 'todo alist))
5176 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5177 (org-split-string value))))
5178 (if todo (push value (cdr todo))
5179 (push (list 'todo value) alist))))
5180 ((equal key "SETUPFILE")
5181 (unless buffer-read-only ; Do not check in Gnus messages.
5182 (let ((f (and (org-string-nw-p value)
5183 (expand-file-name
5184 (org-unbracket-string "\"" "\"" value)))))
5185 (when (and f (file-readable-p f) (not (member f files)))
5186 (with-temp-buffer
5187 (setq default-directory (file-name-directory f))
5188 (insert-file-contents f)
5189 (setq alist
5190 ;; Fake Org mode to benefit from cache
5191 ;; without recurring needlessly.
5192 (let ((major-mode 'org-mode))
5193 (org--setup-collect-keywords
5194 regexp (cons f files) alist)))))))))))))))
5195 alist)
5197 (defun org-tag-string-to-alist (s)
5198 "Return tag alist associated to string S.
5199 S is a value for TAGS keyword or produced with
5200 `org-tag-alist-to-string'. Return value is an alist suitable for
5201 `org-tag-alist' or `org-tag-persistent-alist'."
5202 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5203 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5204 "\\|{.+?}\\)" ; regular expression
5205 "\\(?:(\\(.\\))\\)?\\'"))
5206 alist group-flag)
5207 (dolist (tokens lines (cdr (nreverse alist)))
5208 (push '(:newline) alist)
5209 (while tokens
5210 (let ((token (pop tokens)))
5211 (pcase token
5212 ("{"
5213 (push '(:startgroup) alist)
5214 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5215 ("}"
5216 (push '(:endgroup) alist)
5217 (setq group-flag nil))
5218 ("["
5219 (push '(:startgrouptag) alist)
5220 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5221 ("]"
5222 (push '(:endgrouptag) alist)
5223 (setq group-flag nil))
5224 (":"
5225 (push '(:grouptags) alist))
5226 ((guard (string-match tag-re token))
5227 (let ((tag (match-string 1 token))
5228 (key (and (match-beginning 2)
5229 (string-to-char (match-string 2 token)))))
5230 ;; Push all tags in groups, no matter if they already
5231 ;; appear somewhere else in the list.
5232 (when (or group-flag (not (assoc tag alist)))
5233 (push (cons tag key) alist))))))))))
5235 (defun org-tag-alist-to-string (alist &optional skip-key)
5236 "Return tag string associated to ALIST.
5238 ALIST is an alist, as defined in `org-tag-alist' or
5239 `org-tag-persistent-alist', or produced with
5240 `org-tag-string-to-alist'.
5242 Return value is a string suitable as a value for \"TAGS\"
5243 keyword.
5245 When optional argument SKIP-KEY is non-nil, skip selection keys
5246 next to tags."
5247 (mapconcat (lambda (token)
5248 (pcase token
5249 (`(:startgroup) "{")
5250 (`(:endgroup) "}")
5251 (`(:startgrouptag) "[")
5252 (`(:endgrouptag) "]")
5253 (`(:grouptags) ":")
5254 (`(:newline) "\\n")
5255 ((and
5256 (guard (not skip-key))
5257 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5258 (format "%s(%c)" tag key))
5259 (`(,(and tag (pred stringp)) . ,_) tag)
5260 (_ (user-error "Invalid tag token: %S" token))))
5261 alist
5262 " "))
5264 (defun org-tag-alist-to-groups (alist)
5265 "Return group alist from tag ALIST.
5266 ALIST is an alist, as defined in `org-tag-alist' or
5267 `org-tag-persistent-alist', or produced with
5268 `org-tag-string-to-alist'. Return value is an alist following
5269 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5270 a string, summarizing TAGS, as a list of strings."
5271 (let (groups group-status current-group)
5272 (dolist (token alist (nreverse groups))
5273 (pcase token
5274 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5275 (`(,(or :endgroup :endgrouptag))
5276 (when (eq group-status 'append)
5277 (push (nreverse current-group) groups))
5278 (setq group-status nil))
5279 (`(:grouptags) (setq group-status 'append))
5280 ((and `(,tag . ,_) (guard group-status))
5281 (if (eq group-status 'append) (push tag current-group)
5282 (setq current-group (list tag))))
5283 (_ nil)))))
5285 (defvar org--file-cache (make-hash-table :test #'equal)
5286 "Hash table to store contents of files referenced via a URL.
5287 This is the cache of file URLs read using `org-file-contents'.")
5289 (defun org-reset-file-cache ()
5290 "Reset the cache of files downloaded by `org-file-contents'."
5291 (clrhash org--file-cache))
5293 (defun org-file-url-p (file)
5294 "Non-nil if FILE is a URL."
5295 (require 'ffap)
5296 (string-match-p ffap-url-regexp file))
5298 (defun org-file-contents (file &optional noerror nocache)
5299 "Return the contents of FILE, as a string.
5301 FILE can be a file name or URL.
5303 If FILE is a URL, download the contents. If the URL contents are
5304 already cached in the `org--file-cache' hash table, the download step
5305 is skipped.
5307 If NOERROR is non-nil, ignore the error when unable to read the FILE
5308 from file or URL.
5310 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5311 is available. This option applies only if FILE is a URL."
5312 (let* ((is-url (org-file-url-p file))
5313 (cache (and is-url
5314 (not nocache)
5315 (gethash file org--file-cache))))
5316 (cond
5317 (cache)
5318 (is-url
5319 (with-current-buffer (url-retrieve-synchronously file)
5320 (goto-char (point-min))
5321 ;; Move point to after the url-retrieve header.
5322 (search-forward "\n\n" nil :move)
5323 ;; Search for the success code only in the url-retrieve header.
5324 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5325 ;; Update the cache `org--file-cache' and return contents.
5326 (puthash file
5327 (buffer-substring-no-properties (point) (point-max))
5328 org--file-cache)
5329 (funcall (if noerror #'message #'user-error)
5330 "Unable to fetch file from %S"
5331 file))))
5333 (with-temp-buffer
5334 (condition-case err
5335 (progn
5336 (insert-file-contents file)
5337 (buffer-string))
5338 (file-error
5339 (funcall (if noerror #'message #'user-error)
5340 (error-message-string err)))))))))
5342 (defun org-extract-log-state-settings (x)
5343 "Extract the log state setting from a TODO keyword string.
5344 This will extract info from a string like \"WAIT(w@/!)\"."
5345 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5346 (let ((kw (match-string 1 x))
5347 (log1 (and (match-end 3) (match-string 3 x)))
5348 (log2 (and (match-end 4) (match-string 4 x))))
5349 (and (or log1 log2)
5350 (list kw
5351 (and log1 (if (equal log1 "!") 'time 'note))
5352 (and log2 (if (equal log2 "!") 'time 'note)))))))
5354 (defun org-remove-keyword-keys (list)
5355 "Remove a pair of parenthesis at the end of each string in LIST."
5356 (mapcar (lambda (x)
5357 (if (string-match "(.*)$" x)
5358 (substring x 0 (match-beginning 0))
5360 list))
5362 (defun org-assign-fast-keys (alist)
5363 "Assign fast keys to a keyword-key alist.
5364 Respect keys that are already there."
5365 (let (new e (alt ?0))
5366 (while (setq e (pop alist))
5367 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5368 (cdr e)) ;; Key already assigned.
5369 (push e new)
5370 (let ((clist (string-to-list (downcase (car e))))
5371 (used (append new alist)))
5372 (when (= (car clist) ?@)
5373 (pop clist))
5374 (while (and clist (rassoc (car clist) used))
5375 (pop clist))
5376 (unless clist
5377 (while (rassoc alt used)
5378 (cl-incf alt)))
5379 (push (cons (car e) (or (car clist) alt)) new))))
5380 (nreverse new)))
5382 ;;; Some variables used in various places
5384 (defvar org-window-configuration nil
5385 "Used in various places to store a window configuration.")
5386 (defvar org-selected-window nil
5387 "Used in various places to store a window configuration.")
5388 (defvar org-finish-function nil
5389 "Function to be called when `C-c C-c' is used.
5390 This is for getting out of special buffers like capture.")
5391 (defvar org-last-state)
5393 ;; Defined somewhere in this file, but used before definition.
5394 (defvar org-entities) ;; defined in org-entities.el
5395 (defvar org-struct-menu)
5396 (defvar org-org-menu)
5397 (defvar org-tbl-menu)
5399 ;;;; Define the Org mode
5401 ;; We use a before-change function to check if a table might need
5402 ;; an update.
5403 (defvar org-table-may-need-update t
5404 "Indicates that a table might need an update.
5405 This variable is set by `org-before-change-function'.
5406 `org-table-align' sets it back to nil.")
5407 (defun org-before-change-function (_beg _end)
5408 "Every change indicates that a table might need an update."
5409 (setq org-table-may-need-update t))
5410 (defvar org-mode-map)
5411 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5412 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5413 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5414 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5415 (defvar org-table-buffer-is-an nil)
5417 (defvar bidi-paragraph-direction)
5418 (defvar buffer-face-mode-face)
5420 (require 'outline)
5422 ;; Other stuff we need.
5423 (require 'time-date)
5424 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5425 (require 'easymenu)
5426 (autoload 'easy-menu-add "easymenu")
5427 (require 'overlay)
5429 ;; (require 'org-macs) moved higher up in the file before it is first used
5430 (require 'org-entities)
5431 ;; (require 'org-compat) moved higher up in the file before it is first used
5432 (require 'org-faces)
5433 (require 'org-list)
5434 (require 'org-pcomplete)
5435 (require 'org-src)
5436 (require 'org-footnote)
5437 (require 'org-macro)
5439 ;; babel
5440 (require 'ob)
5442 ;;;###autoload
5443 (define-derived-mode org-mode outline-mode "Org"
5444 "Outline-based notes management and organizer, alias
5445 \"Carsten's outline-mode for keeping track of everything.\"
5447 Org mode develops organizational tasks around a NOTES file which
5448 contains information about projects as plain text. Org mode is
5449 implemented on top of Outline mode, which is ideal to keep the content
5450 of large files well structured. It supports ToDo items, deadlines and
5451 time stamps, which magically appear in the diary listing of the Emacs
5452 calendar. Tables are easily created with a built-in table editor.
5453 Plain text URL-like links connect to websites, emails (VM), Usenet
5454 messages (Gnus), BBDB entries, and any files related to the project.
5455 For printing and sharing of notes, an Org file (or a part of it)
5456 can be exported as a structured ASCII or HTML file.
5458 The following commands are available:
5460 \\{org-mode-map}"
5462 ;; Get rid of Outline menus, they are not needed
5463 ;; Need to do this here because define-derived-mode sets up
5464 ;; the keymap so late. Still, it is a waste to call this each time
5465 ;; we switch another buffer into Org mode.
5466 (define-key org-mode-map [menu-bar headings] 'undefined)
5467 (define-key org-mode-map [menu-bar hide] 'undefined)
5468 (define-key org-mode-map [menu-bar show] 'undefined)
5470 (org-load-modules-maybe)
5471 (org-install-agenda-files-menu)
5472 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5473 (add-to-invisibility-spec '(org-cwidth))
5474 (add-to-invisibility-spec '(org-hide-block . t))
5475 (setq-local outline-regexp org-outline-regexp)
5476 (setq-local outline-level 'org-outline-level)
5477 (setq bidi-paragraph-direction 'left-to-right)
5478 (when (and org-ellipsis
5479 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5480 (fboundp 'make-glyph-code))
5481 (unless org-display-table
5482 (setq org-display-table (make-display-table)))
5483 (set-display-table-slot
5484 org-display-table 4
5485 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5486 (if (stringp org-ellipsis) org-ellipsis "..."))))
5487 (setq buffer-display-table org-display-table))
5488 (org-set-regexps-and-options)
5489 (org-set-font-lock-defaults)
5490 (when (and org-tag-faces (not org-tags-special-faces-re))
5491 ;; tag faces set outside customize.... force initialization.
5492 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5493 ;; Calc embedded
5494 (setq-local calc-embedded-open-mode "# ")
5495 ;; Modify a few syntax entries
5496 (modify-syntax-entry ?@ "w")
5497 (modify-syntax-entry ?\" "\"")
5498 (modify-syntax-entry ?\\ "_")
5499 (modify-syntax-entry ?~ "_")
5500 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5501 ;; Activate before-change-function
5502 (setq-local org-table-may-need-update t)
5503 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5504 ;; Check for running clock before killing a buffer
5505 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5506 ;; Initialize macros templates.
5507 (org-macro-initialize-templates)
5508 ;; Initialize radio targets.
5509 (org-update-radio-target-regexp)
5510 ;; Indentation.
5511 (setq-local indent-line-function 'org-indent-line)
5512 (setq-local indent-region-function 'org-indent-region)
5513 ;; Filling and auto-filling.
5514 (org-setup-filling)
5515 ;; Comments.
5516 (org-setup-comments-handling)
5517 ;; Initialize cache.
5518 (org-element-cache-reset)
5519 ;; Beginning/end of defun
5520 (setq-local beginning-of-defun-function 'org-backward-element)
5521 (setq-local end-of-defun-function
5522 (lambda ()
5523 (if (not (org-at-heading-p))
5524 (org-forward-element)
5525 (org-forward-element)
5526 (forward-char -1))))
5527 ;; Next error for sparse trees
5528 (setq-local next-error-function 'org-occur-next-match)
5529 ;; Make sure dependence stuff works reliably, even for users who set it
5530 ;; too late :-(
5531 (if org-enforce-todo-dependencies
5532 (add-hook 'org-blocker-hook
5533 'org-block-todo-from-children-or-siblings-or-parent)
5534 (remove-hook 'org-blocker-hook
5535 'org-block-todo-from-children-or-siblings-or-parent))
5536 (if org-enforce-todo-checkbox-dependencies
5537 (add-hook 'org-blocker-hook
5538 'org-block-todo-from-checkboxes)
5539 (remove-hook 'org-blocker-hook
5540 'org-block-todo-from-checkboxes))
5542 ;; Align options lines
5543 (setq-local
5544 align-mode-rules-list
5545 '((org-in-buffer-settings
5546 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5547 (modes . '(org-mode)))))
5549 ;; Imenu
5550 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5552 ;; Make isearch reveal context
5553 (setq-local outline-isearch-open-invisible-function
5554 (lambda (&rest _) (org-show-context 'isearch)))
5556 ;; Setup the pcomplete hooks
5557 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5558 (setq-local pcomplete-command-name-function 'org-command-at-point)
5559 (setq-local pcomplete-default-completion-function 'ignore)
5560 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5561 (setq-local pcomplete-termination-string "")
5562 (setq-local buffer-face-mode-face 'org-default)
5564 ;; If empty file that did not turn on Org mode automatically, make
5565 ;; it to.
5566 (when (and org-insert-mode-line-in-empty-file
5567 (called-interactively-p 'any)
5568 (= (point-min) (point-max)))
5569 (insert "# -*- mode: org -*-\n\n"))
5570 (unless org-inhibit-startup
5571 (org-unmodified
5572 (when org-startup-with-beamer-mode (org-beamer-mode))
5573 (when org-startup-align-all-tables
5574 (org-table-map-tables #'org-table-align t))
5575 (when org-startup-with-inline-images (org-display-inline-images))
5576 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5577 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5578 (when org-startup-truncated (setq truncate-lines t))
5579 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5580 (org-refresh-effort-properties)))
5581 ;; Try to set `org-hide' face correctly.
5582 (let ((foreground (org-find-invisible-foreground)))
5583 (when foreground
5584 (set-face-foreground 'org-hide foreground))))
5586 ;; Update `customize-package-emacs-version-alist'
5587 (add-to-list 'customize-package-emacs-version-alist
5588 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5589 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5590 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5591 ("9.0" . "26.1")))
5593 (defvar org-mode-transpose-word-syntax-table
5594 (let ((st (make-syntax-table text-mode-syntax-table)))
5595 (dolist (c org-emphasis-alist st)
5596 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5598 (when (fboundp 'abbrev-table-put)
5599 (abbrev-table-put org-mode-abbrev-table
5600 :parents (list text-mode-abbrev-table)))
5602 (defun org-find-invisible-foreground ()
5603 (let ((candidates (remove
5604 "unspecified-bg"
5605 (nconc
5606 (list (face-background 'default)
5607 (face-background 'org-default))
5608 (mapcar
5609 (lambda (alist)
5610 (when (boundp alist)
5611 (cdr (assq 'background-color (symbol-value alist)))))
5612 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5613 (list (face-foreground 'org-hide))))))
5614 (car (remove nil candidates))))
5616 (defun org-current-time (&optional rounding-minutes past)
5617 "Current time, possibly rounded to ROUNDING-MINUTES.
5618 When ROUNDING-MINUTES is not an integer, fall back on the car of
5619 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5620 the rounding returns a past time."
5621 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5622 (car org-time-stamp-rounding-minutes)))
5623 (time (decode-time)) res)
5624 (if (< r 1)
5625 (current-time)
5626 (setq res
5627 (apply 'encode-time
5628 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5629 (nthcdr 2 time))))
5630 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5631 (seconds-to-time (- (float-time res) (* r 60)))
5632 res))))
5634 (defun org-today ()
5635 "Return today date, considering `org-extend-today-until'."
5636 (time-to-days
5637 (time-subtract (current-time)
5638 (list 0 (* 3600 org-extend-today-until) 0))))
5640 ;;;; Font-Lock stuff, including the activators
5642 (defvar org-mouse-map (make-sparse-keymap))
5643 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5644 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5645 (when org-mouse-1-follows-link
5646 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5647 (when org-tab-follows-link
5648 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5649 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5651 (require 'font-lock)
5653 (defconst org-non-link-chars "]\t\n\r<>")
5654 (defvar org-link-types-re nil
5655 "Matches a link that has a url-like prefix like \"http:\"")
5656 (defvar org-link-re-with-space nil
5657 "Matches a link with spaces, optional angular brackets around it.")
5658 (defvar org-link-re-with-space2 nil
5659 "Matches a link with spaces, optional angular brackets around it.")
5660 (defvar org-link-re-with-space3 nil
5661 "Matches a link with spaces, only for internal part in bracket links.")
5662 (defvar org-angle-link-re nil
5663 "Matches link with angular brackets, spaces are allowed.")
5664 (defvar org-plain-link-re nil
5665 "Matches plain link, without spaces.")
5666 (defvar org-bracket-link-regexp nil
5667 "Matches a link in double brackets.")
5668 (defvar org-bracket-link-analytic-regexp nil
5669 "Regular expression used to analyze links.
5670 Here is what the match groups contain after a match:
5671 1: http:
5672 2: http
5673 3: path
5674 4: [desc]
5675 5: desc")
5676 (defvar org-bracket-link-analytic-regexp++ nil
5677 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5678 (defvar org-any-link-re nil
5679 "Regular expression matching any link.")
5681 (defconst org-match-sexp-depth 3
5682 "Number of stacked braces for sub/superscript matching.")
5684 (defun org-create-multibrace-regexp (left right n)
5685 "Create a regular expression which will match a balanced sexp.
5686 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5687 as single character strings.
5688 The regexp returned will match the entire expression including the
5689 delimiters. It will also define a single group which contains the
5690 match except for the outermost delimiters. The maximum depth of
5691 stacked delimiters is N. Escaping delimiters is not possible."
5692 (let* ((nothing (concat "[^" left right "]*?"))
5693 (or "\\|")
5694 (re nothing)
5695 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5696 (while (> n 1)
5697 (setq n (1- n)
5698 re (concat re or next)
5699 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5700 (concat left "\\(" re "\\)" right)))
5702 (defconst org-match-substring-regexp
5703 (concat
5704 "\\(\\S-\\)\\([_^]\\)\\("
5705 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5706 "\\|"
5707 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5708 "\\|"
5709 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5710 "The regular expression matching a sub- or superscript.")
5712 (defconst org-match-substring-with-braces-regexp
5713 (concat
5714 "\\(\\S-\\)\\([_^]\\)"
5715 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5716 "The regular expression matching a sub- or superscript, forcing braces.")
5718 (defun org-make-link-regexps ()
5719 "Update the link regular expressions.
5720 This should be called after the variable `org-link-parameters' has changed."
5721 (let ((types-re (regexp-opt (org-link-types) t)))
5722 (setq org-link-types-re
5723 (concat "\\`" types-re ":")
5724 org-link-re-with-space
5725 (concat "<?" types-re ":"
5726 "\\([^" org-non-link-chars " ]"
5727 "[^" org-non-link-chars "]*"
5728 "[^" org-non-link-chars " ]\\)>?")
5729 org-link-re-with-space2
5730 (concat "<?" types-re ":"
5731 "\\([^" org-non-link-chars " ]"
5732 "[^\t\n\r]*"
5733 "[^" org-non-link-chars " ]\\)>?")
5734 org-link-re-with-space3
5735 (concat "<?" types-re ":"
5736 "\\([^" org-non-link-chars " ]"
5737 "[^\t\n\r]*\\)")
5738 org-angle-link-re
5739 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5740 types-re)
5741 org-plain-link-re
5742 (concat
5743 "\\<" types-re ":"
5744 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5745 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5746 org-bracket-link-regexp
5747 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5748 org-bracket-link-analytic-regexp
5749 (concat
5750 "\\[\\["
5751 "\\(" types-re ":\\)?"
5752 "\\([^]]+\\)"
5753 "\\]"
5754 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5755 "\\]")
5756 org-bracket-link-analytic-regexp++
5757 (concat
5758 "\\[\\["
5759 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5760 "\\([^]]+\\)"
5761 "\\]"
5762 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5763 "\\]")
5764 org-any-link-re
5765 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5766 org-angle-link-re "\\)\\|\\("
5767 org-plain-link-re "\\)"))))
5769 (org-make-link-regexps)
5771 (defvar org-emph-face nil)
5773 (defun org-do-emphasis-faces (limit)
5774 "Run through the buffer and emphasize strings."
5775 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5776 (car org-emphasis-regexp-components))))
5777 (catch :exit
5778 (while (re-search-forward quick-re limit t)
5779 (let* ((marker (match-string 2))
5780 (verbatim? (member marker '("~" "="))))
5781 (when (save-excursion
5782 (goto-char (match-beginning 0))
5783 ;; Do not match headline stars. Do not consider
5784 ;; stars of a headline as closing marker for bold
5785 ;; markup either.
5786 (and (not (looking-at-p org-outline-regexp-bol))
5787 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5788 (not (string-match-p
5789 (concat org-outline-regexp-bol "\\'")
5790 (match-string 0)))))
5791 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5792 (font-lock-prepend-text-property
5793 (match-beginning 2) (match-end 2) 'face face)
5794 (when verbatim?
5795 (org-remove-flyspell-overlays-in
5796 (match-beginning 0) (match-end 0)))
5797 (add-text-properties (match-beginning 2) (match-end 2)
5798 '(font-lock-multiline t org-emphasis t))
5799 (when org-hide-emphasis-markers
5800 (add-text-properties (match-end 4) (match-beginning 5)
5801 '(invisible org-link))
5802 (add-text-properties (match-beginning 3) (match-end 3)
5803 '(invisible org-link)))
5804 (throw :exit t))))))))
5806 (defun org-emphasize (&optional char)
5807 "Insert or change an emphasis, i.e. a font like bold or italic.
5808 If there is an active region, change that region to a new emphasis.
5809 If there is no region, just insert the marker characters and position
5810 the cursor between them.
5811 CHAR should be the marker character. If it is a space, it means to
5812 remove the emphasis of the selected region.
5813 If CHAR is not given (for example in an interactive call) it will be
5814 prompted for."
5815 (interactive)
5816 (let ((erc org-emphasis-regexp-components)
5817 (string "") beg end move s)
5818 (if (org-region-active-p)
5819 (setq beg (region-beginning)
5820 end (region-end)
5821 string (buffer-substring beg end))
5822 (setq move t))
5824 (unless char
5825 (message "Emphasis marker or tag: [%s]"
5826 (mapconcat #'car org-emphasis-alist ""))
5827 (setq char (read-char-exclusive)))
5828 (if (equal char ?\s)
5829 (setq s ""
5830 move nil)
5831 (unless (assoc (char-to-string char) org-emphasis-alist)
5832 (user-error "No such emphasis marker: \"%c\"" char))
5833 (setq s (char-to-string char)))
5834 (while (and (> (length string) 1)
5835 (equal (substring string 0 1) (substring string -1))
5836 (assoc (substring string 0 1) org-emphasis-alist))
5837 (setq string (substring string 1 -1)))
5838 (setq string (concat s string s))
5839 (when beg (delete-region beg end))
5840 (unless (or (bolp)
5841 (string-match (concat "[" (nth 0 erc) "\n]")
5842 (char-to-string (char-before (point)))))
5843 (insert " "))
5844 (unless (or (eobp)
5845 (string-match (concat "[" (nth 1 erc) "\n]")
5846 (char-to-string (char-after (point)))))
5847 (insert " ") (backward-char 1))
5848 (insert string)
5849 (and move (backward-char 1))))
5851 (defconst org-nonsticky-props
5852 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5854 (defsubst org-rear-nonsticky-at (pos)
5855 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5857 (defun org-activate-links (limit)
5858 "Add link properties to links.
5859 This includes angle, plain, and bracket links."
5860 (catch :exit
5861 (while (re-search-forward org-any-link-re limit t)
5862 (let* ((start (match-beginning 0))
5863 (end (match-end 0))
5864 (type (cond ((eq ?< (char-after start)) 'angle)
5865 ((eq ?\[ (char-after (1+ start))) 'bracket)
5866 (t 'plain))))
5867 (when (and (memq type org-highlight-links)
5868 ;; Do not confuse plain links with tags.
5869 (not (and (eq type 'plain)
5870 (let ((face (get-text-property
5871 (max (1- start) (point-min)) 'face)))
5872 (if (consp face) (memq 'org-tag face)
5873 (eq 'org-tag face))))))
5874 (let* ((link-object (save-excursion
5875 (goto-char start)
5876 (save-match-data (org-element-link-parser))))
5877 (link (org-element-property :raw-link link-object))
5878 (path (org-element-property :path link-object))
5879 (properties ;for link's visible part
5880 (list
5881 'face (pcase (org-link-get-parameter type :face)
5882 ((and (pred functionp) face) (funcall face path))
5883 ((and (pred facep) face) face)
5884 ((and (pred consp) face) face) ;anonymous
5885 (_ 'org-link))
5886 'mouse-face (or (org-link-get-parameter type :mouse-face)
5887 'highlight)
5888 'keymap (or (org-link-get-parameter type :keymap)
5889 org-mouse-map)
5890 'help-echo (pcase (org-link-get-parameter type :help-echo)
5891 ((and (pred stringp) echo) echo)
5892 ((and (pred functionp) echo) echo)
5893 (_ (concat "LINK: " link)))
5894 'htmlize-link (pcase (org-link-get-parameter type
5895 :htmlize-link)
5896 ((and (pred functionp) f) (funcall f))
5897 (_ `(:uri ,link)))
5898 'font-lock-multiline t)))
5899 (org-remove-flyspell-overlays-in start end)
5900 (org-rear-nonsticky-at end)
5901 (if (not (eq 'bracket type))
5902 (add-text-properties start end properties)
5903 ;; Handle invisible parts in bracket links.
5904 (remove-text-properties start end '(invisible nil))
5905 (let ((hidden
5906 (append `(invisible
5907 ,(or (org-link-get-parameter type :display)
5908 'org-link))
5909 properties))
5910 (visible-start (or (match-beginning 4) (match-beginning 2)))
5911 (visible-end (or (match-end 4) (match-end 2))))
5912 (add-text-properties start visible-start hidden)
5913 (add-text-properties visible-start visible-end properties)
5914 (add-text-properties visible-end end hidden)
5915 (org-rear-nonsticky-at visible-start)
5916 (org-rear-nonsticky-at visible-end)))
5917 (let ((f (org-link-get-parameter type :activate-func)))
5918 (when (functionp f)
5919 (funcall f start end path (eq type 'bracket))))
5920 (throw :exit t))))) ;signal success
5921 nil))
5923 (defun org-activate-code (limit)
5924 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5925 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5926 (remove-text-properties (match-beginning 0) (match-end 0)
5927 '(display t invisible t intangible t))
5930 (defcustom org-src-fontify-natively t
5931 "When non-nil, fontify code in code blocks.
5932 See also the `org-block' face."
5933 :type 'boolean
5934 :version "24.4"
5935 :package-version '(Org . "8.3")
5936 :group 'org-appearance
5937 :group 'org-babel)
5939 (defcustom org-allow-promoting-top-level-subtree nil
5940 "When non-nil, allow promoting a top level subtree.
5941 The leading star of the top level headline will be replaced
5942 by a #."
5943 :type 'boolean
5944 :version "24.1"
5945 :group 'org-appearance)
5947 (defun org-fontify-meta-lines-and-blocks (limit)
5948 (condition-case nil
5949 (org-fontify-meta-lines-and-blocks-1 limit)
5950 (error (message "org-mode fontification error in %S at %d"
5951 (current-buffer)
5952 (line-number-at-pos)))))
5954 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5955 "Fontify #+ lines and blocks."
5956 (let ((case-fold-search t))
5957 (when (re-search-forward
5958 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5959 limit t)
5960 (let ((beg (match-beginning 0))
5961 (block-start (match-end 0))
5962 (block-end nil)
5963 (lang (match-string 7))
5964 (beg1 (line-beginning-position 2))
5965 (dc1 (downcase (match-string 2)))
5966 (dc3 (downcase (match-string 3)))
5967 end end1 quoting block-type)
5968 (cond
5969 ((and (match-end 4) (equal dc3 "+begin"))
5970 ;; Truly a block
5971 (setq block-type (downcase (match-string 5))
5972 quoting (member block-type org-protecting-blocks))
5973 (when (re-search-forward
5974 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5975 nil t) ;; on purpose, we look further than LIMIT
5976 (setq end (min (point-max) (match-end 0))
5977 end1 (min (point-max) (1- (match-beginning 0))))
5978 (setq block-end (match-beginning 0))
5979 (when quoting
5980 (org-remove-flyspell-overlays-in beg1 end1)
5981 (remove-text-properties beg end
5982 '(display t invisible t intangible t)))
5983 (add-text-properties
5984 beg end '(font-lock-fontified t font-lock-multiline t))
5985 (add-text-properties beg beg1 '(face org-meta-line))
5986 (org-remove-flyspell-overlays-in beg beg1)
5987 (add-text-properties ; For end_src
5988 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5989 (org-remove-flyspell-overlays-in end1 end)
5990 (cond
5991 ((and lang (not (string= lang "")) org-src-fontify-natively)
5992 (org-src-font-lock-fontify-block lang block-start block-end)
5993 (add-text-properties beg1 block-end '(src-block t)))
5994 (quoting
5995 (add-text-properties beg1 (min (point-max) (1+ end1))
5996 (list 'face
5997 (list :inherit
5998 (let ((face-name
5999 (intern (format "org-block-%s" lang))))
6000 (append (and (facep face-name) (list face-name))
6001 '(org-block))))))) ; end of source block
6002 ((not org-fontify-quote-and-verse-blocks))
6003 ((string= block-type "quote")
6004 (add-face-text-property
6005 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6006 ((string= block-type "verse")
6007 (add-face-text-property
6008 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6009 (add-text-properties beg beg1 '(face org-block-begin-line))
6010 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6011 '(face org-block-end-line))
6013 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6014 (org-remove-flyspell-overlays-in
6015 (match-beginning 0)
6016 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6017 (add-text-properties
6018 beg (match-end 3)
6019 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6020 '(font-lock-fontified t invisible t)
6021 '(font-lock-fontified t face org-document-info-keyword)))
6022 (add-text-properties
6023 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6024 (if (string-equal dc1 "+title:")
6025 '(font-lock-fontified t face org-document-title)
6026 '(font-lock-fontified t face org-document-info))))
6027 ((string-prefix-p "+caption" dc1)
6028 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6029 (remove-text-properties (match-beginning 0) (match-end 0)
6030 '(display t invisible t intangible t))
6031 ;; Handle short captions.
6032 (save-excursion
6033 (beginning-of-line)
6034 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6035 (add-text-properties (line-beginning-position) (match-end 1)
6036 '(font-lock-fontified t face org-meta-line))
6037 (add-text-properties (match-end 0) (line-end-position)
6038 '(font-lock-fontified t face org-block))
6040 ((member dc3 '(" " ""))
6041 (org-remove-flyspell-overlays-in beg (match-end 0))
6042 (add-text-properties
6043 beg (match-end 0)
6044 '(font-lock-fontified t face font-lock-comment-face)))
6045 (t ;; just any other in-buffer setting, but not indented
6046 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6047 (remove-text-properties (match-beginning 0) (match-end 0)
6048 '(display t invisible t intangible t))
6049 (add-text-properties beg (match-end 0)
6050 '(font-lock-fontified t face org-meta-line))
6051 t))))))
6053 (defun org-fontify-drawers (limit)
6054 "Fontify drawers."
6055 (when (re-search-forward org-drawer-regexp limit t)
6056 (add-text-properties
6057 (match-beginning 0) (match-end 0)
6058 '(font-lock-fontified t face org-special-keyword))
6059 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6062 (defun org-fontify-macros (limit)
6063 "Fontify macros."
6064 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6065 (add-text-properties
6066 (match-beginning 0) (match-end 0)
6067 '(font-lock-fontified t face org-macro))
6068 (when org-hide-macro-markers
6069 (add-text-properties (match-end 2) (match-beginning 2)
6070 '(invisible t))
6071 (add-text-properties (match-beginning 1) (match-end 1)
6072 '(invisible t)))
6073 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6076 (defun org-activate-footnote-links (limit)
6077 "Add text properties for footnotes."
6078 (let ((fn (org-footnote-next-reference-or-definition limit)))
6079 (when fn
6080 (let* ((beg (nth 1 fn))
6081 (end (nth 2 fn))
6082 (label (car fn))
6083 (referencep (/= (line-beginning-position) beg)))
6084 (when (and referencep (nth 3 fn))
6085 (save-excursion
6086 (goto-char beg)
6087 (search-forward (or label "fn:"))
6088 (org-remove-flyspell-overlays-in beg (match-end 0))))
6089 (add-text-properties beg end
6090 (list 'mouse-face 'highlight
6091 'keymap org-mouse-map
6092 'help-echo
6093 (if referencep "Footnote reference"
6094 "Footnote definition")
6095 'font-lock-fontified t
6096 'font-lock-multiline t
6097 'face 'org-footnote))))))
6099 (defun org-activate-dates (limit)
6100 "Add text properties for dates."
6101 (when (and (re-search-forward org-tsr-regexp-both limit t)
6102 (not (equal (char-before (match-beginning 0)) 91)))
6103 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6104 (add-text-properties (match-beginning 0) (match-end 0)
6105 (list 'mouse-face 'highlight
6106 'keymap org-mouse-map))
6107 (org-rear-nonsticky-at (match-end 0))
6108 (when org-display-custom-times
6109 (if (match-end 3)
6110 (org-display-custom-time (match-beginning 3) (match-end 3))
6111 (org-display-custom-time (match-beginning 1) (match-end 1))))
6114 (defvar-local org-target-link-regexp nil
6115 "Regular expression matching radio targets in plain text.")
6117 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6118 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6119 border border border))
6120 "Regular expression matching a link target.")
6122 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6123 "Regular expression matching a radio target.")
6125 (defconst org-any-target-regexp
6126 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6127 "Regular expression matching any target.")
6129 (defun org-activate-target-links (limit)
6130 "Add text properties for target matches."
6131 (when org-target-link-regexp
6132 (let ((case-fold-search t))
6133 (when (re-search-forward org-target-link-regexp limit t)
6134 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6135 (add-text-properties (match-beginning 1) (match-end 1)
6136 (list 'mouse-face 'highlight
6137 'keymap org-mouse-map
6138 'help-echo "Radio target link"
6139 'org-linked-text t))
6140 (org-rear-nonsticky-at (match-end 1))
6141 t))))
6143 (defun org-update-radio-target-regexp ()
6144 "Find all radio targets in this file and update the regular expression.
6145 Also refresh fontification if needed."
6146 (interactive)
6147 (let ((old-regexp org-target-link-regexp)
6148 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6149 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6150 (targets
6151 (org-with-wide-buffer
6152 (goto-char (point-min))
6153 (let (rtn)
6154 (while (re-search-forward org-radio-target-regexp nil t)
6155 ;; Make sure point is really within the object.
6156 (backward-char)
6157 (let ((obj (org-element-context)))
6158 (when (eq (org-element-type obj) 'radio-target)
6159 (cl-pushnew (org-element-property :value obj) rtn
6160 :test #'equal))))
6161 rtn))))
6162 (setq org-target-link-regexp
6163 (and targets
6164 (concat before-re
6165 (mapconcat
6166 (lambda (x)
6167 (replace-regexp-in-string
6168 " +" "\\s-+" (regexp-quote x) t t))
6169 targets
6170 "\\|")
6171 after-re)))
6172 (unless (equal old-regexp org-target-link-regexp)
6173 ;; Clean-up cache.
6174 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6175 ((not org-target-link-regexp) old-regexp)
6177 (concat before-re
6178 (mapconcat
6179 (lambda (re)
6180 (substring re (length before-re)
6181 (- (length after-re))))
6182 (list old-regexp org-target-link-regexp)
6183 "\\|")
6184 after-re)))))
6185 (org-with-wide-buffer
6186 (goto-char (point-min))
6187 (while (re-search-forward regexp nil t)
6188 (org-element-cache-refresh (match-beginning 1)))))
6189 ;; Re fontify buffer.
6190 (when (memq 'radio org-highlight-links)
6191 (org-restart-font-lock)))))
6193 (defun org-hide-wide-columns (limit)
6194 (let (s e)
6195 (setq s (text-property-any (point) (or limit (point-max))
6196 'org-cwidth t))
6197 (when s
6198 (setq e (next-single-property-change s 'org-cwidth))
6199 (add-text-properties s e '(invisible org-cwidth))
6200 (goto-char e)
6201 t)))
6203 (defvar org-latex-and-related-regexp nil
6204 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6206 (defun org-compute-latex-and-related-regexp ()
6207 "Compute regular expression for LaTeX, entities and sub/superscript.
6208 Result depends on variable `org-highlight-latex-and-related'."
6209 (setq-local
6210 org-latex-and-related-regexp
6211 (let* ((re-sub
6212 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6213 ((eq org-use-sub-superscripts '{})
6214 (list org-match-substring-with-braces-regexp))
6215 (org-use-sub-superscripts (list org-match-substring-regexp))))
6216 (re-latex
6217 (when (memq 'latex org-highlight-latex-and-related)
6218 (let ((matchers (plist-get org-format-latex-options :matchers)))
6219 (delq nil
6220 (mapcar (lambda (x)
6221 (and (member (car x) matchers) (nth 1 x)))
6222 org-latex-regexps)))))
6223 (re-entities
6224 (when (memq 'entities org-highlight-latex-and-related)
6225 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6226 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6228 (defun org-do-latex-and-related (limit)
6229 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6230 LIMIT bounds the search for syntax to highlight. Stop at first
6231 highlighted object, if any. Return t if some highlighting was
6232 done, nil otherwise."
6233 (when (org-string-nw-p org-latex-and-related-regexp)
6234 (catch 'found
6235 (while (re-search-forward org-latex-and-related-regexp limit t)
6236 (unless
6237 (cl-some
6238 (lambda (f)
6239 (memq f '(org-code org-verbatim underline org-special-keyword)))
6240 (save-excursion
6241 (goto-char (1+ (match-beginning 0)))
6242 (face-at-point nil t)))
6243 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6244 '(?_ ?^))
6246 0)))
6247 (font-lock-prepend-text-property
6248 (+ offset (match-beginning 0)) (match-end 0)
6249 'face 'org-latex-and-related)
6250 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6251 '(font-lock-multiline t)))
6252 (throw 'found t)))
6253 nil)))
6255 (defun org-restart-font-lock ()
6256 "Restart `font-lock-mode', to force refontification."
6257 (when (and (boundp 'font-lock-mode) font-lock-mode)
6258 (font-lock-mode -1)
6259 (font-lock-mode 1)))
6261 (defun org-activate-tags (limit)
6262 (when (re-search-forward
6263 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6264 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6265 (add-text-properties (match-beginning 1) (match-end 1)
6266 (list 'mouse-face 'highlight
6267 'keymap org-mouse-map))
6268 (org-rear-nonsticky-at (match-end 1))
6271 (defun org-outline-level ()
6272 "Compute the outline level of the heading at point.
6274 If this is called at a normal headline, the level is the number
6275 of stars. Use `org-reduced-level' to remove the effect of
6276 `org-odd-levels'. Unlike to `org-current-level', this function
6277 takes into consideration inlinetasks."
6278 (org-with-wide-buffer
6279 (end-of-line)
6280 (if (re-search-backward org-outline-regexp-bol nil t)
6281 (1- (- (match-end 0) (match-beginning 0)))
6282 0)))
6284 (defvar org-font-lock-keywords nil)
6286 (defsubst org-re-property (property &optional literal allow-null value)
6287 "Return a regexp matching a PROPERTY line.
6289 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6290 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6291 non-nil, match properties even without a value.
6293 Match group 3 is set to the value when it exists. If there is no
6294 value and ALLOW-NULL is non-nil, it is set to the empty string.
6296 With optional argument VALUE, match only property lines with
6297 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6298 unless LITERAL is non-nil."
6299 (concat
6300 "^\\(?4:[ \t]*\\)"
6301 (format "\\(?1::\\(?2:%s\\):\\)"
6302 (if literal property (regexp-quote property)))
6303 (cond (value
6304 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6305 (if literal value (regexp-quote value))))
6306 (allow-null
6307 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6309 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6311 (defconst org-property-re
6312 (org-re-property "\\S-+" 'literal t)
6313 "Regular expression matching a property line.
6314 There are four matching groups:
6315 1: :PROPKEY: including the leading and trailing colon,
6316 2: PROPKEY without the leading and trailing colon,
6317 3: PROPVAL without leading or trailing spaces,
6318 4: the indentation of the current line,
6319 5: trailing whitespace.")
6321 (defvar org-font-lock-hook nil
6322 "Functions to be called for special font lock stuff.")
6324 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6326 (defvar org-font-lock-set-keywords-hook nil
6327 "Functions that can manipulate `org-font-lock-extra-keywords'.
6328 This is called after `org-font-lock-extra-keywords' is defined, but before
6329 it is installed to be used by font lock. This can be useful if something
6330 needs to be inserted at a specific position in the font-lock sequence.")
6332 (defun org-font-lock-hook (limit)
6333 "Run `org-font-lock-hook' within LIMIT."
6334 (run-hook-with-args 'org-font-lock-hook limit))
6336 (defun org-set-font-lock-defaults ()
6337 "Set font lock defaults for the current buffer."
6338 (let* ((em org-fontify-emphasized-text)
6339 (lk org-highlight-links)
6340 (org-font-lock-extra-keywords
6341 (list
6342 ;; Call the hook
6343 '(org-font-lock-hook)
6344 ;; Headlines
6345 `(,(if org-fontify-whole-heading-line
6346 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6347 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6348 (1 (org-get-level-face 1))
6349 (2 (org-get-level-face 2))
6350 (3 (org-get-level-face 3)))
6351 ;; Table lines
6352 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6353 (1 'org-table t))
6354 ;; Table internals
6355 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6356 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6357 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6358 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6359 ;; Drawers
6360 '(org-fontify-drawers)
6361 ;; Properties
6362 (list org-property-re
6363 '(1 'org-special-keyword t)
6364 '(3 'org-property-value t))
6365 ;; Link related fontification.
6366 '(org-activate-links)
6367 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6368 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6369 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6370 (when (memq 'footnote lk) '(org-activate-footnote-links))
6371 ;; Targets.
6372 (list org-any-target-regexp '(0 'org-target t))
6373 ;; Diary sexps.
6374 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6375 ;; Macro
6376 '(org-fontify-macros)
6377 '(org-hide-wide-columns (0 nil append))
6378 ;; TODO keyword
6379 (list (format org-heading-keyword-regexp-format
6380 org-todo-regexp)
6381 '(2 (org-get-todo-face 2) t))
6382 ;; DONE
6383 (if org-fontify-done-headline
6384 (list (format org-heading-keyword-regexp-format
6385 (concat
6386 "\\(?:"
6387 (mapconcat 'regexp-quote org-done-keywords "\\|")
6388 "\\)"))
6389 '(2 'org-headline-done t))
6390 nil)
6391 ;; Priorities
6392 '(org-font-lock-add-priority-faces)
6393 ;; Tags
6394 '(org-font-lock-add-tag-faces)
6395 ;; Tags groups
6396 (when (and org-group-tags org-tag-groups-alist)
6397 (list (concat org-outline-regexp-bol ".+\\(:"
6398 (regexp-opt (mapcar 'car org-tag-groups-alist))
6399 ":\\).*$")
6400 '(1 'org-tag-group prepend)))
6401 ;; Special keywords
6402 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6403 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6404 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6405 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6406 ;; Emphasis
6407 (when em '(org-do-emphasis-faces))
6408 ;; Checkboxes
6409 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6410 1 'org-checkbox prepend)
6411 (when (cdr (assq 'checkbox org-list-automatic-rules))
6412 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6413 (0 (org-get-checkbox-statistics-face) t)))
6414 ;; Description list items
6415 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6416 1 'org-list-dt prepend)
6417 ;; ARCHIVEd headings
6418 (list (concat
6419 org-outline-regexp-bol
6420 "\\(.*:" org-archive-tag ":.*\\)")
6421 '(1 'org-archived prepend))
6422 ;; Specials
6423 '(org-do-latex-and-related)
6424 '(org-fontify-entities)
6425 '(org-raise-scripts)
6426 ;; Code
6427 '(org-activate-code (1 'org-code t))
6428 ;; COMMENT
6429 (list (format
6430 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6431 org-todo-regexp
6432 org-comment-string)
6433 '(9 'org-special-keyword t))
6434 ;; Blocks and meta lines
6435 '(org-fontify-meta-lines-and-blocks))))
6436 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6437 (run-hooks 'org-font-lock-set-keywords-hook)
6438 ;; Now set the full font-lock-keywords
6439 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6440 (setq-local font-lock-defaults
6441 '(org-font-lock-keywords t nil nil backward-paragraph))
6442 (kill-local-variable 'font-lock-keywords)
6443 nil))
6445 (defun org-toggle-pretty-entities ()
6446 "Toggle the composition display of entities as UTF8 characters."
6447 (interactive)
6448 (setq-local org-pretty-entities (not org-pretty-entities))
6449 (org-restart-font-lock)
6450 (if org-pretty-entities
6451 (message "Entities are now displayed as UTF8 characters")
6452 (save-restriction
6453 (widen)
6454 (decompose-region (point-min) (point-max))
6455 (message "Entities are now displayed as plain text"))))
6457 (defvar-local org-custom-properties-overlays nil
6458 "List of overlays used for custom properties.")
6460 (defun org-toggle-custom-properties-visibility ()
6461 "Display or hide properties in `org-custom-properties'."
6462 (interactive)
6463 (if org-custom-properties-overlays
6464 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6465 (setq org-custom-properties-overlays nil))
6466 (when org-custom-properties
6467 (org-with-wide-buffer
6468 (goto-char (point-min))
6469 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6470 (while (re-search-forward regexp nil t)
6471 (let ((end (cdr (save-match-data (org-get-property-block)))))
6472 (when (and end (< (point) end))
6473 ;; Hide first custom property in current drawer.
6474 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6475 (overlay-put o 'invisible t)
6476 (overlay-put o 'org-custom-property t)
6477 (push o org-custom-properties-overlays))
6478 ;; Hide additional custom properties in the same drawer.
6479 (while (re-search-forward regexp end t)
6480 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6481 (overlay-put o 'invisible t)
6482 (overlay-put o 'org-custom-property t)
6483 (push o org-custom-properties-overlays)))))
6484 ;; Each entry is limited to a single property drawer.
6485 (outline-next-heading)))))))
6487 (defun org-fontify-entities (limit)
6488 "Find an entity to fontify."
6489 (let (ee)
6490 (when org-pretty-entities
6491 (catch 'match
6492 ;; "\_ "-family is left out on purpose. Only the first one,
6493 ;; i.e., "\_ ", could be fontified anyway, and it would be
6494 ;; confusing when adding a second white space character.
6495 (while (re-search-forward
6496 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6497 limit t)
6498 (when (and (not (org-at-comment-p))
6499 (setq ee (org-entity-get (match-string 1)))
6500 (= (length (nth 6 ee)) 1))
6501 (let* ((end (if (equal (match-string 2) "{}")
6502 (match-end 2)
6503 (match-end 1))))
6504 (add-text-properties
6505 (match-beginning 0) end
6506 (list 'font-lock-fontified t))
6507 (compose-region (match-beginning 0) end
6508 (nth 6 ee) nil)
6509 (backward-char 1)
6510 (throw 'match t))))
6511 nil))))
6513 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6514 "Fontify string S like in Org mode."
6515 (with-temp-buffer
6516 (insert s)
6517 (let ((org-odd-levels-only odd-levels))
6518 (org-mode)
6519 (org-font-lock-ensure)
6520 (buffer-string))))
6522 (defvar org-m nil)
6523 (defvar org-l nil)
6524 (defvar org-f nil)
6525 (defun org-get-level-face (n)
6526 "Get the right face for match N in font-lock matching of headlines."
6527 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6528 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6529 (if org-cycle-level-faces
6530 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6531 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6532 (cond
6533 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6534 ((eq n 2) org-f)
6535 (t (unless org-level-color-stars-only org-f))))
6537 (defun org-face-from-face-or-color (context inherit face-or-color)
6538 "Create a face list that inherits INHERIT, but sets the foreground color.
6539 When FACE-OR-COLOR is not a string, just return it."
6540 (if (stringp face-or-color)
6541 (list :inherit inherit
6542 (cdr (assoc context org-faces-easy-properties))
6543 face-or-color)
6544 face-or-color))
6546 (defun org-get-todo-face (kwd)
6547 "Get the right face for a TODO keyword KWD.
6548 If KWD is a number, get the corresponding match group."
6549 (when (numberp kwd) (setq kwd (match-string kwd)))
6550 (or (org-face-from-face-or-color
6551 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6552 (and (member kwd org-done-keywords) 'org-done)
6553 'org-todo))
6555 (defun org-get-priority-face (priority)
6556 "Get the right face for PRIORITY.
6557 PRIORITY is a character."
6558 (or (org-face-from-face-or-color
6559 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6560 'org-priority))
6562 (defun org-get-tag-face (tag)
6563 "Get the right face for TAG.
6564 If TAG is a number, get the corresponding match group."
6565 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6566 (or (org-face-from-face-or-color
6567 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6568 'org-tag)))
6570 (defun org-font-lock-add-priority-faces (limit)
6571 "Add the special priority faces."
6572 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6573 (add-text-properties
6574 (match-beginning 1) (match-end 1)
6575 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6576 'font-lock-fontified t))))
6578 (defun org-font-lock-add-tag-faces (limit)
6579 "Add the special tag faces."
6580 (when (and org-tag-faces org-tags-special-faces-re)
6581 (while (re-search-forward org-tags-special-faces-re limit t)
6582 (add-text-properties (match-beginning 1) (match-end 1)
6583 (list 'face (org-get-tag-face 1)
6584 'font-lock-fontified t))
6585 (backward-char 1))))
6587 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6588 "Remove fontification and activation overlays from links."
6589 (font-lock-default-unfontify-region beg end)
6590 (let* ((buffer-undo-list t)
6591 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6592 (inhibit-modification-hooks t)
6593 deactivate-mark buffer-file-name buffer-file-truename)
6594 (decompose-region beg end)
6595 (remove-text-properties beg end
6596 '(mouse-face t keymap t org-linked-text t
6597 invisible t intangible t
6598 org-emphasis t))
6599 (org-remove-font-lock-display-properties beg end)))
6601 (defconst org-script-display '(((raise -0.3) (height 0.7))
6602 ((raise 0.3) (height 0.7))
6603 ((raise -0.5))
6604 ((raise 0.5)))
6605 "Display properties for showing superscripts and subscripts.")
6607 (defun org-remove-font-lock-display-properties (beg end)
6608 "Remove specific display properties that have been added by font lock.
6609 The will remove the raise properties that are used to show superscripts
6610 and subscripts."
6611 (let (next prop)
6612 (while (< beg end)
6613 (setq next (next-single-property-change beg 'display nil end)
6614 prop (get-text-property beg 'display))
6615 (when (member prop org-script-display)
6616 (put-text-property beg next 'display nil))
6617 (setq beg next))))
6619 (defun org-raise-scripts (limit)
6620 "Add raise properties to sub/superscripts."
6621 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6622 (re-search-forward
6623 (if (eq org-use-sub-superscripts t)
6624 org-match-substring-regexp
6625 org-match-substring-with-braces-regexp)
6626 limit t))
6627 (let* ((pos (point)) table-p comment-p
6628 (mpos (match-beginning 3))
6629 (emph-p (get-text-property mpos 'org-emphasis))
6630 (link-p (get-text-property mpos 'mouse-face))
6631 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6632 (goto-char (point-at-bol))
6633 (setq table-p (looking-at-p org-table-dataline-regexp)
6634 comment-p (looking-at-p "^[ \t]*#[ +]"))
6635 (goto-char pos)
6636 ;; Handle a_b^c
6637 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6638 (unless (or comment-p emph-p link-p keyw-p)
6639 (put-text-property (match-beginning 3) (match-end 0)
6640 'display
6641 (if (equal (char-after (match-beginning 2)) ?^)
6642 (nth (if table-p 3 1) org-script-display)
6643 (nth (if table-p 2 0) org-script-display)))
6644 (add-text-properties (match-beginning 2) (match-end 2)
6645 (list 'invisible t
6646 'org-dwidth t 'org-dwidth-n 1))
6647 (if (and (eq (char-after (match-beginning 3)) ?{)
6648 (eq (char-before (match-end 3)) ?}))
6649 (progn
6650 (add-text-properties
6651 (match-beginning 3) (1+ (match-beginning 3))
6652 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6653 (add-text-properties
6654 (1- (match-end 3)) (match-end 3)
6655 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6656 t)))
6658 ;;;; Visibility cycling, including org-goto and indirect buffer
6660 ;;; Cycling
6662 (defvar-local org-cycle-global-status nil)
6663 (put 'org-cycle-global-status 'org-state t)
6664 (defvar-local org-cycle-subtree-status nil)
6665 (put 'org-cycle-subtree-status 'org-state t)
6667 (defvar org-inlinetask-min-level)
6669 (defun org-unlogged-message (&rest args)
6670 "Display a message, but avoid logging it in the *Messages* buffer."
6671 (let ((message-log-max nil))
6672 (apply 'message args)))
6674 ;;;###autoload
6675 (defun org-cycle (&optional arg)
6676 "TAB-action and visibility cycling for Org mode.
6678 This is the command invoked in Org mode by the `TAB' key. Its main
6679 purpose is outline visibility cycling, but it also invokes other actions
6680 in special contexts.
6682 When this function is called with a `\\[universal-argument]' prefix, rotate \
6683 the entire
6684 buffer through 3 states (global cycling)
6685 1. OVERVIEW: Show only top-level headlines.
6686 2. CONTENTS: Show all headlines of all levels, but no body text.
6687 3. SHOW ALL: Show everything.
6689 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6690 switch to the startup visibility,
6691 determined by the variable `org-startup-folded', and by any VISIBILITY
6692 properties in the buffer.
6694 With a `\\[universal-argument] \\[universal-argument] \
6695 \\[universal-argument]' prefix argument, show the entire buffer, including
6696 any drawers.
6698 When inside a table, re-align the table and move to the next field.
6700 When point is at the beginning of a headline, rotate the subtree started
6701 by this line through 3 different states (local cycling)
6702 1. FOLDED: Only the main headline is shown.
6703 2. CHILDREN: The main headline and the direct children are shown.
6704 From this state, you can move to one of the children
6705 and zoom in further.
6706 3. SUBTREE: Show the entire subtree, including body text.
6707 If there is no subtree, switch directly from CHILDREN to FOLDED.
6709 When point is at the beginning of an empty headline and the variable
6710 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6711 of the headline by demoting and promoting it to likely levels. This
6712 speeds up creation document structure by pressing `TAB' once or several
6713 times right after creating a new headline.
6715 When there is a numeric prefix, go up to a heading with level ARG, do
6716 a `show-subtree' and return to the previous cursor position. If ARG
6717 is negative, go up that many levels.
6719 When point is not at the beginning of a headline, execute the global
6720 binding for `TAB', which is re-indenting the line. See the option
6721 `org-cycle-emulate-tab' for details.
6723 As a special case, if point is at the beginning of the buffer and there is
6724 no headline in line 1, this function will act as if called with prefix arg
6725 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6726 prefix arg, but only
6727 if the variable `org-cycle-global-at-bob' is t."
6728 (interactive "P")
6729 (org-load-modules-maybe)
6730 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6731 (and org-cycle-level-after-item/entry-creation
6732 (or (org-cycle-level)
6733 (org-cycle-item-indentation))))
6734 (let* ((limit-level
6735 (or org-cycle-max-level
6736 (and (boundp 'org-inlinetask-min-level)
6737 org-inlinetask-min-level
6738 (1- org-inlinetask-min-level))))
6739 (nstars (and limit-level
6740 (if org-odd-levels-only
6741 (and limit-level (1- (* limit-level 2)))
6742 limit-level)))
6743 (org-outline-regexp
6744 (if (not (derived-mode-p 'org-mode))
6745 outline-regexp
6746 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6747 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6748 (not (looking-at org-outline-regexp))))
6749 (org-cycle-hook
6750 (if bob-special
6751 (delq 'org-optimize-window-after-visibility-change
6752 (copy-sequence org-cycle-hook))
6753 org-cycle-hook))
6754 (pos (point)))
6756 (cond
6758 ((equal arg '(16))
6759 (setq last-command 'dummy)
6760 (org-set-startup-visibility)
6761 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6763 ((equal arg '(64))
6764 (outline-show-all)
6765 (org-unlogged-message "Entire buffer visible, including drawers"))
6767 ((equal arg '(4)) (org-cycle-internal-global))
6769 ;; Try hiding block at point.
6770 ((org-hide-block-toggle-maybe))
6772 ;; Try cdlatex TAB completion
6773 ((org-try-cdlatex-tab))
6775 ;; Table: enter it or move to the next field.
6776 ((org-at-table-p 'any)
6777 (if (org-at-table.el-p)
6778 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6779 Use `\\[org-edit-special]' to edit table.el tables"))
6780 (if arg (org-table-edit-field t)
6781 (org-table-justify-field-maybe)
6782 (call-interactively 'org-table-next-field))))
6784 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6786 ;; Global cycling: delegate to `org-cycle-internal-global'.
6787 (bob-special (org-cycle-internal-global))
6789 ;; Drawers: delegate to `org-flag-drawer'.
6790 ((save-excursion
6791 (beginning-of-line 1)
6792 (looking-at org-drawer-regexp))
6793 (org-flag-drawer ; toggle block visibility
6794 (not (get-char-property (match-end 0) 'invisible))))
6796 ;; Show-subtree, ARG levels up from here.
6797 ((integerp arg)
6798 (save-excursion
6799 (org-back-to-heading)
6800 (outline-up-heading (if (< arg 0) (- arg)
6801 (- (funcall outline-level) arg)))
6802 (org-show-subtree)))
6804 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6805 ((and (featurep 'org-inlinetask)
6806 (org-inlinetask-at-task-p)
6807 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6808 (org-inlinetask-toggle-visibility))
6810 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6811 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6812 (save-excursion (move-beginning-of-line 1)
6813 (looking-at org-outline-regexp)))
6814 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6815 (org-cycle-internal-local))
6817 ;; From there: TAB emulation and template completion.
6818 (buffer-read-only (org-back-to-heading))
6820 ((run-hook-with-args-until-success
6821 'org-tab-after-check-for-cycling-hook))
6823 ((org-try-structure-completion))
6825 ((run-hook-with-args-until-success
6826 'org-tab-before-tab-emulation-hook))
6828 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6829 (or (not (bolp))
6830 (not (looking-at org-outline-regexp))))
6831 (call-interactively (global-key-binding "\t")))
6833 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6834 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6835 (or (and (eq org-cycle-emulate-tab 'white)
6836 (= (match-end 0) (point-at-eol)))
6837 (and (eq org-cycle-emulate-tab 'whitestart)
6838 (>= (match-end 0) pos))))
6840 (eq org-cycle-emulate-tab t))
6841 (call-interactively (global-key-binding "\t")))
6843 (t (save-excursion
6844 (org-back-to-heading)
6845 (org-cycle)))))))
6847 (defun org-cycle-internal-global ()
6848 "Do the global cycling action."
6849 ;; Hack to avoid display of messages for .org attachments in Gnus
6850 (let ((ga (string-match "\\*fontification" (buffer-name))))
6851 (cond
6852 ((and (eq last-command this-command)
6853 (eq org-cycle-global-status 'overview))
6854 ;; We just created the overview - now do table of contents
6855 ;; This can be slow in very large buffers, so indicate action
6856 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6857 (unless ga (org-unlogged-message "CONTENTS..."))
6858 (org-content)
6859 (unless ga (org-unlogged-message "CONTENTS...done"))
6860 (setq org-cycle-global-status 'contents)
6861 (run-hook-with-args 'org-cycle-hook 'contents))
6863 ((and (eq last-command this-command)
6864 (eq org-cycle-global-status 'contents))
6865 ;; We just showed the table of contents - now show everything
6866 (run-hook-with-args 'org-pre-cycle-hook 'all)
6867 (outline-show-all)
6868 (unless ga (org-unlogged-message "SHOW ALL"))
6869 (setq org-cycle-global-status 'all)
6870 (run-hook-with-args 'org-cycle-hook 'all))
6873 ;; Default action: go to overview
6874 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6875 (org-overview)
6876 (unless ga (org-unlogged-message "OVERVIEW"))
6877 (setq org-cycle-global-status 'overview)
6878 (run-hook-with-args 'org-cycle-hook 'overview)))))
6880 (defvar org-called-with-limited-levels nil
6881 "Non-nil when `org-with-limited-levels' is currently active.")
6883 (defun org-cycle-internal-local ()
6884 "Do the local cycling action."
6885 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6886 ;; First, determine end of headline (EOH), end of subtree or item
6887 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6888 (save-excursion
6889 (if (org-at-item-p)
6890 (progn
6891 (beginning-of-line)
6892 (setq struct (org-list-struct))
6893 (setq eoh (point-at-eol))
6894 (setq eos (org-list-get-item-end-before-blank (point) struct))
6895 (setq has-children (org-list-has-child-p (point) struct)))
6896 (org-back-to-heading)
6897 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6898 (setq eos (save-excursion (org-end-of-subtree t t)
6899 (when (bolp) (backward-char)) (point)))
6900 (setq has-children
6901 (or (save-excursion
6902 (let ((level (funcall outline-level)))
6903 (outline-next-heading)
6904 (and (org-at-heading-p t)
6905 (> (funcall outline-level) level))))
6906 (save-excursion
6907 (org-list-search-forward (org-item-beginning-re) eos t)))))
6908 ;; Determine end invisible part of buffer (EOL)
6909 (beginning-of-line 2)
6910 (while (and (not (eobp)) ;This is like `next-line'.
6911 (get-char-property (1- (point)) 'invisible))
6912 (goto-char (next-single-char-property-change (point) 'invisible))
6913 (and (eolp) (beginning-of-line 2)))
6914 (setq eol (point)))
6915 ;; Find out what to do next and set `this-command'
6916 (cond
6917 ((= eos eoh)
6918 ;; Nothing is hidden behind this heading
6919 (unless (org-before-first-heading-p)
6920 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6921 (org-unlogged-message "EMPTY ENTRY")
6922 (setq org-cycle-subtree-status nil)
6923 (save-excursion
6924 (goto-char eos)
6925 (outline-next-heading)
6926 (when (outline-invisible-p) (org-flag-heading nil))))
6927 ((and (or (>= eol eos)
6928 (not (string-match "\\S-" (buffer-substring eol eos))))
6929 (or has-children
6930 (not (setq children-skipped
6931 org-cycle-skip-children-state-if-no-children))))
6932 ;; Entire subtree is hidden in one line: children view
6933 (unless (org-before-first-heading-p)
6934 (run-hook-with-args 'org-pre-cycle-hook 'children))
6935 (if (org-at-item-p)
6936 (org-list-set-item-visibility (point-at-bol) struct 'children)
6937 (org-show-entry)
6938 (org-with-limited-levels (org-show-children))
6939 ;; FIXME: This slows down the func way too much.
6940 ;; How keep drawers hidden in subtree anyway?
6941 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6942 ;; (org-cycle-hide-drawers 'subtree))
6944 ;; Fold every list in subtree to top-level items.
6945 (when (eq org-cycle-include-plain-lists 'integrate)
6946 (save-excursion
6947 (org-back-to-heading)
6948 (while (org-list-search-forward (org-item-beginning-re) eos t)
6949 (beginning-of-line 1)
6950 (let* ((struct (org-list-struct))
6951 (prevs (org-list-prevs-alist struct))
6952 (end (org-list-get-bottom-point struct)))
6953 (dolist (e (org-list-get-all-items (point) struct prevs))
6954 (org-list-set-item-visibility e struct 'folded))
6955 (goto-char (if (< end eos) end eos)))))))
6956 (org-unlogged-message "CHILDREN")
6957 (save-excursion
6958 (goto-char eos)
6959 (outline-next-heading)
6960 (when (outline-invisible-p) (org-flag-heading nil)))
6961 (setq org-cycle-subtree-status 'children)
6962 (unless (org-before-first-heading-p)
6963 (run-hook-with-args 'org-cycle-hook 'children)))
6964 ((or children-skipped
6965 (and (eq last-command this-command)
6966 (eq org-cycle-subtree-status 'children)))
6967 ;; We just showed the children, or no children are there,
6968 ;; now show everything.
6969 (unless (org-before-first-heading-p)
6970 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6971 (outline-flag-region eoh eos nil)
6972 (org-unlogged-message
6973 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6974 (setq org-cycle-subtree-status 'subtree)
6975 (unless (org-before-first-heading-p)
6976 (run-hook-with-args 'org-cycle-hook 'subtree)))
6978 ;; Default action: hide the subtree.
6979 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6980 (outline-flag-region eoh eos t)
6981 (org-unlogged-message "FOLDED")
6982 (setq org-cycle-subtree-status 'folded)
6983 (unless (org-before-first-heading-p)
6984 (run-hook-with-args 'org-cycle-hook 'folded))))))
6986 ;;;###autoload
6987 (defun org-global-cycle (&optional arg)
6988 "Cycle the global visibility. For details see `org-cycle'.
6989 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6990 With a numeric prefix, show all headlines up to that level."
6991 (interactive "P")
6992 (let ((org-cycle-include-plain-lists
6993 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6994 (cond
6995 ((integerp arg)
6996 (outline-show-all)
6997 (outline-hide-sublevels arg)
6998 (setq org-cycle-global-status 'contents))
6999 ((equal arg '(4))
7000 (org-set-startup-visibility)
7001 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7003 (org-cycle '(4))))))
7005 (defun org-set-startup-visibility ()
7006 "Set the visibility required by startup options and properties."
7007 (cond
7008 ((eq org-startup-folded t)
7009 (org-overview))
7010 ((eq org-startup-folded 'content)
7011 (org-content))
7012 ((or (eq org-startup-folded 'showeverything)
7013 (eq org-startup-folded nil))
7014 (outline-show-all)))
7015 (unless (eq org-startup-folded 'showeverything)
7016 (when org-hide-block-startup (org-hide-block-all))
7017 (org-set-visibility-according-to-property 'no-cleanup)
7018 (org-cycle-hide-archived-subtrees 'all)
7019 (org-cycle-hide-drawers 'all)
7020 (org-cycle-show-empty-lines t)))
7022 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7023 "Switch subtree visibilities according to :VISIBILITY: property."
7024 (interactive)
7025 (org-with-wide-buffer
7026 (goto-char (point-min))
7027 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7028 (if (not (org-at-property-p)) (outline-next-heading)
7029 (let ((state (match-string 3)))
7030 (save-excursion
7031 (org-back-to-heading t)
7032 (outline-hide-subtree)
7033 (org-reveal)
7034 (cond
7035 ((equal state "folded")
7036 (outline-hide-subtree))
7037 ((equal state "children")
7038 (org-show-hidden-entry)
7039 (org-show-children))
7040 ((equal state "content")
7041 (save-excursion
7042 (save-restriction
7043 (org-narrow-to-subtree)
7044 (org-content))))
7045 ((member state '("all" "showall"))
7046 (outline-show-subtree)))))))
7047 (unless no-cleanup
7048 (org-cycle-hide-archived-subtrees 'all)
7049 (org-cycle-hide-drawers 'all)
7050 (org-cycle-show-empty-lines 'all))))
7052 ;; This function uses outline-regexp instead of the more fundamental
7053 ;; org-outline-regexp so that org-cycle-global works outside of Org
7054 ;; buffers, where outline-regexp is needed.
7055 (defun org-overview ()
7056 "Switch to overview mode, showing only top-level headlines.
7057 This shows all headlines with a level equal or greater than the level
7058 of the first headline in the buffer. This is important, because if the
7059 first headline is not level one, then (hide-sublevels 1) gives confusing
7060 results."
7061 (interactive)
7062 (save-excursion
7063 (let ((level
7064 (save-excursion
7065 (goto-char (point-min))
7066 (when (re-search-forward (concat "^" outline-regexp) nil t)
7067 (goto-char (match-beginning 0))
7068 (funcall outline-level)))))
7069 (and level (outline-hide-sublevels level)))))
7071 (defun org-content (&optional arg)
7072 "Show all headlines in the buffer, like a table of contents.
7073 With numerical argument N, show content up to level N."
7074 (interactive "P")
7075 (org-overview)
7076 (save-excursion
7077 ;; Visit all headings and show their offspring
7078 (and (integerp arg) (org-overview))
7079 (goto-char (point-max))
7080 (catch 'exit
7081 (while (and (progn (condition-case nil
7082 (outline-previous-visible-heading 1)
7083 (error (goto-char (point-min))))
7085 (looking-at org-outline-regexp))
7086 (if (integerp arg)
7087 (org-show-children (1- arg))
7088 (outline-show-branches))
7089 (when (bobp) (throw 'exit nil))))))
7091 (defun org-optimize-window-after-visibility-change (state)
7092 "Adjust the window after a change in outline visibility.
7093 This function is the default value of the hook `org-cycle-hook'."
7094 (when (get-buffer-window (current-buffer))
7095 (cond
7096 ((eq state 'content) nil)
7097 ((eq state 'all) nil)
7098 ((eq state 'folded) nil)
7099 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7100 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7102 (defun org-remove-empty-overlays-at (pos)
7103 "Remove outline overlays that do not contain non-white stuff."
7104 (dolist (o (overlays-at pos))
7105 (and (eq 'outline (overlay-get o 'invisible))
7106 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7107 (overlay-end o))))
7108 (delete-overlay o))))
7110 (defun org-clean-visibility-after-subtree-move ()
7111 "Fix visibility issues after moving a subtree."
7112 ;; First, find a reasonable region to look at:
7113 ;; Start two siblings above, end three below
7114 (let* ((beg (save-excursion
7115 (and (org-get-last-sibling)
7116 (org-get-last-sibling))
7117 (point)))
7118 (end (save-excursion
7119 (and (org-get-next-sibling)
7120 (org-get-next-sibling)
7121 (org-get-next-sibling))
7122 (if (org-at-heading-p)
7123 (point-at-eol)
7124 (point))))
7125 (level (looking-at "\\*+"))
7126 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7127 (save-excursion
7128 (save-restriction
7129 (narrow-to-region beg end)
7130 (when re
7131 ;; Properly fold already folded siblings
7132 (goto-char (point-min))
7133 (while (re-search-forward re nil t)
7134 (when (and (not (outline-invisible-p))
7135 (save-excursion
7136 (goto-char (point-at-eol)) (outline-invisible-p)))
7137 (outline-hide-entry))))
7138 (org-cycle-show-empty-lines 'overview)
7139 (org-cycle-hide-drawers 'overview)))))
7141 (defun org-cycle-show-empty-lines (state)
7142 "Show empty lines above all visible headlines.
7143 The region to be covered depends on STATE when called through
7144 `org-cycle-hook'. Lisp program can use t for STATE to get the
7145 entire buffer covered. Note that an empty line is only shown if there
7146 are at least `org-cycle-separator-lines' empty lines before the headline."
7147 (when (/= org-cycle-separator-lines 0)
7148 (save-excursion
7149 (let* ((n (abs org-cycle-separator-lines))
7150 (re (cond
7151 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7152 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7153 (t (let ((ns (number-to-string (- n 2))))
7154 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7155 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7156 beg end)
7157 (cond
7158 ((memq state '(overview contents t))
7159 (setq beg (point-min) end (point-max)))
7160 ((memq state '(children folded))
7161 (setq beg (point)
7162 end (progn (org-end-of-subtree t t)
7163 (line-beginning-position 2)))))
7164 (when beg
7165 (goto-char beg)
7166 (while (re-search-forward re end t)
7167 (unless (get-char-property (match-end 1) 'invisible)
7168 (let ((e (match-end 1))
7169 (b (if (>= org-cycle-separator-lines 0)
7170 (match-beginning 1)
7171 (save-excursion
7172 (goto-char (match-beginning 0))
7173 (skip-chars-backward " \t\n")
7174 (line-end-position)))))
7175 (outline-flag-region b e nil))))))))
7176 ;; Never hide empty lines at the end of the file.
7177 (save-excursion
7178 (goto-char (point-max))
7179 (outline-previous-heading)
7180 (outline-end-of-heading)
7181 (when (and (looking-at "[ \t\n]+")
7182 (= (match-end 0) (point-max)))
7183 (outline-flag-region (point) (match-end 0) nil))))
7185 (defun org-show-empty-lines-in-parent ()
7186 "Move to the parent and re-show empty lines before visible headlines."
7187 (save-excursion
7188 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7189 (org-cycle-show-empty-lines context))))
7191 (defun org-files-list ()
7192 "Return `org-agenda-files' list, plus all open Org files.
7193 This is useful for operations that need to scan all of a user's
7194 open and agenda-wise Org files."
7195 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7196 (dolist (buf (buffer-list))
7197 (with-current-buffer buf
7198 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7199 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7200 files))
7202 (defsubst org-entry-beginning-position ()
7203 "Return the beginning position of the current entry."
7204 (save-excursion (org-back-to-heading t) (point)))
7206 (defsubst org-entry-end-position ()
7207 "Return the end position of the current entry."
7208 (save-excursion (outline-next-heading) (point)))
7210 (defun org-cycle-hide-drawers (state &optional exceptions)
7211 "Re-hide all drawers after a visibility state change.
7212 When non-nil, optional argument EXCEPTIONS is a list of strings
7213 specifying which drawers should not be hidden."
7214 (when (and (derived-mode-p 'org-mode)
7215 (not (memq state '(overview folded contents))))
7216 (save-excursion
7217 (let* ((globalp (memq state '(contents all)))
7218 (beg (if globalp (point-min) (point)))
7219 (end (if globalp (point-max)
7220 (if (eq state 'children)
7221 (save-excursion (outline-next-heading) (point))
7222 (org-end-of-subtree t)))))
7223 (goto-char beg)
7224 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7225 (unless (member-ignore-case (match-string 1) exceptions)
7226 (let ((drawer (org-element-at-point)))
7227 (when (memq (org-element-type drawer) '(drawer property-drawer))
7228 (org-flag-drawer t drawer)
7229 ;; Make sure to skip drawer entirely or we might flag
7230 ;; it another time when matching its ending line with
7231 ;; `org-drawer-regexp'.
7232 (goto-char (org-element-property :end drawer))))))))))
7234 (defun org-flag-drawer (flag &optional element)
7235 "When FLAG is non-nil, hide the drawer we are at.
7236 Otherwise make it visible. When optional argument ELEMENT is
7237 a parsed drawer, as returned by `org-element-at-point', hide or
7238 show that drawer instead."
7239 (let ((drawer (or element
7240 (and (save-excursion
7241 (beginning-of-line)
7242 (looking-at-p org-drawer-regexp))
7243 (org-element-at-point)))))
7244 (when (memq (org-element-type drawer) '(drawer property-drawer))
7245 (let ((post (org-element-property :post-affiliated drawer)))
7246 (save-excursion
7247 (outline-flag-region
7248 (progn (goto-char post) (line-end-position))
7249 (progn (goto-char (org-element-property :end drawer))
7250 (skip-chars-backward " \r\t\n")
7251 (line-end-position))
7252 flag))
7253 ;; When the drawer is hidden away, make sure point lies in
7254 ;; a visible part of the buffer.
7255 (when (and flag (> (line-beginning-position) post))
7256 (goto-char post))))))
7258 (defun org-subtree-end-visible-p ()
7259 "Is the end of the current subtree visible?"
7260 (pos-visible-in-window-p
7261 (save-excursion (org-end-of-subtree t) (point))))
7263 (defun org-first-headline-recenter ()
7264 "Move cursor to the first headline and recenter the headline."
7265 (let ((window (get-buffer-window)))
7266 (when window
7267 (goto-char (point-min))
7268 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7269 (set-window-start window (line-beginning-position))))))
7271 ;;; Saving and restoring visibility
7273 (defun org-outline-overlay-data (&optional use-markers)
7274 "Return a list of the locations of all outline overlays.
7275 These are overlays with the `invisible' property value `outline'.
7276 The return value is a list of cons cells, with start and stop
7277 positions for each overlay.
7278 If USE-MARKERS is set, return the positions as markers."
7279 (let (beg end)
7280 (org-with-wide-buffer
7281 (delq nil
7282 (mapcar (lambda (o)
7283 (when (eq (overlay-get o 'invisible) 'outline)
7284 (setq beg (overlay-start o)
7285 end (overlay-end o))
7286 (and beg end (> end beg)
7287 (if use-markers
7288 (cons (copy-marker beg)
7289 (copy-marker end t))
7290 (cons beg end)))))
7291 (overlays-in (point-min) (point-max)))))))
7293 (defun org-set-outline-overlay-data (data)
7294 "Create visibility overlays for all positions in DATA.
7295 DATA should have been made by `org-outline-overlay-data'."
7296 (org-with-wide-buffer
7297 (outline-show-all)
7298 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7300 ;;; Folding of blocks
7302 (defvar-local org-hide-block-overlays nil
7303 "Overlays hiding blocks.")
7305 (defun org-block-map (function &optional start end)
7306 "Call FUNCTION at the head of all source blocks in the current buffer.
7307 Optional arguments START and END can be used to limit the range."
7308 (let ((start (or start (point-min)))
7309 (end (or end (point-max))))
7310 (save-excursion
7311 (goto-char start)
7312 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7313 (save-excursion
7314 (save-match-data
7315 (goto-char (match-beginning 0))
7316 (funcall function)))))))
7318 (defun org-hide-block-toggle-all ()
7319 "Toggle the visibility of all blocks in the current buffer."
7320 (org-block-map 'org-hide-block-toggle))
7322 (defun org-hide-block-all ()
7323 "Fold all blocks in the current buffer."
7324 (interactive)
7325 (org-show-block-all)
7326 (org-block-map 'org-hide-block-toggle-maybe))
7328 (defun org-show-block-all ()
7329 "Unfold all blocks in the current buffer."
7330 (interactive)
7331 (mapc #'delete-overlay org-hide-block-overlays)
7332 (setq org-hide-block-overlays nil))
7334 (defun org-hide-block-toggle-maybe ()
7335 "Toggle visibility of block at point.
7336 Unlike to `org-hide-block-toggle', this function does not throw
7337 an error. Return a non-nil value when toggling is successful."
7338 (interactive)
7339 (ignore-errors (org-hide-block-toggle)))
7341 (defun org-hide-block-toggle (&optional force)
7342 "Toggle the visibility of the current block.
7343 When optional argument FORCE is `off', make block visible. If it
7344 is non-nil, hide it unconditionally. Throw an error when not at
7345 a block. Return a non-nil value when toggling is successful."
7346 (interactive)
7347 (let ((element (org-element-at-point)))
7348 (unless (memq (org-element-type element)
7349 '(center-block comment-block dynamic-block example-block
7350 export-block quote-block special-block
7351 src-block verse-block))
7352 (user-error "Not at a block"))
7353 (let* ((start (save-excursion
7354 (goto-char (org-element-property :post-affiliated element))
7355 (line-end-position)))
7356 (end (save-excursion
7357 (goto-char (org-element-property :end element))
7358 (skip-chars-backward " \r\t\n")
7359 (line-end-position)))
7360 (overlays (overlays-at start)))
7361 (cond
7362 ;; Do nothing when not before or at the block opening line or
7363 ;; at the block closing line.
7364 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7365 ((and (not (eq force 'off))
7366 (not (memq t (mapcar
7367 (lambda (o)
7368 (eq (overlay-get o 'invisible) 'org-hide-block))
7369 overlays))))
7370 (let ((ov (make-overlay start end)))
7371 (overlay-put ov 'invisible 'org-hide-block)
7372 ;; Make the block accessible to `isearch'.
7373 (overlay-put
7374 ov 'isearch-open-invisible
7375 (lambda (ov)
7376 (when (memq ov org-hide-block-overlays)
7377 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7378 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7379 (delete-overlay ov))))
7380 (push ov org-hide-block-overlays)
7381 ;; When the block is hidden away, make sure point is left in
7382 ;; a visible part of the buffer.
7383 (when (> (line-beginning-position) start)
7384 (goto-char start)
7385 (beginning-of-line))
7386 ;; Signal successful toggling.
7388 ((or (not force) (eq force 'off))
7389 (dolist (ov overlays t)
7390 (when (memq ov org-hide-block-overlays)
7391 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7392 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7393 (delete-overlay ov))))))))
7395 ;; Remove overlays when changing major mode
7396 (add-hook 'org-mode-hook
7397 (lambda () (add-hook 'change-major-mode-hook
7398 'org-show-block-all 'append 'local)))
7400 ;;; Org-goto
7402 (defvar org-goto-window-configuration nil)
7403 (defvar org-goto-marker nil)
7404 (defvar org-goto-map)
7405 (defun org-goto-map ()
7406 "Set the keymap `org-goto'."
7407 (setq org-goto-map
7408 (let ((map (make-sparse-keymap)))
7409 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7410 mouse-drag-region universal-argument org-occur)))
7411 (dolist (cmd cmds)
7412 (substitute-key-definition cmd cmd map global-map)))
7413 (suppress-keymap map)
7414 (org-defkey map "\C-m" 'org-goto-ret)
7415 (org-defkey map [(return)] 'org-goto-ret)
7416 (org-defkey map [(left)] 'org-goto-left)
7417 (org-defkey map [(right)] 'org-goto-right)
7418 (org-defkey map [(control ?g)] 'org-goto-quit)
7419 (org-defkey map "\C-i" 'org-cycle)
7420 (org-defkey map [(tab)] 'org-cycle)
7421 (org-defkey map [(down)] 'outline-next-visible-heading)
7422 (org-defkey map [(up)] 'outline-previous-visible-heading)
7423 (if org-goto-auto-isearch
7424 (if (fboundp 'define-key-after)
7425 (define-key-after map [t] 'org-goto-local-auto-isearch)
7426 nil)
7427 (org-defkey map "q" 'org-goto-quit)
7428 (org-defkey map "n" 'outline-next-visible-heading)
7429 (org-defkey map "p" 'outline-previous-visible-heading)
7430 (org-defkey map "f" 'outline-forward-same-level)
7431 (org-defkey map "b" 'outline-backward-same-level)
7432 (org-defkey map "u" 'outline-up-heading))
7433 (org-defkey map "/" 'org-occur)
7434 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7435 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7436 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7437 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7438 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7439 map)))
7441 (defconst org-goto-help
7442 "Browse buffer copy, to find location or copy text.%s
7443 RET=jump to location C-g=quit and return to previous location
7444 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7446 (defvar org-goto-start-pos) ; dynamically scoped parameter
7448 (defun org-goto (&optional alternative-interface)
7449 "Look up a different location in the current file, keeping current visibility.
7451 When you want look-up or go to a different location in a
7452 document, the fastest way is often to fold the entire buffer and
7453 then dive into the tree. This method has the disadvantage, that
7454 the previous location will be folded, which may not be what you
7455 want.
7457 This command works around this by showing a copy of the current
7458 buffer in an indirect buffer, in overview mode. You can dive
7459 into the tree in that copy, use org-occur and incremental search
7460 to find a location. When pressing RET or `Q', the command
7461 returns to the original buffer in which the visibility is still
7462 unchanged. After RET it will also jump to the location selected
7463 in the indirect buffer and expose the headline hierarchy above.
7465 With a prefix argument, use the alternative interface: e.g., if
7466 `org-goto-interface' is `outline' use `outline-path-completion'."
7467 (interactive "P")
7468 (org-goto-map)
7469 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7470 (org-refile-use-outline-path t)
7471 (org-refile-target-verify-function nil)
7472 (interface
7473 (if (not alternative-interface)
7474 org-goto-interface
7475 (if (eq org-goto-interface 'outline)
7476 'outline-path-completion
7477 'outline)))
7478 (org-goto-start-pos (point))
7479 (selected-point
7480 (if (eq interface 'outline)
7481 (car (org-get-location (current-buffer) org-goto-help))
7482 (let ((pa (org-refile-get-location "Goto")))
7483 (org-refile-check-position pa)
7484 (nth 3 pa)))))
7485 (if selected-point
7486 (progn
7487 (org-mark-ring-push org-goto-start-pos)
7488 (goto-char selected-point)
7489 (when (or (outline-invisible-p) (org-invisible-p2))
7490 (org-show-context 'org-goto)))
7491 (message "Quit"))))
7493 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7494 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7495 (defvar org-goto-local-auto-isearch-map) ; defined below
7497 (defun org-get-location (_buf help)
7498 "Let the user select a location in current buffer.
7499 This function uses a recursive edit. It returns the selected position
7500 or nil."
7501 (org-no-popups
7502 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7503 (isearch-hide-immediately nil)
7504 (isearch-search-fun-function
7505 (lambda () 'org-goto-local-search-headings))
7506 (org-goto-selected-point org-goto-exit-command))
7507 (save-excursion
7508 (save-window-excursion
7509 (delete-other-windows)
7510 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7511 (pop-to-buffer-same-window
7512 (condition-case nil
7513 (make-indirect-buffer (current-buffer) "*org-goto*")
7514 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7515 (with-output-to-temp-buffer "*Org Help*"
7516 (princ (format help (if org-goto-auto-isearch
7517 " Just type for auto-isearch."
7518 " n/p/f/b/u to navigate, q to quit."))))
7519 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7520 (setq buffer-read-only nil)
7521 (let ((org-startup-truncated t)
7522 (org-startup-folded nil)
7523 (org-startup-align-all-tables nil))
7524 (org-mode)
7525 (org-overview))
7526 (setq buffer-read-only t)
7527 (if (and (boundp 'org-goto-start-pos)
7528 (integer-or-marker-p org-goto-start-pos))
7529 (progn (goto-char org-goto-start-pos)
7530 (when (outline-invisible-p)
7531 (org-show-set-visibility 'lineage)))
7532 (goto-char (point-min)))
7533 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7534 (message "Select location and press RET")
7535 (use-local-map org-goto-map)
7536 (recursive-edit)))
7537 (kill-buffer "*org-goto*")
7538 (cons org-goto-selected-point org-goto-exit-command))))
7540 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7541 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7542 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7543 (if (fboundp 'isearch-other-control-char)
7544 (progn
7545 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7546 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7547 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7548 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7549 (define-key org-goto-local-auto-isearch-map [return] nil))
7551 (defun org-goto-local-search-headings (string bound noerror)
7552 "Search and make sure that any matches are in headlines."
7553 (catch 'return
7554 (while (if isearch-forward
7555 (search-forward string bound noerror)
7556 (search-backward string bound noerror))
7557 (when (save-match-data
7558 (and (save-excursion
7559 (beginning-of-line)
7560 (looking-at org-complex-heading-regexp))
7561 (or (not (match-beginning 5))
7562 (< (point) (match-beginning 5)))))
7563 (throw 'return (point))))))
7565 (defun org-goto-local-auto-isearch ()
7566 "Start isearch."
7567 (interactive)
7568 (goto-char (point-min))
7569 (let ((keys (this-command-keys)))
7570 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7571 (isearch-mode t)
7572 (isearch-process-search-char (string-to-char keys)))))
7574 (defun org-goto-ret (&optional _arg)
7575 "Finish `org-goto' by going to the new location."
7576 (interactive "P")
7577 (setq org-goto-selected-point (point))
7578 (setq org-goto-exit-command 'return)
7579 (throw 'exit nil))
7581 (defun org-goto-left ()
7582 "Finish `org-goto' by going to the new location."
7583 (interactive)
7584 (if (org-at-heading-p)
7585 (progn
7586 (beginning-of-line 1)
7587 (setq org-goto-selected-point (point)
7588 org-goto-exit-command 'left)
7589 (throw 'exit nil))
7590 (user-error "Not on a heading")))
7592 (defun org-goto-right ()
7593 "Finish `org-goto' by going to the new location."
7594 (interactive)
7595 (if (org-at-heading-p)
7596 (progn
7597 (setq org-goto-selected-point (point)
7598 org-goto-exit-command 'right)
7599 (throw 'exit nil))
7600 (user-error "Not on a heading")))
7602 (defun org-goto-quit ()
7603 "Finish `org-goto' without cursor motion."
7604 (interactive)
7605 (setq org-goto-selected-point nil)
7606 (setq org-goto-exit-command 'quit)
7607 (throw 'exit nil))
7609 ;;; Indirect buffer display of subtrees
7611 (defvar org-indirect-dedicated-frame nil
7612 "This is the frame being used for indirect tree display.")
7613 (defvar org-last-indirect-buffer nil)
7615 (defun org-tree-to-indirect-buffer (&optional arg)
7616 "Create indirect buffer and narrow it to current subtree.
7618 With a numerical prefix ARG, go up to this level and then take that tree.
7619 If ARG is negative, go up that many levels.
7621 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7622 indirect buffer previously made with this command, to avoid proliferation of
7623 indirect buffers. However, when you call the command with a \
7624 `\\[universal-argument]' prefix, or
7625 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7626 so that you can work with several indirect buffers at the same time. If
7627 `org-indirect-buffer-display' is `dedicated-frame', the \
7628 `\\[universal-argument]' prefix also
7629 requests that a new frame be made for the new buffer, so that the dedicated
7630 frame is not changed."
7631 (interactive "P")
7632 (let ((cbuf (current-buffer))
7633 (cwin (selected-window))
7634 (pos (point))
7635 beg end level heading ibuf)
7636 (save-excursion
7637 (org-back-to-heading t)
7638 (when (numberp arg)
7639 (setq level (org-outline-level))
7640 (when (< arg 0) (setq arg (+ level arg)))
7641 (while (> (setq level (org-outline-level)) arg)
7642 (org-up-heading-safe)))
7643 (setq beg (point)
7644 heading (org-get-heading 'no-tags))
7645 (org-end-of-subtree t t)
7646 (when (org-at-heading-p) (backward-char 1))
7647 (setq end (point)))
7648 (when (and (buffer-live-p org-last-indirect-buffer)
7649 (not (eq org-indirect-buffer-display 'new-frame))
7650 (not arg))
7651 (kill-buffer org-last-indirect-buffer))
7652 (setq ibuf (org-get-indirect-buffer cbuf heading)
7653 org-last-indirect-buffer ibuf)
7654 (cond
7655 ((or (eq org-indirect-buffer-display 'new-frame)
7656 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7657 (select-frame (make-frame))
7658 (delete-other-windows)
7659 (pop-to-buffer-same-window ibuf)
7660 (org-set-frame-title heading))
7661 ((eq org-indirect-buffer-display 'dedicated-frame)
7662 (raise-frame
7663 (select-frame (or (and org-indirect-dedicated-frame
7664 (frame-live-p org-indirect-dedicated-frame)
7665 org-indirect-dedicated-frame)
7666 (setq org-indirect-dedicated-frame (make-frame)))))
7667 (delete-other-windows)
7668 (pop-to-buffer-same-window ibuf)
7669 (org-set-frame-title (concat "Indirect: " heading)))
7670 ((eq org-indirect-buffer-display 'current-window)
7671 (pop-to-buffer-same-window ibuf))
7672 ((eq org-indirect-buffer-display 'other-window)
7673 (pop-to-buffer ibuf))
7674 (t (error "Invalid value")))
7675 (narrow-to-region beg end)
7676 (outline-show-all)
7677 (goto-char pos)
7678 (run-hook-with-args 'org-cycle-hook 'all)
7679 (and (window-live-p cwin) (select-window cwin))))
7681 (defun org-get-indirect-buffer (&optional buffer heading)
7682 (setq buffer (or buffer (current-buffer)))
7683 (let ((n 1) (base (buffer-name buffer)) bname)
7684 (while (buffer-live-p
7685 (get-buffer
7686 (setq bname
7687 (concat base "-"
7688 (if heading (concat heading "-" (number-to-string n))
7689 (number-to-string n))))))
7690 (setq n (1+ n)))
7691 (condition-case nil
7692 (make-indirect-buffer buffer bname 'clone)
7693 (error (make-indirect-buffer buffer bname)))))
7695 (defun org-set-frame-title (title)
7696 "Set the title of the current frame to the string TITLE."
7697 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7699 ;;;; Structure editing
7701 ;;; Inserting headlines
7703 (defun org--line-empty-p (n)
7704 "Is the Nth next line empty?
7706 Counts the current line as N = 1 and the previous line as N = 0;
7707 see `beginning-of-line'."
7708 (save-excursion
7709 (and (not (bobp))
7710 (or (beginning-of-line n) t)
7711 (save-match-data
7712 (looking-at "[ \t]*$")))))
7714 (defun org-previous-line-empty-p ()
7715 "Is the previous line a blank line?
7716 When NEXT is non-nil, check the next line instead."
7717 (org--line-empty-p 0))
7719 (defun org-next-line-empty-p ()
7720 "Is the previous line a blank line?
7721 When NEXT is non-nil, check the next line instead."
7722 (org--line-empty-p 2))
7724 (defun org--blank-before-heading-p (&optional parent)
7725 "Non-nil when an empty line should precede a new heading here.
7726 When optional argument PARENT is non-nil, consider parent
7727 headline instead of current one."
7728 (pcase (assq 'heading org-blank-before-new-entry)
7729 (`(heading . auto)
7730 (save-excursion
7731 (org-with-limited-levels
7732 (unless (and (org-before-first-heading-p)
7733 (not (outline-next-heading)))
7734 (org-back-to-heading t)
7735 (when parent (org-up-heading-safe))
7736 (cond ((not (bobp))
7737 (org-previous-line-empty-p))
7738 ((outline-next-heading)
7739 (org-previous-line-empty-p))
7740 ;; Ignore trailing spaces on last buffer line.
7741 ((progn (skip-chars-backward " \t") (bolp))
7742 (org-previous-line-empty-p))
7743 (t nil))))))
7744 (`(heading . ,value) value)
7745 (_ nil)))
7747 (defun org-insert-heading (&optional arg invisible-ok top)
7748 "Insert a new heading or an item with the same depth at point.
7750 If point is at the beginning of a heading, insert a new heading
7751 or a new headline above the current one. When at the beginning
7752 of a regular line of text, turn it into a heading.
7754 If point is in the middle of a line, split it and create a new
7755 headline with the text in the current line after point (see
7756 `org-M-RET-may-split-line' on how to modify this behavior). As
7757 a special case, on a headline, splitting can only happen on the
7758 title itself. E.g., this excludes breaking stars or tags.
7760 With a `\\[universal-argument]' prefix, set \
7761 `org-insert-heading-respect-content' to
7762 a non-nil value for the duration of the command. This forces the
7763 insertion of a heading after the current subtree, independently
7764 on the location of point.
7766 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7767 insert the heading at the end of the tree
7768 above the current heading. For example, if point is within a
7769 2nd-level heading, then it will insert a 2nd-level heading at
7770 the end of the 1st-level parent subtree.
7772 When INVISIBLE-OK is set, stop at invisible headlines when going
7773 back. This is important for non-interactive uses of the
7774 command.
7776 When optional argument TOP is non-nil, insert a level 1 heading,
7777 unconditionally."
7778 (interactive "P")
7779 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7780 (level (org-current-level))
7781 (stars (make-string (if (and level (not top)) level 1) ?*)))
7782 (cond
7783 ((or org-insert-heading-respect-content
7784 (member arg '((4) (16)))
7785 (and (not invisible-ok)
7786 (invisible-p (max (1- (point)) (point-min)))))
7787 ;; Position point at the location of insertion.
7788 (if (not level) ;before first headline
7789 (org-with-limited-levels (outline-next-heading))
7790 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7791 ;; is nil.
7792 (org-with-limited-levels (org-back-to-heading invisible-ok))
7793 (cond ((equal arg '(16))
7794 (org-up-heading-safe)
7795 (org-end-of-subtree t t))
7797 (org-end-of-subtree t t))))
7798 (unless (bolp) (insert "\n")) ;ensure final newline
7799 (unless (and blank? (org-previous-line-empty-p))
7800 (org-N-empty-lines-before-current (if blank? 1 0)))
7801 (insert stars " \n")
7802 (forward-char -1))
7803 ;; At a headline...
7804 ((org-at-heading-p)
7805 (cond ((bolp)
7806 (when blank? (save-excursion (insert "\n")))
7807 (save-excursion (insert stars " \n"))
7808 (unless (and blank? (org-previous-line-empty-p))
7809 (org-N-empty-lines-before-current (if blank? 1 0)))
7810 (end-of-line))
7811 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7812 (org-match-line org-complex-heading-regexp)
7813 (org-pos-in-match-range (point) 4))
7814 ;; Grab the text that should moved to the new headline.
7815 ;; Preserve tags.
7816 (let ((split (delete-and-extract-region (point) (match-end 4))))
7817 (if (looking-at "[ \t]*$") (replace-match "")
7818 (org-set-tags nil t))
7819 (end-of-line)
7820 (when blank? (insert "\n"))
7821 (insert "\n" stars " ")
7822 (when (org-string-nw-p split) (insert split))
7823 (when (eobp) (save-excursion (insert "\n")))))
7825 (end-of-line)
7826 (when blank? (insert "\n"))
7827 (insert "\n" stars " ")
7828 (when (eobp) (save-excursion (insert "\n"))))))
7829 ;; On regular text, turn line into a headline or split, if
7830 ;; appropriate.
7831 ((bolp)
7832 (insert stars " ")
7833 (unless (and blank? (org-previous-line-empty-p))
7834 (org-N-empty-lines-before-current (if blank? 1 0))))
7836 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7837 (end-of-line))
7838 (insert "\n" stars " ")
7839 (unless (and blank? (org-previous-line-empty-p))
7840 (org-N-empty-lines-before-current (if blank? 1 0))))))
7841 (run-hooks 'org-insert-heading-hook))
7843 (defun org-N-empty-lines-before-current (n)
7844 "Make the number of empty lines before current exactly N.
7845 So this will delete or add empty lines."
7846 (let ((column (current-column)))
7847 (beginning-of-line)
7848 (unless (bobp)
7849 (let ((start (save-excursion
7850 (skip-chars-backward " \r\t\n")
7851 (line-end-position))))
7852 (delete-region start (line-end-position 0))))
7853 (insert (make-string n ?\n))
7854 (move-to-column column)))
7856 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7857 "Return the heading of the current entry, without the stars.
7858 When NO-TAGS is non-nil, don't include tags.
7859 When NO-TODO is non-nil, don't include TODO keywords.
7860 When NO-PRIORITY is non-nil, don't include priority cookie.
7861 When NO-COMMENT is non-nil, don't include COMMENT string."
7862 (save-excursion
7863 (org-back-to-heading t)
7864 (let ((case-fold-search nil))
7865 (looking-at org-complex-heading-regexp)
7866 (let ((todo (and (not no-todo) (match-string 2)))
7867 (priority (and (not no-priority) (match-string 3)))
7868 (headline (pcase (match-string 4)
7869 (`nil "")
7870 ((and (guard no-comment) h)
7871 (replace-regexp-in-string
7872 (eval-when-compile
7873 (format "\\`%s[ \t]+" org-comment-string))
7874 "" h))
7875 (h h)))
7876 (tags (and (not no-tags) (match-string 5))))
7877 (mapconcat #'identity
7878 (delq nil (list todo priority headline tags))
7879 " ")))))
7881 (defvar orgstruct-mode) ; defined below
7883 (defun org-heading-components ()
7884 "Return the components of the current heading.
7885 This is a list with the following elements:
7886 - the level as an integer
7887 - the reduced level, different if `org-odd-levels-only' is set.
7888 - the TODO keyword, or nil
7889 - the priority character, like ?A, or nil if no priority is given
7890 - the headline text itself, or the tags string if no headline text
7891 - the tags string, or nil."
7892 (save-excursion
7893 (org-back-to-heading t)
7894 (when (let (case-fold-search)
7895 (looking-at
7896 (if orgstruct-mode
7897 org-heading-regexp
7898 org-complex-heading-regexp)))
7899 (if orgstruct-mode
7900 (list (length (match-string 1))
7901 (org-reduced-level (length (match-string 1)))
7904 (match-string 2)
7905 nil)
7906 (list (length (match-string 1))
7907 (org-reduced-level (length (match-string 1)))
7908 (match-string-no-properties 2)
7909 (and (match-end 3) (aref (match-string 3) 2))
7910 (match-string-no-properties 4)
7911 (match-string-no-properties 5))))))
7913 (defun org-get-entry ()
7914 "Get the entry text, after heading, entire subtree."
7915 (save-excursion
7916 (org-back-to-heading t)
7917 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7919 (defun org-edit-headline (&optional heading)
7920 "Edit the current headline.
7921 Set it to HEADING when provided."
7922 (interactive)
7923 (org-with-wide-buffer
7924 (org-back-to-heading t)
7925 (let ((case-fold-search nil))
7926 (when (looking-at org-complex-heading-regexp)
7927 (let* ((old (match-string-no-properties 4))
7928 (new (save-match-data
7929 (org-trim (or heading (read-string "Edit: " old))))))
7930 (unless (equal old new)
7931 (if old (replace-match new t t nil 4)
7932 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7933 (insert " " new))
7934 (org-set-tags nil t)
7935 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7937 (defun org-insert-heading-after-current ()
7938 "Insert a new heading with same level as current, after current subtree."
7939 (interactive)
7940 (org-back-to-heading)
7941 (org-insert-heading)
7942 (org-move-subtree-down)
7943 (end-of-line 1))
7945 (defun org-insert-heading-respect-content (&optional invisible-ok)
7946 "Insert heading with `org-insert-heading-respect-content' set to t."
7947 (interactive)
7948 (org-insert-heading '(4) invisible-ok))
7950 (defun org-insert-todo-heading-respect-content (&optional force-state)
7951 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7952 (interactive)
7953 (org-insert-todo-heading force-state '(4)))
7955 (defun org-insert-todo-heading (arg &optional force-heading)
7956 "Insert a new heading with the same level and TODO state as current heading.
7958 If the heading has no TODO state, or if the state is DONE, use
7959 the first state (TODO by default). Also with one prefix arg,
7960 force first state. With two prefix args, force inserting at the
7961 end of the parent subtree.
7963 When called at a plain list item, insert a new item with an
7964 unchecked check box."
7965 (interactive "P")
7966 (when (or force-heading (not (org-insert-item 'checkbox)))
7967 (org-insert-heading (or (and (equal arg '(16)) '(16))
7968 force-heading))
7969 (save-excursion
7970 (org-back-to-heading)
7971 (outline-previous-heading)
7972 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7973 (let* ((new-mark-x
7974 (if (or (equal arg '(4))
7975 (not (match-beginning 2))
7976 (member (match-string 2) org-done-keywords))
7977 (car org-todo-keywords-1)
7978 (match-string 2)))
7979 (new-mark
7981 (run-hook-with-args-until-success
7982 'org-todo-get-default-hook new-mark-x nil)
7983 new-mark-x)))
7984 (beginning-of-line 1)
7985 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7986 (if org-treat-insert-todo-heading-as-state-change
7987 (org-todo new-mark)
7988 (insert new-mark " "))))
7989 (when org-provide-todo-statistics
7990 (org-update-parent-todo-statistics))))
7992 (defun org-insert-subheading (arg)
7993 "Insert a new subheading and demote it.
7994 Works for outline headings and for plain lists alike."
7995 (interactive "P")
7996 (org-insert-heading arg)
7997 (cond
7998 ((org-at-heading-p) (org-do-demote))
7999 ((org-at-item-p) (org-indent-item))))
8001 (defun org-insert-todo-subheading (arg)
8002 "Insert a new subheading with TODO keyword or checkbox and demote it.
8003 Works for outline headings and for plain lists alike."
8004 (interactive "P")
8005 (org-insert-todo-heading arg)
8006 (cond
8007 ((org-at-heading-p) (org-do-demote))
8008 ((org-at-item-p) (org-indent-item))))
8010 ;;; Promotion and Demotion
8012 (defvar org-after-demote-entry-hook nil
8013 "Hook run after an entry has been demoted.
8014 The cursor will be at the beginning of the entry.
8015 When a subtree is being demoted, the hook will be called for each node.")
8017 (defvar org-after-promote-entry-hook nil
8018 "Hook run after an entry has been promoted.
8019 The cursor will be at the beginning of the entry.
8020 When a subtree is being promoted, the hook will be called for each node.")
8022 (defun org-promote-subtree ()
8023 "Promote the entire subtree.
8024 See also `org-promote'."
8025 (interactive)
8026 (save-excursion
8027 (org-with-limited-levels (org-map-tree 'org-promote)))
8028 (org-fix-position-after-promote))
8030 (defun org-demote-subtree ()
8031 "Demote the entire subtree.
8032 See `org-demote' and `org-promote'."
8033 (interactive)
8034 (save-excursion
8035 (org-with-limited-levels (org-map-tree 'org-demote)))
8036 (org-fix-position-after-promote))
8038 (defun org-do-promote ()
8039 "Promote the current heading higher up the tree.
8040 If the region is active in `transient-mark-mode', promote all
8041 headings in the region."
8042 (interactive)
8043 (save-excursion
8044 (if (org-region-active-p)
8045 (org-map-region 'org-promote (region-beginning) (region-end))
8046 (org-promote)))
8047 (org-fix-position-after-promote))
8049 (defun org-do-demote ()
8050 "Demote the current heading lower down the tree.
8051 If the region is active in `transient-mark-mode', demote all
8052 headings in the region."
8053 (interactive)
8054 (save-excursion
8055 (if (org-region-active-p)
8056 (org-map-region 'org-demote (region-beginning) (region-end))
8057 (org-demote)))
8058 (org-fix-position-after-promote))
8060 (defun org-fix-position-after-promote ()
8061 "Fix cursor position and indentation after demoting/promoting."
8062 (let ((pos (point)))
8063 (when (save-excursion
8064 (beginning-of-line)
8065 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8066 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8067 (cond ((eobp) (insert " "))
8068 ((eolp) (insert " "))
8069 ((equal (char-after) ?\s) (forward-char 1))))))
8071 (defun org-current-level ()
8072 "Return the level of the current entry, or nil if before the first headline.
8073 The level is the number of stars at the beginning of the
8074 headline. Use `org-reduced-level' to remove the effect of
8075 `org-odd-levels'. Unlike to `org-outline-level', this function
8076 ignores inlinetasks."
8077 (let ((level (org-with-limited-levels (org-outline-level))))
8078 (and (> level 0) level)))
8080 (defun org-get-previous-line-level ()
8081 "Return the outline depth of the last headline before the current line.
8082 Returns 0 for the first headline in the buffer, and nil if before the
8083 first headline."
8084 (and (org-current-level)
8085 (or (and (/= (line-beginning-position) (point-min))
8086 (save-excursion (beginning-of-line 0) (org-current-level)))
8087 0)))
8089 (defun org-reduced-level (l)
8090 "Compute the effective level of a heading.
8091 This takes into account the setting of `org-odd-levels-only'."
8092 (cond
8093 ((zerop l) 0)
8094 (org-odd-levels-only (1+ (floor (/ l 2))))
8095 (t l)))
8097 (defun org-level-increment ()
8098 "Return the number of stars that will be added or removed at a
8099 time to headlines when structure editing, based on the value of
8100 `org-odd-levels-only'."
8101 (if org-odd-levels-only 2 1))
8103 (defun org-get-valid-level (level &optional change)
8104 "Rectify a level change under the influence of `org-odd-levels-only'.
8105 LEVEL is a current level, CHANGE is by how much the level should
8106 be modified. Even if CHANGE is nil, LEVEL may be returned
8107 modified because even level numbers will become the next higher
8108 odd number. Returns values greater than 0."
8109 (if org-odd-levels-only
8110 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8111 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8112 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8113 (max 1 (+ level (or change 0)))))
8115 (defun org-promote ()
8116 "Promote the current heading higher up the tree."
8117 (org-with-wide-buffer
8118 (org-back-to-heading t)
8119 (let* ((after-change-functions (remq 'flyspell-after-change-function
8120 after-change-functions))
8121 (level (save-match-data (funcall outline-level)))
8122 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8123 (diff (abs (- level (length up-head) -1))))
8124 (cond
8125 ((and (= level 1) org-allow-promoting-top-level-subtree)
8126 (replace-match "# " nil t))
8127 ((= level 1)
8128 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8129 (t (replace-match up-head nil t)))
8130 (unless (= level 1)
8131 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8132 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8133 (run-hooks 'org-after-promote-entry-hook))))
8135 (defun org-demote ()
8136 "Demote the current heading lower down the tree."
8137 (org-with-wide-buffer
8138 (org-back-to-heading t)
8139 (let* ((after-change-functions (remq 'flyspell-after-change-function
8140 after-change-functions))
8141 (level (save-match-data (funcall outline-level)))
8142 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8143 (diff (abs (- level (length down-head) -1))))
8144 (replace-match down-head nil t)
8145 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8146 (when org-adapt-indentation (org-fixup-indentation diff))
8147 (run-hooks 'org-after-demote-entry-hook))))
8149 (defun org-cycle-level ()
8150 "Cycle the level of an empty headline through possible states.
8151 This goes first to child, then to parent, level, then up the hierarchy.
8152 After top level, it switches back to sibling level."
8153 (interactive)
8154 (let ((org-adapt-indentation nil))
8155 (when (org-point-at-end-of-empty-headline)
8156 (setq this-command 'org-cycle-level) ; Only needed for caching
8157 (let ((cur-level (org-current-level))
8158 (prev-level (org-get-previous-line-level)))
8159 (cond
8160 ;; If first headline in file, promote to top-level.
8161 ((= prev-level 0)
8162 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8163 do (org-do-promote)))
8164 ;; If same level as prev, demote one.
8165 ((= prev-level cur-level)
8166 (org-do-demote))
8167 ;; If parent is top-level, promote to top level if not already.
8168 ((= prev-level 1)
8169 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8170 do (org-do-promote)))
8171 ;; If top-level, return to prev-level.
8172 ((= cur-level 1)
8173 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8174 do (org-do-demote)))
8175 ;; If less than prev-level, promote one.
8176 ((< cur-level prev-level)
8177 (org-do-promote))
8178 ;; If deeper than prev-level, promote until higher than
8179 ;; prev-level.
8180 ((> cur-level prev-level)
8181 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8182 do (org-do-promote))))
8183 t))))
8185 (defun org-map-tree (fun)
8186 "Call FUN for every heading underneath the current one."
8187 (org-back-to-heading t)
8188 (let ((level (funcall outline-level)))
8189 (save-excursion
8190 (funcall fun)
8191 (while (and (progn
8192 (outline-next-heading)
8193 (> (funcall outline-level) level))
8194 (not (eobp)))
8195 (funcall fun)))))
8197 (defun org-map-region (fun beg end)
8198 "Call FUN for every heading between BEG and END."
8199 (let ((org-ignore-region t))
8200 (save-excursion
8201 (setq end (copy-marker end))
8202 (goto-char beg)
8203 (when (and (re-search-forward org-outline-regexp-bol nil t)
8204 (< (point) end))
8205 (funcall fun))
8206 (while (and (progn
8207 (outline-next-heading)
8208 (< (point) end))
8209 (not (eobp)))
8210 (funcall fun)))))
8212 (defun org-fixup-indentation (diff)
8213 "Change the indentation in the current entry by DIFF.
8215 DIFF is an integer. Indentation is done according to the
8216 following rules:
8218 - Planning information and property drawers are always indented
8219 according to the new level of the headline;
8221 - Footnote definitions and their contents are ignored;
8223 - Inlinetasks' boundaries are not shifted;
8225 - Empty lines are ignored;
8227 - Other lines' indentation are shifted by DIFF columns, unless
8228 it would introduce a structural change in the document, in
8229 which case no shifting is done at all.
8231 Assume point is at a heading or an inlinetask beginning."
8232 (org-with-wide-buffer
8233 (narrow-to-region (line-beginning-position)
8234 (save-excursion
8235 (if (org-with-limited-levels (org-at-heading-p))
8236 (org-with-limited-levels (outline-next-heading))
8237 (org-inlinetask-goto-end))
8238 (point)))
8239 (forward-line)
8240 ;; Indent properly planning info and property drawer.
8241 (when (looking-at-p org-planning-line-re)
8242 (org-indent-line)
8243 (forward-line))
8244 (when (looking-at org-property-drawer-re)
8245 (goto-char (match-end 0))
8246 (forward-line)
8247 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8248 (catch 'no-shift
8249 (when (zerop diff) (throw 'no-shift nil))
8250 ;; If DIFF is negative, first check if a shift is possible at all
8251 ;; (e.g., it doesn't break structure). This can only happen if
8252 ;; some contents are not properly indented.
8253 (let ((case-fold-search t))
8254 (when (< diff 0)
8255 (let ((diff (- diff))
8256 (forbidden-re (concat org-outline-regexp
8257 "\\|"
8258 (substring org-footnote-definition-re 1))))
8259 (save-excursion
8260 (while (not (eobp))
8261 (cond
8262 ((looking-at-p "[ \t]*$") (forward-line))
8263 ((and (looking-at-p org-footnote-definition-re)
8264 (let ((e (org-element-at-point)))
8265 (and (eq (org-element-type e) 'footnote-definition)
8266 (goto-char (org-element-property :end e))))))
8267 ((looking-at-p org-outline-regexp) (forward-line))
8268 ;; Give up if shifting would move before column 0 or
8269 ;; if it would introduce a headline or a footnote
8270 ;; definition.
8272 (skip-chars-forward " \t")
8273 (let ((ind (current-column)))
8274 (when (or (< ind diff)
8275 (and (= ind diff) (looking-at-p forbidden-re)))
8276 (throw 'no-shift nil)))
8277 ;; Ignore contents of example blocks and source
8278 ;; blocks if their indentation is meant to be
8279 ;; preserved. Jump to block's closing line.
8280 (beginning-of-line)
8281 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8282 (let ((e (org-element-at-point)))
8283 (and (memq (org-element-type e)
8284 '(example-block src-block))
8285 (or org-src-preserve-indentation
8286 (org-element-property :preserve-indent e))
8287 (goto-char (org-element-property :end e))
8288 (progn (skip-chars-backward " \r\t\n")
8289 (beginning-of-line)
8290 t))))
8291 (forward-line))))))))
8292 ;; Shift lines but footnote definitions, inlinetasks boundaries
8293 ;; by DIFF. Also skip contents of source or example blocks
8294 ;; when indentation is meant to be preserved.
8295 (while (not (eobp))
8296 (cond
8297 ((and (looking-at-p org-footnote-definition-re)
8298 (let ((e (org-element-at-point)))
8299 (and (eq (org-element-type e) 'footnote-definition)
8300 (goto-char (org-element-property :end e))))))
8301 ((looking-at-p org-outline-regexp) (forward-line))
8302 ((looking-at-p "[ \t]*$") (forward-line))
8304 (indent-line-to (+ (org-get-indentation) diff))
8305 (beginning-of-line)
8306 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8307 (let ((e (org-element-at-point)))
8308 (and (memq (org-element-type e)
8309 '(example-block src-block))
8310 (or org-src-preserve-indentation
8311 (org-element-property :preserve-indent e))
8312 (goto-char (org-element-property :end e))
8313 (progn (skip-chars-backward " \r\t\n")
8314 (beginning-of-line)
8315 t))))
8316 (forward-line)))))))))
8318 (defun org-convert-to-odd-levels ()
8319 "Convert an Org file with all levels allowed to one with odd levels.
8320 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8321 level 5 etc."
8322 (interactive)
8323 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8324 (let ((outline-level 'org-outline-level)
8325 (org-odd-levels-only nil) n)
8326 (save-excursion
8327 (goto-char (point-min))
8328 (while (re-search-forward "^\\*\\*+ " nil t)
8329 (setq n (- (length (match-string 0)) 2))
8330 (while (>= (setq n (1- n)) 0)
8331 (org-demote))
8332 (end-of-line 1))))))
8334 (defun org-convert-to-oddeven-levels ()
8335 "Convert an Org file with only odd levels to one with odd/even levels.
8336 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8337 file contains a section with an even level, conversion would
8338 destroy the structure of the file. An error is signaled in this
8339 case."
8340 (interactive)
8341 (goto-char (point-min))
8342 ;; First check if there are no even levels
8343 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8344 (org-show-set-visibility 'canonical)
8345 (error "Not all levels are odd in this file. Conversion not possible"))
8346 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8347 (let ((outline-regexp org-outline-regexp)
8348 (outline-level 'org-outline-level)
8349 (org-odd-levels-only nil) n)
8350 (save-excursion
8351 (goto-char (point-min))
8352 (while (re-search-forward "^\\*\\*+ " nil t)
8353 (setq n (/ (1- (length (match-string 0))) 2))
8354 (while (>= (setq n (1- n)) 0)
8355 (org-promote))
8356 (end-of-line 1))))))
8358 (defun org-tr-level (n)
8359 "Make N odd if required."
8360 (if org-odd-levels-only (1+ (/ n 2)) n))
8362 ;;; Vertical tree motion, cutting and pasting of subtrees
8364 (defun org-move-subtree-up (&optional arg)
8365 "Move the current subtree up past ARG headlines of the same level."
8366 (interactive "p")
8367 (org-move-subtree-down (- (prefix-numeric-value arg))))
8369 (defun org-move-subtree-down (&optional arg)
8370 "Move the current subtree down past ARG headlines of the same level."
8371 (interactive "p")
8372 (setq arg (prefix-numeric-value arg))
8373 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8374 'org-get-last-sibling))
8375 (ins-point (make-marker))
8376 (cnt (abs arg))
8377 (col (current-column))
8378 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8379 ;; Select the tree
8380 (org-back-to-heading)
8381 (setq beg0 (point))
8382 (save-excursion
8383 (setq ne-beg (org-back-over-empty-lines))
8384 (setq beg (point)))
8385 (save-match-data
8386 (save-excursion (outline-end-of-heading)
8387 (setq folded (outline-invisible-p)))
8388 (progn (org-end-of-subtree nil t)
8389 (unless (eobp) (backward-char))))
8390 (outline-next-heading)
8391 (setq ne-end (org-back-over-empty-lines))
8392 (setq end (point))
8393 (goto-char beg0)
8394 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8395 ;; include less whitespace
8396 (save-excursion
8397 (goto-char beg)
8398 (forward-line (- ne-beg ne-end))
8399 (setq beg (point))))
8400 ;; Find insertion point, with error handling
8401 (while (> cnt 0)
8402 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8403 (progn (goto-char beg0)
8404 (user-error "Cannot move past superior level or buffer limit")))
8405 (setq cnt (1- cnt)))
8406 (when (> arg 0)
8407 ;; Moving forward - still need to move over subtree
8408 (org-end-of-subtree t t)
8409 (save-excursion
8410 (org-back-over-empty-lines)
8411 (or (bolp) (newline))))
8412 (setq ne-ins (org-back-over-empty-lines))
8413 (move-marker ins-point (point))
8414 (setq txt (buffer-substring beg end))
8415 (org-save-markers-in-region beg end)
8416 (delete-region beg end)
8417 (org-remove-empty-overlays-at beg)
8418 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8419 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8420 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8421 (let ((bbb (point)))
8422 (insert-before-markers txt)
8423 (org-reinstall-markers-in-region bbb)
8424 (move-marker ins-point bbb))
8425 (or (bolp) (insert "\n"))
8426 (setq ins-end (point))
8427 (goto-char ins-point)
8428 (org-skip-whitespace)
8429 (when (and (< arg 0)
8430 (org-first-sibling-p)
8431 (> ne-ins ne-beg))
8432 ;; Move whitespace back to beginning
8433 (save-excursion
8434 (goto-char ins-end)
8435 (let ((kill-whole-line t))
8436 (kill-line (- ne-ins ne-beg)) (point)))
8437 (insert (make-string (- ne-ins ne-beg) ?\n)))
8438 (move-marker ins-point nil)
8439 (if folded
8440 (outline-hide-subtree)
8441 (org-show-entry)
8442 (org-show-children)
8443 (org-cycle-hide-drawers 'children))
8444 (org-clean-visibility-after-subtree-move)
8445 ;; move back to the initial column we were at
8446 (move-to-column col)))
8448 (defvar org-subtree-clip ""
8449 "Clipboard for cut and paste of subtrees.
8450 This is actually only a copy of the kill, because we use the normal kill
8451 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8453 (defvar org-subtree-clip-folded nil
8454 "Was the last copied subtree folded?
8455 This is used to fold the tree back after pasting.")
8457 (defun org-cut-subtree (&optional n)
8458 "Cut the current subtree into the clipboard.
8459 With prefix arg N, cut this many sequential subtrees.
8460 This is a short-hand for marking the subtree and then cutting it."
8461 (interactive "p")
8462 (org-copy-subtree n 'cut))
8464 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8465 "Copy the current subtree it in the clipboard.
8466 With prefix arg N, copy this many sequential subtrees.
8467 This is a short-hand for marking the subtree and then copying it.
8468 If CUT is non-nil, actually cut the subtree.
8469 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8470 of some markers in the region, even if CUT is non-nil. This is
8471 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8472 (interactive "p")
8473 (let (beg end folded (beg0 (point)))
8474 (if (called-interactively-p 'any)
8475 (org-back-to-heading nil) ; take what looks like a subtree
8476 (org-back-to-heading t)) ; take what is really there
8477 (setq beg (point))
8478 (skip-chars-forward " \t\r\n")
8479 (save-match-data
8480 (if nosubtrees
8481 (outline-next-heading)
8482 (save-excursion (outline-end-of-heading)
8483 (setq folded (outline-invisible-p)))
8484 (ignore-errors (org-forward-heading-same-level (1- n) t))
8485 (org-end-of-subtree t t)))
8486 ;; Include the end of an inlinetask
8487 (when (and (featurep 'org-inlinetask)
8488 (looking-at-p (concat (org-inlinetask-outline-regexp)
8489 "END[ \t]*$")))
8490 (end-of-line))
8491 (setq end (point))
8492 (goto-char beg0)
8493 (when (> end beg)
8494 (setq org-subtree-clip-folded folded)
8495 (when (or cut force-store-markers)
8496 (org-save-markers-in-region beg end))
8497 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8498 (setq org-subtree-clip (current-kill 0))
8499 (message "%s: Subtree(s) with %d characters"
8500 (if cut "Cut" "Copied")
8501 (length org-subtree-clip)))))
8503 (defun org-paste-subtree (&optional level tree for-yank remove)
8504 "Paste the clipboard as a subtree, with modification of headline level.
8505 The entire subtree is promoted or demoted in order to match a new headline
8506 level.
8508 If the cursor is at the beginning of a headline, the same level as
8509 that headline is used to paste the tree.
8511 If not, the new level is derived from the *visible* headings
8512 before and after the insertion point, and taken to be the inferior headline
8513 level of the two. So if the previous visible heading is level 3 and the
8514 next is level 4 (or vice versa), level 4 will be used for insertion.
8515 This makes sure that the subtree remains an independent subtree and does
8516 not swallow low level entries.
8518 You can also force a different level, either by using a numeric prefix
8519 argument, or by inserting the heading marker by hand. For example, if the
8520 cursor is after \"*****\", then the tree will be shifted to level 5.
8522 If optional TREE is given, use this text instead of the kill ring.
8524 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8525 move back over whitespace before inserting, and move point to the end of
8526 the inserted text when done.
8528 When REMOVE is non-nil, remove the subtree from the clipboard."
8529 (interactive "P")
8530 (setq tree (or tree (and kill-ring (current-kill 0))))
8531 (unless (org-kill-is-subtree-p tree)
8532 (user-error "%s"
8533 (substitute-command-keys
8534 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8535 (org-with-limited-levels
8536 (let* ((visp (not (outline-invisible-p)))
8537 (txt tree)
8538 (^re_ "\\(\\*+\\)[ \t]*")
8539 (old-level (if (string-match org-outline-regexp-bol txt)
8540 (- (match-end 0) (match-beginning 0) 1)
8541 -1))
8542 (force-level (cond (level (prefix-numeric-value level))
8543 ((and (looking-at "[ \t]*$")
8544 (string-match
8545 "^\\*+$" (buffer-substring
8546 (point-at-bol) (point))))
8547 (- (match-end 0) (match-beginning 0)))
8548 ((and (bolp)
8549 (looking-at org-outline-regexp))
8550 (- (match-end 0) (point) 1))))
8551 (previous-level (save-excursion
8552 (condition-case nil
8553 (progn
8554 (outline-previous-visible-heading 1)
8555 (if (looking-at ^re_)
8556 (- (match-end 0) (match-beginning 0) 1)
8558 (error 1))))
8559 (next-level (save-excursion
8560 (condition-case nil
8561 (progn
8562 (or (looking-at org-outline-regexp)
8563 (outline-next-visible-heading 1))
8564 (if (looking-at ^re_)
8565 (- (match-end 0) (match-beginning 0) 1)
8567 (error 1))))
8568 (new-level (or force-level (max previous-level next-level)))
8569 (shift (if (or (= old-level -1)
8570 (= new-level -1)
8571 (= old-level new-level))
8573 (- new-level old-level)))
8574 (delta (if (> shift 0) -1 1))
8575 (func (if (> shift 0) 'org-demote 'org-promote))
8576 (org-odd-levels-only nil)
8577 beg end newend)
8578 ;; Remove the forced level indicator
8579 (when force-level
8580 (delete-region (point-at-bol) (point)))
8581 ;; Paste
8582 (beginning-of-line (if (bolp) 1 2))
8583 (setq beg (point))
8584 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8585 (insert-before-markers txt)
8586 (unless (string-suffix-p "\n" txt) (insert "\n"))
8587 (setq newend (point))
8588 (org-reinstall-markers-in-region beg)
8589 (setq end (point))
8590 (goto-char beg)
8591 (skip-chars-forward " \t\n\r")
8592 (setq beg (point))
8593 (when (and (outline-invisible-p) visp)
8594 (save-excursion (outline-show-heading)))
8595 ;; Shift if necessary
8596 (unless (= shift 0)
8597 (save-restriction
8598 (narrow-to-region beg end)
8599 (while (not (= shift 0))
8600 (org-map-region func (point-min) (point-max))
8601 (setq shift (+ delta shift)))
8602 (goto-char (point-min))
8603 (setq newend (point-max))))
8604 (when (or (called-interactively-p 'interactive) for-yank)
8605 (message "Clipboard pasted as level %d subtree" new-level))
8606 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8607 kill-ring
8608 (eq org-subtree-clip (current-kill 0))
8609 org-subtree-clip-folded)
8610 ;; The tree was folded before it was killed/copied
8611 (outline-hide-subtree))
8612 (and for-yank (goto-char newend))
8613 (and remove (setq kill-ring (cdr kill-ring))))))
8615 (defun org-kill-is-subtree-p (&optional txt)
8616 "Check if the current kill is an outline subtree, or a set of trees.
8617 Returns nil if kill does not start with a headline, or if the first
8618 headline level is not the largest headline level in the tree.
8619 So this will actually accept several entries of equal levels as well,
8620 which is OK for `org-paste-subtree'.
8621 If optional TXT is given, check this string instead of the current kill."
8622 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8623 (re (org-get-limited-outline-regexp))
8624 (^re (concat "^" re))
8625 (start-level (and kill
8626 (string-match
8627 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8628 kill)
8629 (- (match-end 2) (match-beginning 2) 1)))
8630 (start (1+ (or (match-beginning 2) -1))))
8631 (if (not start-level)
8632 (progn
8633 nil) ;; does not even start with a heading
8634 (catch 'exit
8635 (while (setq start (string-match ^re kill (1+ start)))
8636 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8637 (throw 'exit nil)))
8638 t))))
8640 (defvar org-markers-to-move nil
8641 "Markers that should be moved with a cut-and-paste operation.
8642 Those markers are stored together with their positions relative to
8643 the start of the region.")
8645 (defun org-save-markers-in-region (beg end)
8646 "Check markers in region.
8647 If these markers are between BEG and END, record their position relative
8648 to BEG, so that after moving the block of text, we can put the markers back
8649 into place.
8650 This function gets called just before an entry or tree gets cut from the
8651 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8652 called immediately, to move the markers with the entries."
8653 (setq org-markers-to-move nil)
8654 (when (featurep 'org-clock)
8655 (org-clock-save-markers-for-cut-and-paste beg end))
8656 (when (featurep 'org-agenda)
8657 (org-agenda-save-markers-for-cut-and-paste beg end)))
8659 (defun org-check-and-save-marker (marker beg end)
8660 "Check if MARKER is between BEG and END.
8661 If yes, remember the marker and the distance to BEG."
8662 (when (and (marker-buffer marker)
8663 (equal (marker-buffer marker) (current-buffer))
8664 (>= marker beg) (< marker end))
8665 (push (cons marker (- marker beg)) org-markers-to-move)))
8667 (defun org-reinstall-markers-in-region (beg)
8668 "Move all remembered markers to their position relative to BEG."
8669 (dolist (x org-markers-to-move)
8670 (move-marker (car x) (+ beg (cdr x))))
8671 (setq org-markers-to-move nil))
8673 (defun org-narrow-to-subtree ()
8674 "Narrow buffer to the current subtree."
8675 (interactive)
8676 (save-excursion
8677 (save-match-data
8678 (org-with-limited-levels
8679 (narrow-to-region
8680 (progn (org-back-to-heading t) (point))
8681 (progn (org-end-of-subtree t t)
8682 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8683 (point)))))))
8685 (defun org-narrow-to-block ()
8686 "Narrow buffer to the current block."
8687 (interactive)
8688 (let* ((case-fold-search t)
8689 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8690 "^[ \t]*#\\+end_.*")))
8691 (if blockp
8692 (narrow-to-region (car blockp) (cdr blockp))
8693 (user-error "Not in a block"))))
8695 (defun org-clone-subtree-with-time-shift (n &optional shift)
8696 "Clone the task (subtree) at point N times.
8697 The clones will be inserted as siblings.
8699 In interactive use, the user will be prompted for the number of
8700 clones to be produced. If the entry has a timestamp, the user
8701 will also be prompted for a time shift, which may be a repeater
8702 as used in time stamps, for example `+3d'. To disable this,
8703 you can call the function with a universal prefix argument.
8705 When a valid repeater is given and the entry contains any time
8706 stamps, the clones will become a sequence in time, with time
8707 stamps in the subtree shifted for each clone produced. If SHIFT
8708 is nil or the empty string, time stamps will be left alone. The
8709 ID property of the original subtree is removed.
8711 In each clone, all the CLOCK entries will be removed. This
8712 prevents Org from considering that the clocked times overlap.
8714 If the original subtree did contain time stamps with a repeater,
8715 the following will happen:
8716 - the repeater will be removed in each clone
8717 - an additional clone will be produced, with the current, unshifted
8718 date(s) in the entry.
8719 - the original entry will be placed *after* all the clones, with
8720 repeater intact.
8721 - the start days in the repeater in the original entry will be shifted
8722 to past the last clone.
8723 In this way you can spell out a number of instances of a repeating task,
8724 and still retain the repeater to cover future instances of the task.
8726 As described above, N+1 clones are produced when the original
8727 subtree has a repeater. Setting N to 0, then, can be used to
8728 remove the repeater from a subtree and create a shifted clone
8729 with the original repeater."
8730 (interactive "nNumber of clones to produce: ")
8731 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8732 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8733 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8734 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8735 (shift
8736 (or shift
8737 (if (and (not (equal current-prefix-arg '(4)))
8738 (save-excursion
8739 (goto-char beg)
8740 (re-search-forward org-ts-regexp-both end-of-tree t)))
8741 (read-from-minibuffer
8742 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8743 ""))) ;No time shift
8744 (doshift
8745 (and (org-string-nw-p shift)
8746 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8747 shift)
8748 (user-error "Invalid shift specification %s" shift)))))
8749 (goto-char end-of-tree)
8750 (unless (bolp) (insert "\n"))
8751 (let* ((end (point))
8752 (template (buffer-substring beg end))
8753 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8754 (shift-what (pcase (and doshift (match-string 2 shift))
8755 (`nil nil)
8756 ("d" 'day)
8757 ("w" (setq shift-n (* 7 shift-n)) 'day)
8758 ("m" 'month)
8759 ("y" 'year)
8760 (_ (error "Unsupported time unit"))))
8761 (nmin 1)
8762 (nmax n)
8763 (n-no-remove -1)
8764 (idprop (org-entry-get nil "ID")))
8765 (when (and doshift
8766 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8767 template))
8768 (delete-region beg end)
8769 (setq end beg)
8770 (setq nmin 0)
8771 (setq nmax (1+ nmax))
8772 (setq n-no-remove nmax))
8773 (goto-char end)
8774 (cl-loop for n from nmin to nmax do
8775 (insert
8776 ;; Prepare clone.
8777 (with-temp-buffer
8778 (insert template)
8779 (org-mode)
8780 (goto-char (point-min))
8781 (org-show-subtree)
8782 (and idprop (if org-clone-delete-id
8783 (org-entry-delete nil "ID")
8784 (org-id-get-create t)))
8785 (unless (= n 0)
8786 (while (re-search-forward org-clock-line-re nil t)
8787 (delete-region (line-beginning-position)
8788 (line-beginning-position 2)))
8789 (goto-char (point-min))
8790 (while (re-search-forward org-drawer-regexp nil t)
8791 (org-remove-empty-drawer-at (point))))
8792 (goto-char (point-min))
8793 (when doshift
8794 (while (re-search-forward org-ts-regexp-both nil t)
8795 (org-timestamp-change (* n shift-n) shift-what))
8796 (unless (= n n-no-remove)
8797 (goto-char (point-min))
8798 (while (re-search-forward org-ts-regexp nil t)
8799 (save-excursion
8800 (goto-char (match-beginning 0))
8801 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8802 (delete-region (match-beginning 1) (match-end 1)))))))
8803 (buffer-string)))))
8804 (goto-char beg)))
8806 ;;; Outline Sorting
8808 (defun org-sort (&optional with-case)
8809 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8810 Optional argument WITH-CASE means sort case-sensitively."
8811 (interactive "P")
8812 (org-call-with-arg
8813 (cond ((org-at-table-p) #'org-table-sort-lines)
8814 ((org-at-item-p) #'org-sort-list)
8815 (t #'org-sort-entries))
8816 with-case))
8818 (defun org-sort-remove-invisible (s)
8819 "Remove invisible part of links and emphasis markers from string S."
8820 (remove-text-properties 0 (length s) org-rm-props s)
8821 (replace-regexp-in-string
8822 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8823 (replace-regexp-in-string
8824 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8825 (org-link-display-format s)
8826 t t) t t))
8828 (defvar org-priority-regexp) ; defined later in the file
8830 (defvar org-after-sorting-entries-or-items-hook nil
8831 "Hook that is run after a bunch of entries or items have been sorted.
8832 When children are sorted, the cursor is in the parent line when this
8833 hook gets called. When a region or a plain list is sorted, the cursor
8834 will be in the first entry of the sorted region/list.")
8836 (defun org-sort-entries
8837 (&optional with-case sorting-type getkey-func compare-func property
8838 interactive?)
8839 "Sort entries on a certain level of an outline tree.
8840 If there is an active region, the entries in the region are sorted.
8841 Else, if the cursor is before the first entry, sort the top-level items.
8842 Else, the children of the entry at point are sorted.
8844 Sorting can be alphabetically, numerically, by date/time as given by
8845 a time stamp, by a property, by priority order, or by a custom function.
8847 The command prompts for the sorting type unless it has been given to the
8848 function through the SORTING-TYPE argument, which needs to be a character,
8849 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8850 the precise meaning of each character:
8852 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8853 c By creation time, which is assumed to be the first inactive time stamp
8854 at the beginning of a line.
8855 d By deadline date/time.
8856 k By clocking time.
8857 n Numerically, by converting the beginning of the entry/item to a number.
8858 o By order of TODO keywords.
8859 p By priority according to the cookie.
8860 r By the value of a property.
8861 s By scheduled date/time.
8862 t By date/time, either the first active time stamp in the entry, or, if
8863 none exist, by the first inactive one.
8865 Capital letters will reverse the sort order.
8867 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8868 called with point at the beginning of the record. It must return a
8869 value that is compatible with COMPARE-FUNC, the function used to
8870 compare entries.
8872 Comparing entries ignores case by default. However, with an optional argument
8873 WITH-CASE, the sorting considers case as well.
8875 Sorting is done against the visible part of the headlines, it ignores hidden
8876 links.
8878 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8880 A non-nil value for INTERACTIVE? is used to signal that this
8881 function is being called interactively."
8882 (interactive (list current-prefix-arg nil nil nil nil t))
8883 (let ((case-func (if with-case 'identity 'downcase))
8884 (cmstr
8885 ;; The clock marker is lost when using `sort-subr', let's
8886 ;; store the clocking string.
8887 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8888 (save-excursion
8889 (goto-char org-clock-marker)
8890 (buffer-substring-no-properties (line-beginning-position)
8891 (point)))))
8892 start beg end stars re re2
8893 txt what tmp)
8894 ;; Find beginning and end of region to sort
8895 (cond
8896 ((org-region-active-p)
8897 ;; we will sort the region
8898 (setq end (region-end)
8899 what "region")
8900 (goto-char (region-beginning))
8901 (unless (org-at-heading-p) (outline-next-heading))
8902 (setq start (point)))
8903 ((or (org-at-heading-p)
8904 (ignore-errors (progn (org-back-to-heading) t)))
8905 ;; we will sort the children of the current headline
8906 (org-back-to-heading)
8907 (setq start (point)
8908 end (progn (org-end-of-subtree t t)
8909 (or (bolp) (insert "\n"))
8910 (when (>= (org-back-over-empty-lines) 1)
8911 (forward-line 1))
8912 (point))
8913 what "children")
8914 (goto-char start)
8915 (outline-show-subtree)
8916 (outline-next-heading))
8918 ;; we will sort the top-level entries in this file
8919 (goto-char (point-min))
8920 (or (org-at-heading-p) (outline-next-heading))
8921 (setq start (point))
8922 (goto-char (point-max))
8923 (beginning-of-line 1)
8924 (when (looking-at ".*?\\S-")
8925 ;; File ends in a non-white line
8926 (end-of-line 1)
8927 (insert "\n"))
8928 (setq end (point-max))
8929 (setq what "top-level")
8930 (goto-char start)
8931 (outline-show-all)))
8933 (setq beg (point))
8934 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8936 (looking-at "\\(\\*+\\)")
8937 (setq stars (match-string 1)
8938 re (concat "^" (regexp-quote stars) " +")
8939 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8940 txt (buffer-substring beg end))
8941 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8942 (when (and (not (equal stars "*")) (string-match re2 txt))
8943 (user-error "Region to sort contains a level above the first entry"))
8945 (unless sorting-type
8946 (message
8947 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8948 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8949 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8950 what)
8951 (setq sorting-type (read-char-exclusive)))
8953 (unless getkey-func
8954 (and (= (downcase sorting-type) ?f)
8955 (setq getkey-func
8956 (or (and interactive?
8957 (org-read-function
8958 "Function for extracting keys: "))
8959 (error "Missing key extractor")))))
8961 (and (= (downcase sorting-type) ?r)
8962 (not property)
8963 (setq property
8964 (completing-read "Property: "
8965 (mapcar #'list (org-buffer-property-keys t))
8966 nil t)))
8968 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8969 (message "Sorting entries...")
8971 (save-restriction
8972 (narrow-to-region start end)
8973 (let ((dcst (downcase sorting-type))
8974 (case-fold-search nil)
8975 (now (current-time)))
8976 (sort-subr
8977 (/= dcst sorting-type)
8978 ;; This function moves to the beginning character of the "record" to
8979 ;; be sorted.
8980 (lambda nil
8981 (if (re-search-forward re nil t)
8982 (goto-char (match-beginning 0))
8983 (goto-char (point-max))))
8984 ;; This function moves to the last character of the "record" being
8985 ;; sorted.
8986 (lambda nil
8987 (save-match-data
8988 (condition-case nil
8989 (outline-forward-same-level 1)
8990 (error
8991 (goto-char (point-max))))))
8992 ;; This function returns the value that gets sorted against.
8993 (lambda nil
8994 (cond
8995 ((= dcst ?n)
8996 (if (looking-at org-complex-heading-regexp)
8997 (string-to-number (org-sort-remove-invisible (match-string 4)))
8998 nil))
8999 ((= dcst ?a)
9000 (if (looking-at org-complex-heading-regexp)
9001 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9002 nil))
9003 ((= dcst ?k)
9004 (or (get-text-property (point) :org-clock-minutes) 0))
9005 ((= dcst ?t)
9006 (let ((end (save-excursion (outline-next-heading) (point))))
9007 (if (or (re-search-forward org-ts-regexp end t)
9008 (re-search-forward org-ts-regexp-both end t))
9009 (org-time-string-to-seconds (match-string 0))
9010 (float-time now))))
9011 ((= dcst ?c)
9012 (let ((end (save-excursion (outline-next-heading) (point))))
9013 (if (re-search-forward
9014 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9015 end t)
9016 (org-time-string-to-seconds (match-string 0))
9017 (float-time now))))
9018 ((= dcst ?s)
9019 (let ((end (save-excursion (outline-next-heading) (point))))
9020 (if (re-search-forward org-scheduled-time-regexp end t)
9021 (org-time-string-to-seconds (match-string 1))
9022 (float-time now))))
9023 ((= dcst ?d)
9024 (let ((end (save-excursion (outline-next-heading) (point))))
9025 (if (re-search-forward org-deadline-time-regexp end t)
9026 (org-time-string-to-seconds (match-string 1))
9027 (float-time now))))
9028 ((= dcst ?p)
9029 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9030 (string-to-char (match-string 2))
9031 org-default-priority))
9032 ((= dcst ?r)
9033 (or (org-entry-get nil property) ""))
9034 ((= dcst ?o)
9035 (when (looking-at org-complex-heading-regexp)
9036 (let* ((m (match-string 2))
9037 (s (if (member m org-done-keywords) '- '+)))
9038 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9039 ((= dcst ?f)
9040 (if getkey-func
9041 (progn
9042 (setq tmp (funcall getkey-func))
9043 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9044 tmp)
9045 (error "Invalid key function `%s'" getkey-func)))
9046 (t (error "Invalid sorting type `%c'" sorting-type))))
9048 (cond
9049 ((= dcst ?a) 'string<)
9050 ((= dcst ?f)
9051 (or compare-func
9052 (and interactive?
9053 (org-read-function
9054 (concat "Function for comparing keys "
9055 "(empty for default `sort-subr' predicate): ")
9056 'allow-empty))))
9057 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9058 (run-hooks 'org-after-sorting-entries-or-items-hook)
9059 ;; Reset the clock marker if needed
9060 (when cmstr
9061 (save-excursion
9062 (goto-char start)
9063 (search-forward cmstr nil t)
9064 (move-marker org-clock-marker (point))))
9065 (message "Sorting entries...done")))
9067 ;;; The orgstruct minor mode
9069 ;; Define a minor mode which can be used in other modes in order to
9070 ;; integrate the Org mode structure editing commands.
9072 ;; This is really a hack, because the Org mode structure commands use
9073 ;; keys which normally belong to the major mode. Here is how it
9074 ;; works: The minor mode defines all the keys necessary to operate the
9075 ;; structure commands, but wraps the commands into a function which
9076 ;; tests if the cursor is currently at a headline or a plain list
9077 ;; item. If that is the case, the structure command is used,
9078 ;; temporarily setting many Org mode variables like regular
9079 ;; expressions for filling etc. However, when any of those keys is
9080 ;; used at a different location, function uses `key-binding' to look
9081 ;; up if the key has an associated command in another currently active
9082 ;; keymap (minor modes, major mode, global), and executes that
9083 ;; command. There might be problems if any of the keys is otherwise
9084 ;; used as a prefix key.
9086 (defcustom orgstruct-heading-prefix-regexp ""
9087 "Regexp that matches the custom prefix of Org headlines in
9088 orgstruct(++)-mode."
9089 :group 'org
9090 :version "24.4"
9091 :package-version '(Org . "8.3")
9092 :type 'regexp)
9093 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9095 (defcustom orgstruct-setup-hook nil
9096 "Hook run after orgstruct-mode-map is filled."
9097 :group 'org
9098 :version "24.4"
9099 :package-version '(Org . "8.0")
9100 :type 'hook)
9102 (defvar orgstruct-initialized nil)
9104 (defvar org-local-vars nil
9105 "List of local variables, for use by `orgstruct-mode'.")
9107 ;;;###autoload
9108 (define-minor-mode orgstruct-mode
9109 "Toggle the minor mode `orgstruct-mode'.
9110 This mode is for using Org mode structure commands in other
9111 modes. The following keys behave as if Org mode were active, if
9112 the cursor is on a headline, or on a plain list item (both as
9113 defined by Org mode)."
9114 nil " OrgStruct" (make-sparse-keymap)
9115 (funcall (if orgstruct-mode
9116 'add-to-invisibility-spec
9117 'remove-from-invisibility-spec)
9118 '(outline . t))
9119 (when orgstruct-mode
9120 (org-load-modules-maybe)
9121 (unless orgstruct-initialized
9122 (orgstruct-setup)
9123 (setq orgstruct-initialized t))))
9125 ;;;###autoload
9126 (defun turn-on-orgstruct ()
9127 "Unconditionally turn on `orgstruct-mode'."
9128 (orgstruct-mode 1))
9130 (defvar-local orgstruct-is-++ nil
9131 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9132 (defvar-local org-fb-vars nil)
9133 (defun orgstruct++-mode (&optional arg)
9134 "Toggle `orgstruct-mode', the enhanced version of it.
9135 In addition to setting orgstruct-mode, this also exports all
9136 indentation and autofilling variables from Org mode into the
9137 buffer. It will also recognize item context in multiline items."
9138 (interactive "P")
9139 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9140 (if (< arg 1)
9141 (progn (orgstruct-mode -1)
9142 (dolist (v org-fb-vars)
9143 (set (make-local-variable (car v))
9144 (if (eq (car-safe (cadr v)) 'quote)
9145 (cl-cadadr v)
9146 (nth 1 v)))))
9147 (orgstruct-mode 1)
9148 (setq org-fb-vars nil)
9149 (unless org-local-vars
9150 (setq org-local-vars (org-get-local-variables)))
9151 (let (var val)
9152 (dolist (x org-local-vars)
9153 (when (string-match
9154 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9155 \\|fill-prefix\\|indent-\\)"
9156 (symbol-name (car x)))
9157 (setq var (car x) val (nth 1 x))
9158 (push (list var `(quote ,(eval var))) org-fb-vars)
9159 (set (make-local-variable var)
9160 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9161 (setq-local orgstruct-is-++ t))))
9163 ;;;###autoload
9164 (defun turn-on-orgstruct++ ()
9165 "Unconditionally turn on `orgstruct++-mode'."
9166 (orgstruct++-mode 1))
9168 (defun orgstruct-error ()
9169 "Error when there is no default binding for a structure key."
9170 (interactive)
9171 (funcall (if (fboundp 'user-error)
9172 'user-error
9173 'error)
9174 "This key has no function outside structure elements"))
9176 (defun orgstruct-setup ()
9177 "Setup orgstruct keymap."
9178 (dolist (cell '((org-demote . t)
9179 (org-metaleft . t)
9180 (org-metaright . t)
9181 (org-promote . t)
9182 (org-shiftmetaleft . t)
9183 (org-shiftmetaright . t)
9184 org-backward-element
9185 org-backward-heading-same-level
9186 org-ctrl-c-ret
9187 org-ctrl-c-minus
9188 org-ctrl-c-star
9189 org-cycle
9190 org-force-cycle-archived
9191 org-forward-heading-same-level
9192 org-insert-heading
9193 org-insert-heading-respect-content
9194 org-kill-note-or-show-branches
9195 org-mark-subtree
9196 org-meta-return
9197 org-metadown
9198 org-metaup
9199 org-narrow-to-subtree
9200 org-promote-subtree
9201 org-reveal
9202 org-shiftdown
9203 org-shiftleft
9204 org-shiftmetadown
9205 org-shiftmetaup
9206 org-shiftright
9207 org-shifttab
9208 org-shifttab
9209 org-shiftup
9210 org-show-children
9211 org-show-subtree
9212 org-sort
9213 org-up-element
9214 outline-demote
9215 outline-next-visible-heading
9216 outline-previous-visible-heading
9217 outline-promote
9218 outline-up-heading))
9219 (let ((f (or (car-safe cell) cell))
9220 (disable-when-heading-prefix (cdr-safe cell)))
9221 (when (fboundp f)
9222 (let ((new-bindings))
9223 (dolist (binding (nconc (where-is-internal f org-mode-map)
9224 (where-is-internal f outline-mode-map)))
9225 (push binding new-bindings)
9226 ;; TODO use local-function-key-map
9227 (dolist (rep '(("<tab>" . "TAB")
9228 ("<return>" . "RET")
9229 ("<escape>" . "ESC")
9230 ("<delete>" . "DEL")))
9231 (setq binding (read-kbd-macro
9232 (let ((case-fold-search))
9233 (replace-regexp-in-string
9234 (regexp-quote (cdr rep))
9235 (car rep)
9236 (key-description binding)))))
9237 (cl-pushnew binding new-bindings :test 'equal)))
9238 (dolist (binding new-bindings)
9239 (let ((key (lookup-key orgstruct-mode-map binding)))
9240 (when (or (not key) (numberp key))
9241 (ignore-errors
9242 (org-defkey orgstruct-mode-map
9243 binding
9244 (orgstruct-make-binding
9245 f binding disable-when-heading-prefix))))))))))
9246 (run-hooks 'orgstruct-setup-hook))
9248 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9249 "Create a function for binding in the structure minor mode.
9250 FUN is the command to call inside a table. KEY is the key that
9251 should be checked in for a command to execute outside of tables.
9252 Non-nil `disable-when-heading-prefix' means to disable the command
9253 if `orgstruct-heading-prefix-regexp' is not empty."
9254 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9255 (let ((nname name)
9256 (i 0))
9257 (while (fboundp (intern nname))
9258 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9259 (setq name (intern nname)))
9260 (eval
9261 (let ((bindings '((org-heading-regexp
9262 (concat "^"
9263 orgstruct-heading-prefix-regexp
9264 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9265 (org-outline-regexp
9266 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9267 (org-outline-regexp-bol
9268 (concat "^" org-outline-regexp))
9269 (outline-regexp org-outline-regexp)
9270 (outline-heading-end-regexp "\n")
9271 (outline-level 'org-outline-level)
9272 (outline-heading-alist))))
9273 `(defun ,name (arg)
9274 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9275 "Outside of structure, run the binding of `"
9276 (key-description key) "'."
9277 (when disable-when-heading-prefix
9278 (concat
9279 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9280 "back to the default binding due to limitations of Org's implementation of\n"
9281 "`" (symbol-name fun) "'.")))
9282 (interactive "p")
9283 (let* ((disable
9284 ,(and disable-when-heading-prefix
9285 '(not (string= orgstruct-heading-prefix-regexp ""))))
9286 (fallback
9287 (or disable
9288 (not
9289 (let* ,bindings
9290 (org-context-p 'headline 'item
9291 ,(when (memq fun
9292 '(org-insert-heading
9293 org-insert-heading-respect-content
9294 org-meta-return))
9295 '(when orgstruct-is-++
9296 'item-body))))))))
9297 (if fallback
9298 (let* ((orgstruct-mode)
9299 (binding
9300 (let ((key ,key))
9301 (catch 'exit
9302 (dolist
9303 (rep
9304 '(nil
9305 ("<\\([^>]*\\)tab>" . "\\1TAB")
9306 ("<\\([^>]*\\)return>" . "\\1RET")
9307 ("<\\([^>]*\\)escape>" . "\\1ESC")
9308 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9309 nil)
9310 (when rep
9311 (setq key (read-kbd-macro
9312 (let ((case-fold-search))
9313 (replace-regexp-in-string
9314 (car rep)
9315 (cdr rep)
9316 (key-description key))))))
9317 (when (key-binding key)
9318 (throw 'exit (key-binding key))))))))
9319 (if (keymapp binding)
9320 (org-set-transient-map binding)
9321 (let ((func (or binding
9322 (unless disable
9323 'orgstruct-error))))
9324 (when func
9325 (call-interactively func)))))
9326 (org-run-like-in-org-mode
9327 (lambda ()
9328 (interactive)
9329 (let* ,bindings
9330 (call-interactively ',fun)))))))))
9331 name))
9333 (defun org-contextualize-keys (alist contexts)
9334 "Return valid elements in ALIST depending on CONTEXTS.
9336 `org-agenda-custom-commands' or `org-capture-templates' are the
9337 values used for ALIST, and `org-agenda-custom-commands-contexts'
9338 or `org-capture-templates-contexts' are the associated contexts
9339 definitions."
9340 (let ((contexts
9341 ;; normalize contexts
9342 (mapcar
9343 (lambda(c) (cond ((listp (cadr c))
9344 (list (car c) (car c) (nth 1 c)))
9345 ((string= "" (cadr c))
9346 (list (car c) (car c) (nth 2 c)))
9347 (t c)))
9348 contexts))
9349 (a alist) r s)
9350 ;; loop over all commands or templates
9351 (dolist (c a)
9352 (let (vrules repl)
9353 (cond
9354 ((not (assoc (car c) contexts))
9355 (push c r))
9356 ((and (assoc (car c) contexts)
9357 (setq vrules (org-contextualize-validate-key
9358 (car c) contexts)))
9359 (mapc (lambda (vr)
9360 (unless (equal (car vr) (cadr vr))
9361 (setq repl vr)))
9362 vrules)
9363 (if (not repl) (push c r)
9364 (push (cadr repl) s)
9365 (push
9366 (cons (car c)
9367 (cdr (or (assoc (cadr repl) alist)
9368 (error "Undefined key `%s' as contextual replacement for `%s'"
9369 (cadr repl) (car c)))))
9370 r))))))
9371 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9372 (delq
9374 (delete-dups
9375 (mapcar (lambda (x)
9376 (let ((tpl (car x)))
9377 (unless (delq
9379 (mapcar (lambda (y)
9380 (equal y tpl))
9382 x)))
9383 (reverse r))))))
9385 (defun org-contextualize-validate-key (key contexts)
9386 "Check CONTEXTS for agenda or capture KEY."
9387 (let (res)
9388 (dolist (r contexts)
9389 (dolist (rr (car (last r)))
9390 (when
9391 (and (equal key (car r))
9392 (if (functionp rr) (funcall rr)
9393 (or (and (eq (car rr) 'in-file)
9394 (buffer-file-name)
9395 (string-match (cdr rr) (buffer-file-name)))
9396 (and (eq (car rr) 'in-mode)
9397 (string-match (cdr rr) (symbol-name major-mode)))
9398 (and (eq (car rr) 'in-buffer)
9399 (string-match (cdr rr) (buffer-name)))
9400 (when (and (eq (car rr) 'not-in-file)
9401 (buffer-file-name))
9402 (not (string-match (cdr rr) (buffer-file-name))))
9403 (when (eq (car rr) 'not-in-mode)
9404 (not (string-match (cdr rr) (symbol-name major-mode))))
9405 (when (eq (car rr) 'not-in-buffer)
9406 (not (string-match (cdr rr) (buffer-name)))))))
9407 (push r res))))
9408 (delete-dups (delq nil res))))
9410 (defun org-context-p (&rest contexts)
9411 "Check if local context is any of CONTEXTS.
9412 Possible values in the list of contexts are `table', `headline', and `item'."
9413 (let ((pos (point)))
9414 (goto-char (point-at-bol))
9415 (prog1 (or (and (memq 'table contexts)
9416 (looking-at "[ \t]*|"))
9417 (and (memq 'headline contexts)
9418 (looking-at org-outline-regexp))
9419 (and (memq 'item contexts)
9420 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9421 (and (memq 'item-body contexts)
9422 (org-in-item-p)))
9423 (goto-char pos))))
9425 (defconst org-unique-local-variables
9426 '(org-element--cache
9427 org-element--cache-objects
9428 org-element--cache-sync-keys
9429 org-element--cache-sync-requests
9430 org-element--cache-sync-timer)
9431 "List of local variables that cannot be transferred to another buffer.")
9433 (defun org-get-local-variables ()
9434 "Return a list of all local variables in an Org mode buffer."
9435 (delq nil
9436 (mapcar
9437 (lambda (x)
9438 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9439 (name (car binding)))
9440 (and (not (get name 'org-state))
9441 (not (memq name org-unique-local-variables))
9442 (string-match-p
9443 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9444 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9445 (symbol-name name))
9446 binding)))
9447 (with-temp-buffer
9448 (org-mode)
9449 (buffer-local-variables)))))
9451 (defun org-clone-local-variables (from-buffer &optional regexp)
9452 "Clone local variables from FROM-BUFFER.
9453 Optional argument REGEXP selects variables to clone."
9454 (dolist (pair (buffer-local-variables from-buffer))
9455 (pcase pair
9456 (`(,name . ,value) ;ignore unbound variables
9457 (when (and (not (memq name org-unique-local-variables))
9458 (or (null regexp) (string-match-p regexp (symbol-name name))))
9459 (set (make-local-variable name) value))))))
9461 ;;;###autoload
9462 (defun org-run-like-in-org-mode (cmd)
9463 "Run a command, pretending that the current buffer is in Org mode.
9464 This will temporarily bind local variables that are typically bound in
9465 Org mode to the values they have in Org mode, and then interactively
9466 call CMD."
9467 (org-load-modules-maybe)
9468 (unless org-local-vars
9469 (setq org-local-vars (org-get-local-variables)))
9470 (let (binds)
9471 (dolist (var org-local-vars)
9472 (when (or (not (boundp (car var)))
9473 (eq (symbol-value (car var))
9474 (default-value (car var))))
9475 (push (list (car var) `(quote ,(cadr var))) binds)))
9476 (eval `(let ,binds
9477 (call-interactively (quote ,cmd))))))
9479 (defun org-get-category (&optional pos force-refresh)
9480 "Get the category applying to position POS."
9481 (save-match-data
9482 (when force-refresh (org-refresh-category-properties))
9483 (let ((pos (or pos (point))))
9484 (or (get-text-property pos 'org-category)
9485 (progn (org-refresh-category-properties)
9486 (get-text-property pos 'org-category))))))
9488 ;;; Refresh properties
9490 (defun org-refresh-properties (dprop tprop)
9491 "Refresh buffer text properties.
9492 DPROP is the drawer property and TPROP is either the
9493 corresponding text property to set, or an alist with each element
9494 being a text property (as a symbol) and a function to apply to
9495 the value of the drawer property."
9496 (let* ((case-fold-search t)
9497 (inhibit-read-only t)
9498 (inherit? (org-property-inherit-p dprop))
9499 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9500 (global (and inherit? (org--property-global-value dprop nil))))
9501 (org-with-silent-modifications
9502 (org-with-point-at 1
9503 ;; Set global values (e.g., values defined through
9504 ;; "#+PROPERTY:" keywords) to the whole buffer.
9505 (when global (put-text-property (point-min) (point-max) tprop global))
9506 ;; Set local values.
9507 (while (re-search-forward property-re nil t)
9508 (when (org-at-property-p)
9509 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9510 (outline-next-heading))))))
9512 (defun org-refresh-property (tprop p &optional inherit)
9513 "Refresh the buffer text property TPROP from the drawer property P.
9514 The refresh happens only for the current headline, or the whole
9515 sub-tree if optional argument INHERIT is non-nil."
9516 (unless (org-before-first-heading-p)
9517 (save-excursion
9518 (org-back-to-heading t)
9519 (let ((start (point))
9520 (end (save-excursion
9521 (if inherit (org-end-of-subtree t t)
9522 (or (outline-next-heading) (point-max))))))
9523 (if (symbolp tprop)
9524 ;; TPROP is a text property symbol.
9525 (put-text-property start end tprop p)
9526 ;; TPROP is an alist with (property . function) elements.
9527 (pcase-dolist (`(,prop . ,f) tprop)
9528 (put-text-property start end prop (funcall f p))))))))
9530 (defun org-refresh-category-properties ()
9531 "Refresh category text properties in the buffer."
9532 (let ((case-fold-search t)
9533 (inhibit-read-only t)
9534 (default-category
9535 (cond ((null org-category)
9536 (if buffer-file-name
9537 (file-name-sans-extension
9538 (file-name-nondirectory buffer-file-name))
9539 "???"))
9540 ((symbolp org-category) (symbol-name org-category))
9541 (t org-category))))
9542 (org-with-silent-modifications
9543 (org-with-wide-buffer
9544 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9545 ;; This is the default category for the buffer. If none is
9546 ;; found, fall-back to `org-category' or buffer file name.
9547 (put-text-property
9548 (point-min) (point-max)
9549 'org-category
9550 (catch 'buffer-category
9551 (goto-char (point-max))
9552 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9553 (let ((element (org-element-at-point)))
9554 (when (eq (org-element-type element) 'keyword)
9555 (throw 'buffer-category
9556 (org-element-property :value element)))))
9557 default-category))
9558 ;; Set sub-tree specific categories.
9559 (goto-char (point-min))
9560 (let ((regexp (org-re-property "CATEGORY")))
9561 (while (re-search-forward regexp nil t)
9562 (let ((value (match-string-no-properties 3)))
9563 (when (org-at-property-p)
9564 (put-text-property
9565 (save-excursion (org-back-to-heading t) (point))
9566 (save-excursion (org-end-of-subtree t t) (point))
9567 'org-category
9568 value)))))))))
9570 (defun org-refresh-stats-properties ()
9571 "Refresh stats text properties in the buffer."
9572 (org-with-silent-modifications
9573 (org-with-point-at 1
9574 (let ((regexp (concat org-outline-regexp-bol
9575 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9576 (while (re-search-forward regexp nil t)
9577 (let* ((numerator (string-to-number (match-string 1)))
9578 (denominator (and (match-end 2)
9579 (string-to-number (match-string 2))))
9580 (stats (cond ((not denominator) numerator) ;percent
9581 ((= denominator 0) 0)
9582 (t (/ (* numerator 100) denominator)))))
9583 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9584 'org-stats stats)))))))
9586 (defun org-refresh-effort-properties ()
9587 "Refresh effort properties"
9588 (org-refresh-properties
9589 org-effort-property
9590 '((effort . identity)
9591 (effort-minutes . org-duration-to-minutes))))
9593 ;;;; Link Stuff
9595 ;;; Link abbreviations
9597 (defun org-link-expand-abbrev (link)
9598 "Apply replacements as defined in `org-link-abbrev-alist'."
9599 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9600 (let* ((key (match-string 1 link))
9601 (as (or (assoc key org-link-abbrev-alist-local)
9602 (assoc key org-link-abbrev-alist)))
9603 (tag (and (match-end 2) (match-string 3 link)))
9604 rpl)
9605 (if (not as)
9606 link
9607 (setq rpl (cdr as))
9608 (cond
9609 ((symbolp rpl) (funcall rpl tag))
9610 ((string-match "%(\\([^)]+\\))" rpl)
9611 (replace-match
9612 (save-match-data
9613 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9614 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9615 ((string-match "%h" rpl)
9616 (replace-match (url-hexify-string (or tag "")) t t rpl))
9617 (t (concat rpl tag)))))
9618 link))
9620 ;;; Storing and inserting links
9622 (defvar org-insert-link-history nil
9623 "Minibuffer history for links inserted with `org-insert-link'.")
9625 (defvar org-stored-links nil
9626 "Contains the links stored with `org-store-link'.")
9628 (defvar org-store-link-plist nil
9629 "Plist with info about the most recently link created with `org-store-link'.")
9631 (defun org-store-link-functions ()
9632 "Return a list of functions that are called to create and store a link.
9633 The functions defined in the :store property of
9634 `org-link-parameters'.
9636 Each function will be called in turn until one returns a non-nil
9637 value. Each function should check if it is responsible for
9638 creating this link (for example by looking at the major mode).
9639 If not, it must exit and return nil. If yes, it should return
9640 a non-nil value after calling `org-store-link-props' with a list
9641 of properties and values. Special properties are:
9643 :type The link prefix, like \"http\". This must be given.
9644 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9645 This is obligatory as well.
9646 :description Optional default description for the second pair
9647 of brackets in an Org mode link. The user can still change
9648 this when inserting this link into an Org mode buffer.
9650 In addition to these, any additional properties can be specified
9651 and then used in capture templates."
9652 (cl-loop for link in org-link-parameters
9653 with store-func
9654 do (setq store-func (org-link-get-parameter (car link) :store))
9655 if store-func
9656 collect store-func))
9658 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9659 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9661 ;;;###autoload
9662 (defun org-store-link (arg)
9663 "Store an org-link to the current location.
9664 \\<org-mode-map>
9665 This link is added to `org-stored-links' and can later be inserted
9666 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9668 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9669 A single
9670 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9671 `org-gnus-prefer-web-links' for links to Usenet articles.
9673 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9674 skipping storing functions that are not
9675 part of Org core.
9677 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9678 prefix ARG forces storing a link for each line in the
9679 active region."
9680 (interactive "P")
9681 (org-load-modules-maybe)
9682 (if (and (equal arg '(64)) (org-region-active-p))
9683 (save-excursion
9684 (let ((end (region-end)))
9685 (goto-char (region-beginning))
9686 (set-mark (point))
9687 (while (< (point-at-eol) end)
9688 (move-end-of-line 1) (activate-mark)
9689 (let (current-prefix-arg)
9690 (call-interactively 'org-store-link))
9691 (move-beginning-of-line 2)
9692 (set-mark (point)))))
9693 (setq org-store-link-plist nil)
9694 (let (link cpltxt desc description search
9695 txt custom-id agenda-link sfuns sfunsn)
9696 (cond
9698 ;; Store a link using an external link type
9699 ((and (not (equal arg '(16)))
9700 (setq sfuns
9701 (delq
9702 nil (mapcar (lambda (f)
9703 (let (fs) (if (funcall f) (push f fs))))
9704 (org-store-link-functions)))
9705 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9706 (or (and (cdr sfuns)
9707 (funcall (intern
9708 (completing-read
9709 "Which function for creating the link? "
9710 sfunsn nil t (car sfunsn)))))
9711 (funcall (caar sfuns)))
9712 (setq link (plist-get org-store-link-plist :link)
9713 desc (or (plist-get org-store-link-plist
9714 :description)
9715 link))))
9717 ;; Store a link from a source code buffer.
9718 ((org-src-edit-buffer-p)
9719 (let ((coderef-format (org-src-coderef-format)))
9720 (cond ((save-excursion
9721 (beginning-of-line)
9722 (looking-at (org-src-coderef-regexp coderef-format)))
9723 (setq link (format "(%s)" (match-string-no-properties 3))))
9724 ((called-interactively-p 'any)
9725 (let ((label (read-string "Code line label: ")))
9726 (end-of-line)
9727 (setq link (format coderef-format label))
9728 (let ((gc (- 79 (length link))))
9729 (if (< (current-column) gc)
9730 (org-move-to-column gc t)
9731 (insert " ")))
9732 (insert link)
9733 (setq link (concat "(" label ")"))
9734 (setq desc nil)))
9735 (t (setq link nil)))))
9737 ;; We are in the agenda, link to referenced location
9738 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9739 (let ((m (or (get-text-property (point) 'org-hd-marker)
9740 (get-text-property (point) 'org-marker))))
9741 (when m
9742 (org-with-point-at m
9743 (setq agenda-link
9744 (if (called-interactively-p 'any)
9745 (call-interactively 'org-store-link)
9746 (org-store-link nil)))))))
9748 ((eq major-mode 'calendar-mode)
9749 (let ((cd (calendar-cursor-to-date)))
9750 (setq link
9751 (format-time-string
9752 (car org-time-stamp-formats)
9753 (apply 'encode-time
9754 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9755 nil nil nil))))
9756 (org-store-link-props :type "calendar" :date cd)))
9758 ((eq major-mode 'help-mode)
9759 (setq link (concat "help:" (save-excursion
9760 (goto-char (point-min))
9761 (looking-at "^[^ ]+")
9762 (match-string 0))))
9763 (org-store-link-props :type "help"))
9765 ((eq major-mode 'w3-mode)
9766 (setq cpltxt (if (and (buffer-name)
9767 (not (string-match "Untitled" (buffer-name))))
9768 (buffer-name)
9769 (url-view-url t))
9770 link (url-view-url t))
9771 (org-store-link-props :type "w3" :url (url-view-url t)))
9773 ((eq major-mode 'image-mode)
9774 (setq cpltxt (concat "file:"
9775 (abbreviate-file-name buffer-file-name))
9776 link cpltxt)
9777 (org-store-link-props :type "image" :file buffer-file-name))
9779 ;; In dired, store a link to the file of the current line
9780 ((derived-mode-p 'dired-mode)
9781 (let ((file (dired-get-filename nil t)))
9782 (setq file (if file
9783 (abbreviate-file-name
9784 (expand-file-name (dired-get-filename nil t)))
9785 ;; otherwise, no file so use current directory.
9786 default-directory))
9787 (setq cpltxt (concat "file:" file)
9788 link cpltxt)))
9790 ((setq search (run-hook-with-args-until-success
9791 'org-create-file-search-functions))
9792 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9793 "::" search))
9794 (setq cpltxt (or description link)))
9796 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9797 (org-with-limited-levels
9798 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9799 (cond
9800 ;; Store a link using the target at point
9801 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9802 (setq cpltxt
9803 (concat "file:"
9804 (abbreviate-file-name
9805 (buffer-file-name (buffer-base-buffer)))
9806 "::" (match-string 1))
9807 link cpltxt))
9808 ((and (featurep 'org-id)
9809 (or (eq org-id-link-to-org-use-id t)
9810 (and (called-interactively-p 'any)
9811 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9812 (and (eq org-id-link-to-org-use-id
9813 'create-if-interactive-and-no-custom-id)
9814 (not custom-id))))
9815 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9816 ;; Store a link using the ID at point
9817 (setq link (condition-case nil
9818 (prog1 (org-id-store-link)
9819 (setq desc (or (plist-get org-store-link-plist
9820 :description)
9821 "")))
9822 (error
9823 ;; Probably before first headline, link only to file
9824 (concat "file:"
9825 (abbreviate-file-name
9826 (buffer-file-name (buffer-base-buffer))))))))
9828 ;; Just link to current headline
9829 (setq cpltxt (concat "file:"
9830 (abbreviate-file-name
9831 (buffer-file-name (buffer-base-buffer)))))
9832 ;; Add a context search string
9833 (when (org-xor org-context-in-file-links
9834 (equal arg '(4)))
9835 (let* ((element (org-element-at-point))
9836 (name (org-element-property :name element)))
9837 (setq txt (cond
9838 ((org-at-heading-p) nil)
9839 (name)
9840 ((org-region-active-p)
9841 (buffer-substring (region-beginning) (region-end)))))
9842 (when (or (null txt) (string-match "\\S-" txt))
9843 (setq cpltxt
9844 (concat cpltxt "::"
9845 (condition-case nil
9846 (org-make-org-heading-search-string txt)
9847 (error "")))
9848 desc (or name
9849 (nth 4 (ignore-errors (org-heading-components)))
9850 "NONE")))))
9851 (when (string-match "::\\'" cpltxt)
9852 (setq cpltxt (substring cpltxt 0 -2)))
9853 (setq link cpltxt)))))
9855 ((buffer-file-name (buffer-base-buffer))
9856 ;; Just link to this file here.
9857 (setq cpltxt (concat "file:"
9858 (abbreviate-file-name
9859 (buffer-file-name (buffer-base-buffer)))))
9860 ;; Add a context string.
9861 (when (org-xor org-context-in-file-links
9862 (equal arg '(4)))
9863 (setq txt (if (org-region-active-p)
9864 (buffer-substring (region-beginning) (region-end))
9865 (buffer-substring (point-at-bol) (point-at-eol))))
9866 ;; Only use search option if there is some text.
9867 (when (string-match "\\S-" txt)
9868 (setq cpltxt
9869 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9870 desc "NONE")))
9871 (setq link cpltxt))
9873 ((called-interactively-p 'interactive)
9874 (user-error "No method for storing a link from this buffer"))
9876 (t (setq link nil)))
9878 ;; We're done setting link and desc, clean up
9879 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9880 (setq link (or link cpltxt)
9881 desc (or desc cpltxt))
9882 (cond ((not desc))
9883 ((equal desc "NONE") (setq desc nil))
9884 (t (setq desc
9885 (replace-regexp-in-string
9886 org-bracket-link-analytic-regexp
9887 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9888 desc))))
9889 ;; Return the link
9890 (if (not (and (or (called-interactively-p 'any)
9891 executing-kbd-macro)
9892 link))
9893 (or agenda-link (and link (org-make-link-string link desc)))
9894 (push (list link desc) org-stored-links)
9895 (message "Stored: %s" (or desc link))
9896 (when custom-id
9897 (setq link (concat "file:" (abbreviate-file-name
9898 (buffer-file-name)) "::#" custom-id))
9899 (push (list link desc) org-stored-links))
9900 (car org-stored-links)))))
9902 (defun org-store-link-props (&rest plist)
9903 "Store link properties, extract names, addresses and dates."
9904 (let ((x (plist-get plist :from)))
9905 (when x
9906 (let ((adr (mail-extract-address-components x)))
9907 (setq plist (plist-put plist :fromname (car adr)))
9908 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9909 (let ((x (plist-get plist :to)))
9910 (when x
9911 (let ((adr (mail-extract-address-components x)))
9912 (setq plist (plist-put plist :toname (car adr)))
9913 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9914 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9915 (when x
9916 (setq plist (plist-put plist :date-timestamp
9917 (format-time-string
9918 (org-time-stamp-format t) x)))
9919 (setq plist (plist-put plist :date-timestamp-inactive
9920 (format-time-string
9921 (org-time-stamp-format t t) x)))))
9922 (let ((from (plist-get plist :from))
9923 (to (plist-get plist :to)))
9924 (when (and from to org-from-is-user-regexp)
9925 (setq plist
9926 (plist-put plist :fromto
9927 (if (string-match org-from-is-user-regexp from)
9928 (concat "to %t")
9929 (concat "from %f"))))))
9930 (setq org-store-link-plist plist))
9932 (defun org-add-link-props (&rest plist)
9933 "Add these properties to the link property list."
9934 (let (key value)
9935 (while plist
9936 (setq key (pop plist) value (pop plist))
9937 (setq org-store-link-plist
9938 (plist-put org-store-link-plist key value)))))
9940 (defun org-email-link-description (&optional fmt)
9941 "Return the description part of an email link.
9942 This takes information from `org-store-link-plist' and formats it
9943 according to FMT (default from `org-email-link-description-format')."
9944 (setq fmt (or fmt org-email-link-description-format))
9945 (let* ((p org-store-link-plist)
9946 (to (plist-get p :toaddress))
9947 (from (plist-get p :fromaddress))
9948 (table
9949 (list
9950 (cons "%c" (plist-get p :fromto))
9951 (cons "%F" (plist-get p :from))
9952 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9953 (cons "%T" (plist-get p :to))
9954 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9955 (cons "%s" (plist-get p :subject))
9956 (cons "%d" (plist-get p :date))
9957 (cons "%m" (plist-get p :message-id)))))
9958 (when (string-match "%c" fmt)
9959 ;; Check if the user wrote this message
9960 (if (and org-from-is-user-regexp from to
9961 (save-match-data (string-match org-from-is-user-regexp from)))
9962 (setq fmt (replace-match "to %t" t t fmt))
9963 (setq fmt (replace-match "from %f" t t fmt))))
9964 (org-replace-escapes fmt table)))
9966 (defun org-make-org-heading-search-string (&optional string)
9967 "Make search string for the current headline or STRING."
9968 (let ((s (or string
9969 (and (derived-mode-p 'org-mode)
9970 (save-excursion
9971 (org-back-to-heading t)
9972 (org-element-property :raw-value (org-element-at-point))))))
9973 (lines org-context-in-file-links))
9974 (or string (setq s (concat "*" s))) ; Add * for headlines
9975 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9976 (when (and string (integerp lines) (> lines 0))
9977 (let ((slines (org-split-string s "\n")))
9978 (when (< lines (length slines))
9979 (setq s (mapconcat
9980 'identity
9981 (reverse (nthcdr (- (length slines) lines)
9982 (reverse slines))) "\n")))))
9983 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9985 (defun org-make-link-string (link &optional description)
9986 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9987 (unless (org-string-nw-p link) (error "Empty link"))
9988 (let ((uri (cond ((string-match org-link-types-re link)
9989 (concat (match-string 1 link)
9990 (org-link-escape (substring link (match-end 1)))))
9991 ;; For readability, url-encode internal links only
9992 ;; when absolutely needed (i.e, when they contain
9993 ;; square brackets). File links however, are
9994 ;; encoded since, e.g., spaces are significant.
9995 ((or (file-name-absolute-p link)
9996 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9997 (org-link-escape link))
9998 (t link)))
9999 (description
10000 (and (org-string-nw-p description)
10001 ;; Remove brackets from description, as they are fatal.
10002 (replace-regexp-in-string
10003 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10004 (org-trim description)))))
10005 (format "[[%s]%s]"
10007 (if description (format "[%s]" description) ""))))
10009 (defconst org-link-escape-chars
10010 ;;%20 %5B %5D %25
10011 '(?\s ?\[ ?\] ?%)
10012 "List of characters that should be escaped in a link when stored to Org.
10013 This is the list that is used for internal purposes.")
10015 (defun org-link-escape (text &optional table merge)
10016 "Return percent escaped representation of TEXT.
10017 TEXT is a string with the text to escape.
10018 Optional argument TABLE is a list with characters that should be
10019 escaped. When nil, `org-link-escape-chars' is used.
10020 If optional argument MERGE is set, merge TABLE into
10021 `org-link-escape-chars'."
10022 (let ((characters-to-encode
10023 (cond ((null table) org-link-escape-chars)
10024 (merge (append org-link-escape-chars table))
10025 (t table))))
10026 (mapconcat
10027 (lambda (c)
10028 (if (or (memq c characters-to-encode)
10029 (and org-url-hexify-p (or (< c 32) (> c 126))))
10030 (mapconcat (lambda (e) (format "%%%.2X" e))
10031 (or (encode-coding-char c 'utf-8)
10032 (error "Unable to percent escape character: %c" c))
10034 (char-to-string c)))
10035 text "")))
10037 (defun org-link-unescape (str)
10038 "Unhex hexified Unicode parts in string STR.
10039 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10040 reciprocal of `org-link-escape', which see."
10041 (if (org-string-nw-p str)
10042 (replace-regexp-in-string
10043 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10044 str))
10046 (defun org-link-unescape-compound (hex)
10047 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10048 Note: this function also decodes single byte encodings like
10049 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10050 (save-match-data
10051 (let* ((bytes (cdr (split-string hex "%")))
10052 (ret "")
10053 (eat 0)
10054 (sum 0))
10055 (while bytes
10056 (let* ((val (string-to-number (pop bytes) 16))
10057 (shift-xor
10058 (if (= 0 eat)
10059 (cond
10060 ((>= val 252) (cons 6 252))
10061 ((>= val 248) (cons 5 248))
10062 ((>= val 240) (cons 4 240))
10063 ((>= val 224) (cons 3 224))
10064 ((>= val 192) (cons 2 192))
10065 (t (cons 0 0)))
10066 (cons 6 128))))
10067 (when (>= val 192) (setq eat (car shift-xor)))
10068 (setq val (logxor val (cdr shift-xor)))
10069 (setq sum (+ (lsh sum (car shift-xor)) val))
10070 (when (> eat 0) (setq eat (- eat 1)))
10071 (cond
10072 ((= 0 eat) ;multi byte
10073 (setq ret (concat ret (char-to-string sum)))
10074 (setq sum 0))
10075 ((not bytes) ; single byte(s)
10076 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10077 ret)))
10079 (defun org-link-unescape-single-byte-sequence (hex)
10080 "Unhexify hex-encoded single byte character sequences."
10081 (mapconcat (lambda (byte)
10082 (char-to-string (string-to-number byte 16)))
10083 (cdr (split-string hex "%")) ""))
10085 (defun org-xor (a b)
10086 "Exclusive or."
10087 (if a (not b) b))
10089 (defun org-fixup-message-id-for-http (s)
10090 "Replace special characters in a message id, so it can be used in an http query."
10091 (when (string-match "%" s)
10092 (setq s (mapconcat (lambda (c)
10093 (if (eq c ?%)
10094 "%25"
10095 (char-to-string c)))
10096 s "")))
10097 (while (string-match "<" s)
10098 (setq s (replace-match "%3C" t t s)))
10099 (while (string-match ">" s)
10100 (setq s (replace-match "%3E" t t s)))
10101 (while (string-match "@" s)
10102 (setq s (replace-match "%40" t t s)))
10105 (defun org-link-prettify (link)
10106 "Return a human-readable representation of LINK.
10107 The car of LINK must be a raw link.
10108 The cdr of LINK must be either a link description or nil."
10109 (let ((desc (or (cadr link) "<no description>")))
10110 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10111 "<" (car link) ">")))
10113 ;;;###autoload
10114 (defun org-insert-link-global ()
10115 "Insert a link like Org mode does.
10116 This command can be called in any mode to insert a link in Org syntax."
10117 (interactive)
10118 (org-load-modules-maybe)
10119 (org-run-like-in-org-mode 'org-insert-link))
10121 (defun org-insert-all-links (arg &optional pre post)
10122 "Insert all links in `org-stored-links'.
10123 When a universal prefix, do not delete the links from `org-stored-links'.
10124 When `ARG' is a number, insert the last N link(s).
10125 `PRE' and `POST' are optional arguments to define a string to
10126 prepend or to append."
10127 (interactive "P")
10128 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10129 (links (copy-sequence org-stored-links))
10130 (pr (or pre "- "))
10131 (po (or post "\n"))
10132 (cnt 1) l)
10133 (if (null org-stored-links)
10134 (message "No link to insert")
10135 (while (and (or (listp arg) (>= arg cnt))
10136 (setq l (if (listp arg)
10137 (pop links)
10138 (pop org-stored-links))))
10139 (setq cnt (1+ cnt))
10140 (insert pr)
10141 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10142 (insert po)))))
10144 (defun org-insert-last-stored-link (arg)
10145 "Insert the last link stored in `org-stored-links'."
10146 (interactive "p")
10147 (org-insert-all-links arg "" "\n"))
10149 (defun org-link-fontify-links-to-this-file ()
10150 "Fontify links to the current file in `org-stored-links'."
10151 (let ((f (buffer-file-name)) a b)
10152 (setq a (mapcar (lambda(l)
10153 (let ((ll (car l)))
10154 (when (and (string-match "^file:\\(.+\\)::" ll)
10155 (equal f (expand-file-name (match-string 1 ll))))
10156 ll)))
10157 org-stored-links))
10158 (when (featurep 'org-id)
10159 (setq b (mapcar (lambda(l)
10160 (let ((ll (car l)))
10161 (when (and (string-match "^id:\\(.+\\)$" ll)
10162 (equal f (expand-file-name
10163 (or (org-id-find-id-file
10164 (match-string 1 ll)) ""))))
10165 ll)))
10166 org-stored-links)))
10167 (mapcar (lambda(l)
10168 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10169 (delq nil (append a b)))))
10171 (defvar org--links-history nil)
10172 (defun org-insert-link (&optional complete-file link-location default-description)
10173 "Insert a link. At the prompt, enter the link.
10175 Completion can be used to insert any of the link protocol prefixes in use.
10177 The history can be used to select a link previously stored with
10178 `org-store-link'. When the empty string is entered (i.e. if you just
10179 press `RET' at the prompt), the link defaults to the most recently
10180 stored link. As `SPC' triggers completion in the minibuffer, you need to
10181 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10183 You will also be prompted for a description, and if one is given, it will
10184 be displayed in the buffer instead of the link.
10186 If there is already a link at point, this command will allow you to edit
10187 link and description parts.
10189 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10190 file name can be
10191 selected using completion. The path to the file will be relative to the
10192 current directory if the file is in the current directory or a subdirectory.
10193 Otherwise, the link will be the absolute path as completed in the minibuffer
10194 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10195 option `org-link-file-path-type'.
10197 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10198 absolute path even if the file is in
10199 the current directory or below.
10201 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10202 prefix negates `org-keep-stored-link-after-insertion'.
10204 If `org-make-link-description-function' is non-nil, this function will be
10205 called with the link target, and the result will be the default
10206 link description.
10208 If the LINK-LOCATION parameter is non-nil, this value will be used as
10209 the link location instead of reading one interactively.
10211 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10212 as the default description."
10213 (interactive "P")
10214 (let* ((wcf (current-window-configuration))
10215 (origbuf (current-buffer))
10216 (region (when (org-region-active-p)
10217 (buffer-substring (region-beginning) (region-end))))
10218 (remove (and region (list (region-beginning) (region-end))))
10219 (desc region)
10220 (link link-location)
10221 (abbrevs org-link-abbrev-alist-local)
10222 entry all-prefixes auto-desc)
10223 (cond
10224 (link-location) ; specified by arg, just use it.
10225 ((org-in-regexp org-bracket-link-regexp 1)
10226 ;; We do have a link at point, and we are going to edit it.
10227 (setq remove (list (match-beginning 0) (match-end 0)))
10228 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10229 (setq link (read-string "Link: "
10230 (org-link-unescape
10231 (match-string-no-properties 1)))))
10232 ((or (org-in-regexp org-angle-link-re)
10233 (org-in-regexp org-plain-link-re))
10234 ;; Convert to bracket link
10235 (setq remove (list (match-beginning 0) (match-end 0))
10236 link (read-string "Link: "
10237 (org-unbracket-string "<" ">" (match-string 0)))))
10238 ((member complete-file '((4) (16)))
10239 ;; Completing read for file names.
10240 (setq link (org-file-complete-link complete-file)))
10242 ;; Read link, with completion for stored links.
10243 (org-link-fontify-links-to-this-file)
10244 (org-switch-to-buffer-other-window "*Org Links*")
10245 (with-current-buffer "*Org Links*"
10246 (erase-buffer)
10247 (insert "Insert a link.
10248 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10249 (when org-stored-links
10250 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10251 (insert (mapconcat 'org-link-prettify
10252 (reverse org-stored-links) "\n")))
10253 (goto-char (point-min)))
10254 (let ((cw (selected-window)))
10255 (select-window (get-buffer-window "*Org Links*" 'visible))
10256 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10257 (unless (pos-visible-in-window-p (point-max))
10258 (org-fit-window-to-buffer))
10259 (and (window-live-p cw) (select-window cw)))
10260 (setq all-prefixes (append (mapcar 'car abbrevs)
10261 (mapcar 'car org-link-abbrev-alist)
10262 (org-link-types)))
10263 (unwind-protect
10264 ;; Fake a link history, containing the stored links.
10265 (let ((org--links-history
10266 (append (mapcar #'car org-stored-links)
10267 org-insert-link-history)))
10268 (setq link
10269 (org-completing-read
10270 "Link: "
10271 (append
10272 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10273 (mapcar #'car org-stored-links))
10274 nil nil nil
10275 'org--links-history
10276 (caar org-stored-links)))
10277 (unless (org-string-nw-p link) (user-error "No link selected"))
10278 (dolist (l org-stored-links)
10279 (when (equal link (cadr l))
10280 (setq link (car l))
10281 (setq auto-desc t)))
10282 (when (or (member link all-prefixes)
10283 (and (equal ":" (substring link -1))
10284 (member (substring link 0 -1) all-prefixes)
10285 (setq link (substring link 0 -1))))
10286 (setq link (with-current-buffer origbuf
10287 (org-link-try-special-completion link)))))
10288 (set-window-configuration wcf)
10289 (kill-buffer "*Org Links*"))
10290 (setq entry (assoc link org-stored-links))
10291 (or entry (push link org-insert-link-history))
10292 (setq desc (or desc (nth 1 entry)))))
10294 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10295 (not org-keep-stored-link-after-insertion))
10296 (setq org-stored-links (delq (assoc link org-stored-links)
10297 org-stored-links)))
10299 (when (and (string-match org-plain-link-re link)
10300 (not (string-match org-ts-regexp link)))
10301 ;; URL-like link, normalize the use of angular brackets.
10302 (setq link (org-unbracket-string "<" ">" link)))
10304 ;; Check if we are linking to the current file with a search
10305 ;; option If yes, simplify the link by using only the search
10306 ;; option.
10307 (when (and buffer-file-name
10308 (let ((case-fold-search nil))
10309 (string-match "\\`file:\\(.+?\\)::" link)))
10310 (let ((path (match-string-no-properties 1 link))
10311 (search (substring-no-properties link (match-end 0))))
10312 (save-match-data
10313 (when (equal (file-truename buffer-file-name) (file-truename path))
10314 ;; We are linking to this same file, with a search option
10315 (setq link search)))))
10317 ;; Check if we can/should use a relative path. If yes, simplify the link
10318 (let ((case-fold-search nil))
10319 (when (string-match "\\`\\(file\\|docview\\):" link)
10320 (let* ((type (match-string-no-properties 0 link))
10321 (path (substring-no-properties link (match-end 0)))
10322 (origpath path))
10323 (cond
10324 ((or (eq org-link-file-path-type 'absolute)
10325 (equal complete-file '(16)))
10326 (setq path (abbreviate-file-name (expand-file-name path))))
10327 ((eq org-link-file-path-type 'noabbrev)
10328 (setq path (expand-file-name path)))
10329 ((eq org-link-file-path-type 'relative)
10330 (setq path (file-relative-name path)))
10332 (save-match-data
10333 (if (string-match (concat "^" (regexp-quote
10334 (expand-file-name
10335 (file-name-as-directory
10336 default-directory))))
10337 (expand-file-name path))
10338 ;; We are linking a file with relative path name.
10339 (setq path (substring (expand-file-name path)
10340 (match-end 0)))
10341 (setq path (abbreviate-file-name (expand-file-name path)))))))
10342 (setq link (concat type path))
10343 (when (equal desc origpath)
10344 (setq desc path)))))
10346 (if org-make-link-description-function
10347 (setq desc
10348 (or (condition-case nil
10349 (funcall org-make-link-description-function link desc)
10350 (error (progn (message "Can't get link description from `%s'"
10351 (symbol-name org-make-link-description-function))
10352 (sit-for 2) nil)))
10353 (read-string "Description: " default-description)))
10354 (if default-description (setq desc default-description)
10355 (setq desc (or (and auto-desc desc)
10356 (read-string "Description: " desc)))))
10358 (unless (string-match "\\S-" desc) (setq desc nil))
10359 (when remove (apply 'delete-region remove))
10360 (insert (org-make-link-string link desc))
10361 ;; Redisplay so as the new link has proper invisible characters.
10362 (sit-for 0)))
10364 (defun org-link-try-special-completion (type)
10365 "If there is completion support for link type TYPE, offer it."
10366 (let ((fun (org-link-get-parameter type :complete)))
10367 (if (functionp fun)
10368 (funcall fun)
10369 (read-string "Link (no completion support): " (concat type ":")))))
10371 (defun org-file-complete-link (&optional arg)
10372 "Create a file link using completion."
10373 (let ((file (read-file-name "File: "))
10374 (pwd (file-name-as-directory (expand-file-name ".")))
10375 (pwd1 (file-name-as-directory (abbreviate-file-name
10376 (expand-file-name ".")))))
10377 (cond ((equal arg '(16))
10378 (concat "file:"
10379 (abbreviate-file-name (expand-file-name file))))
10380 ((string-match
10381 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10382 (concat "file:" (match-string 1 file)))
10383 ((string-match
10384 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10385 (expand-file-name file))
10386 (concat "file:"
10387 (match-string 1 (expand-file-name file))))
10388 (t (concat "file:" file)))))
10390 (defun org-completing-read (&rest args)
10391 "Completing-read with SPACE being a normal character."
10392 (let ((enable-recursive-minibuffers t)
10393 (minibuffer-local-completion-map
10394 (copy-keymap minibuffer-local-completion-map)))
10395 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10396 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10397 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10398 'org-time-stamp-inactive)
10399 (apply #'completing-read args)))
10401 ;;; Opening/following a link
10403 (defvar org-link-search-failed nil)
10405 (defvar org-open-link-functions nil
10406 "Hook for functions finding a plain text link.
10407 These functions must take a single argument, the link content.
10408 They will be called for links that look like [[link text][description]]
10409 when LINK TEXT does not have a protocol like \"http:\" and does not look
10410 like a filename (e.g. \"./blue.png\").
10412 These functions will be called *before* Org attempts to resolve the
10413 link by doing text searches in the current buffer - so if you want a
10414 link \"[[target]]\" to still find \"<<target>>\", your function should
10415 handle this as a special case.
10417 When the function does handle the link, it must return a non-nil value.
10418 If it decides that it is not responsible for this link, it must return
10419 nil to indicate that that Org can continue with other options like
10420 exact and fuzzy text search.")
10422 (defun org-next-link (&optional search-backward)
10423 "Move forward to the next link.
10424 If the link is in hidden text, expose it."
10425 (interactive "P")
10426 (when (and org-link-search-failed (eq this-command last-command))
10427 (goto-char (point-min))
10428 (message "Link search wrapped back to beginning of buffer"))
10429 (setq org-link-search-failed nil)
10430 (let* ((pos (point))
10431 (ct (org-context))
10432 (a (assq :link ct))
10433 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10434 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10435 ((looking-at org-any-link-re)
10436 ;; Don't stay stuck at link without an org-link face
10437 (forward-char (if search-backward -1 1))))
10438 (if (funcall srch-fun org-any-link-re nil t)
10439 (progn
10440 (goto-char (match-beginning 0))
10441 (when (outline-invisible-p) (org-show-context)))
10442 (goto-char pos)
10443 (setq org-link-search-failed t)
10444 (message "No further link found"))))
10446 (defun org-previous-link ()
10447 "Move backward to the previous link.
10448 If the link is in hidden text, expose it."
10449 (interactive)
10450 (funcall 'org-next-link t))
10452 (defun org-translate-link (s)
10453 "Translate a link string if a translation function has been defined."
10454 (with-temp-buffer
10455 (insert (org-trim s))
10456 (org-trim (org-element-interpret-data (org-element-context)))))
10458 (defun org-translate-link-from-planner (type path)
10459 "Translate a link from Emacs Planner syntax so that Org can follow it.
10460 This is still an experimental function, your mileage may vary."
10461 (cond
10462 ((member type '("http" "https" "news" "ftp"))
10463 ;; standard Internet links are the same.
10464 nil)
10465 ((and (equal type "irc") (string-match "^//" path))
10466 ;; Planner has two / at the beginning of an irc link, we have 1.
10467 ;; We should have zero, actually....
10468 (setq path (substring path 1)))
10469 ((and (equal type "lisp") (string-match "^/" path))
10470 ;; Planner has a slash, we do not.
10471 (setq type "elisp" path (substring path 1)))
10472 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10473 ;; A typical message link. Planner has the id after the final slash,
10474 ;; we separate it with a hash mark
10475 (setq path (concat (match-string 1 path) "#"
10476 (org-unbracket-string "<" ">" (match-string 2 path))))))
10477 (cons type path))
10479 (defun org-find-file-at-mouse (ev)
10480 "Open file link or URL at mouse."
10481 (interactive "e")
10482 (mouse-set-point ev)
10483 (org-open-at-point 'in-emacs))
10485 (defun org-open-at-mouse (ev)
10486 "Open file link or URL at mouse.
10487 See the docstring of `org-open-file' for details."
10488 (interactive "e")
10489 (mouse-set-point ev)
10490 (when (eq major-mode 'org-agenda-mode)
10491 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10492 (org-open-at-point))
10494 (defvar org-window-config-before-follow-link nil
10495 "The window configuration before following a link.
10496 This is saved in case the need arises to restore it.")
10498 ;;;###autoload
10499 (defun org-open-at-point-global ()
10500 "Follow a link or time-stamp like Org mode does.
10501 This command can be called in any mode to follow an external link
10502 or a time-stamp that has Org mode syntax. Its behavior is
10503 undefined when called on internal links (e.g., fuzzy links).
10504 Raise an error when there is nothing to follow. "
10505 (interactive)
10506 (cond ((org-in-regexp org-any-link-re)
10507 (org-open-link-from-string (match-string-no-properties 0)))
10508 ((or (org-in-regexp org-ts-regexp-both nil t)
10509 (org-in-regexp org-tsr-regexp-both nil t))
10510 (org-follow-timestamp-link))
10511 (t (user-error "No link found"))))
10513 ;;;###autoload
10514 (defun org-open-link-from-string (s &optional arg reference-buffer)
10515 "Open a link in the string S, as if it was in Org mode."
10516 (interactive "sLink: \nP")
10517 (let ((reference-buffer (or reference-buffer (current-buffer))))
10518 (with-temp-buffer
10519 (let ((org-inhibit-startup (not reference-buffer)))
10520 (org-mode)
10521 (insert s)
10522 (goto-char (point-min))
10523 (when reference-buffer
10524 (setq org-link-abbrev-alist-local
10525 (with-current-buffer reference-buffer
10526 org-link-abbrev-alist-local)))
10527 (org-open-at-point arg reference-buffer)))))
10529 (defvar org-open-at-point-functions nil
10530 "Hook that is run when following a link at point.
10532 Functions in this hook must return t if they identify and follow
10533 a link at point. If they don't find anything interesting at point,
10534 they must return nil.")
10536 (defvar org-link-search-inhibit-query nil)
10537 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10538 (defun org--open-doi-link (path)
10539 "Open a \"doi\" type link.
10540 PATH is a the path to search for, as a string."
10541 (browse-url (url-encode-url (concat org-doi-server-url path))))
10543 (defun org--open-elisp-link (path)
10544 "Open a \"elisp\" type link.
10545 PATH is the sexp to evaluate, as a string."
10546 (let ((cmd path))
10547 (if (or (and (org-string-nw-p
10548 org-confirm-elisp-link-not-regexp)
10549 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10550 (not org-confirm-elisp-link-function)
10551 (funcall org-confirm-elisp-link-function
10552 (format "Execute \"%s\" as elisp? "
10553 (org-add-props cmd nil 'face 'org-warning))))
10554 (message "%s => %s" cmd
10555 (if (eq (string-to-char cmd) ?\()
10556 (eval (read cmd))
10557 (call-interactively (read cmd))))
10558 (user-error "Abort"))))
10560 (defun org--open-help-link (path)
10561 "Open a \"help\" type link.
10562 PATH is a symbol name, as a string."
10563 (pcase (intern path)
10564 ((and (pred fboundp) variable) (describe-function variable))
10565 ((and (pred boundp) function) (describe-variable function))
10566 (name (user-error "Unknown function or variable: %s" name))))
10568 (defun org--open-shell-link (path)
10569 "Open a \"shell\" type link.
10570 PATH is the command to execute, as a string."
10571 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10572 (cmd path))
10573 (if (or (and (org-string-nw-p
10574 org-confirm-shell-link-not-regexp)
10575 (string-match
10576 org-confirm-shell-link-not-regexp cmd))
10577 (not org-confirm-shell-link-function)
10578 (funcall org-confirm-shell-link-function
10579 (format "Execute \"%s\" in shell? "
10580 (org-add-props cmd nil
10581 'face 'org-warning))))
10582 (progn
10583 (message "Executing %s" cmd)
10584 (shell-command cmd buf)
10585 (when (featurep 'midnight)
10586 (setq clean-buffer-list-kill-buffer-names
10587 (cons (buffer-name buf)
10588 clean-buffer-list-kill-buffer-names))))
10589 (user-error "Abort"))))
10591 (defun org-open-at-point (&optional arg reference-buffer)
10592 "Open link, timestamp, footnote or tags at point.
10594 When point is on a link, follow it. Normally, files will be
10595 opened by an appropriate application. If the optional prefix
10596 argument ARG is non-nil, Emacs will visit the file. With
10597 a double prefix argument, try to open outside of Emacs, in the
10598 application the system uses for this file type.
10600 When point is on a timestamp, open the agenda at the day
10601 specified.
10603 When point is a footnote definition, move to the first reference
10604 found. If it is on a reference, move to the associated
10605 definition.
10607 When point is on a headline, display a list of every link in the
10608 entry, so it is possible to pick one, or all, of them. If point
10609 is on a tag, call `org-tags-view' instead.
10611 When optional argument REFERENCE-BUFFER is non-nil, it should
10612 specify a buffer from where the link search should happen. This
10613 is used internally by `org-open-link-from-string'.
10615 On top of syntactically correct links, this function will open
10616 the link at point in comments or comment blocks and the first
10617 link in a property drawer line."
10618 (interactive "P")
10619 ;; On a code block, open block's results.
10620 (unless (call-interactively 'org-babel-open-src-block-result)
10621 (org-load-modules-maybe)
10622 (setq org-window-config-before-follow-link (current-window-configuration))
10623 (org-remove-occur-highlights nil nil t)
10624 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10625 (let* ((context
10626 ;; Only consider supported types, even if they are not
10627 ;; the closest one.
10628 (org-element-lineage
10629 (org-element-context)
10630 '(clock comment comment-block footnote-definition
10631 footnote-reference headline inlinetask keyword link
10632 node-property timestamp)
10634 (type (org-element-type context))
10635 (value (org-element-property :value context)))
10636 (cond
10637 ((not context) (user-error "No link found"))
10638 ;; Exception: open timestamps and links in properties
10639 ;; drawers, keywords and comments.
10640 ((memq type '(comment comment-block keyword node-property))
10641 (call-interactively #'org-open-at-point-global))
10642 ;; On a headline or an inlinetask, but not on a timestamp,
10643 ;; a link, a footnote reference or on tags.
10644 ((and (memq type '(headline inlinetask))
10645 ;; Not on tags.
10646 (let ((case-fold-search nil))
10647 (save-excursion
10648 (beginning-of-line)
10649 (looking-at org-complex-heading-regexp))
10650 (or (not (match-beginning 5))
10651 (< (point) (match-beginning 5)))))
10652 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10653 (links (car data))
10654 (links-end (cdr data)))
10655 (if links
10656 (dolist (link (if (stringp links) (list links) links))
10657 (search-forward link nil links-end)
10658 (goto-char (match-beginning 0))
10659 (org-open-at-point))
10660 (require 'org-attach)
10661 (org-attach-reveal 'if-exists))))
10662 ;; On a clock line, make sure point is on the timestamp
10663 ;; before opening it.
10664 ((and (eq type 'clock)
10665 value
10666 (>= (point) (org-element-property :begin value))
10667 (<= (point) (org-element-property :end value)))
10668 (org-follow-timestamp-link))
10669 ;; Do nothing on white spaces after an object.
10670 ((>= (point)
10671 (save-excursion
10672 (goto-char (org-element-property :end context))
10673 (skip-chars-backward " \t")
10674 (point)))
10675 (user-error "No link found"))
10676 ((eq type 'timestamp) (org-follow-timestamp-link))
10677 ;; On tags within a headline or an inlinetask.
10678 ((and (memq type '(headline inlinetask))
10679 (let ((case-fold-search nil))
10680 (save-excursion (beginning-of-line)
10681 (looking-at org-complex-heading-regexp))
10682 (and (match-beginning 5)
10683 (>= (point) (match-beginning 5)))))
10684 (org-tags-view arg (substring (match-string 5) 0 -1)))
10685 ((eq type 'link)
10686 (let ((type (org-element-property :type context))
10687 (path (org-link-unescape (org-element-property :path context))))
10688 ;; Switch back to REFERENCE-BUFFER needed when called in
10689 ;; a temporary buffer through `org-open-link-from-string'.
10690 (with-current-buffer (or reference-buffer (current-buffer))
10691 (cond
10692 ((equal type "file")
10693 (if (string-match "[*?{]" (file-name-nondirectory path))
10694 (dired path)
10695 ;; Look into `org-link-parameters' in order to find
10696 ;; a DEDICATED-FUNCTION to open file. The function
10697 ;; will be applied on raw link instead of parsed
10698 ;; link due to the limitation in `org-add-link-type'
10699 ;; ("open" function called with a single argument).
10700 ;; If no such function is found, fallback to
10701 ;; `org-open-file'.
10702 (let* ((option (org-element-property :search-option context))
10703 (app (org-element-property :application context))
10704 (dedicated-function
10705 (org-link-get-parameter
10706 (if app (concat type "+" app) type)
10707 :follow)))
10708 (if dedicated-function
10709 (funcall dedicated-function
10710 (concat path
10711 (and option (concat "::" option))))
10712 (apply #'org-open-file
10713 path
10714 (cond (arg)
10715 ((equal app "emacs") 'emacs)
10716 ((equal app "sys") 'system))
10717 (cond ((not option) nil)
10718 ((string-match-p "\\`[0-9]+\\'" option)
10719 (list (string-to-number option)))
10720 (t (list nil
10721 (org-link-unescape option)))))))))
10722 ((functionp (org-link-get-parameter type :follow))
10723 (funcall (org-link-get-parameter type :follow) path))
10724 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10725 (unless (run-hook-with-args-until-success
10726 'org-open-link-functions path)
10727 (if (not arg) (org-mark-ring-push)
10728 (switch-to-buffer-other-window
10729 (org-get-buffer-for-internal-link (current-buffer))))
10730 (let ((destination
10731 (org-with-wide-buffer
10732 (if (equal type "radio")
10733 (org-search-radio-target
10734 (org-element-property :path context))
10735 (org-link-search
10736 (if (member type '("custom-id" "coderef"))
10737 (org-element-property :raw-link context)
10738 path)
10739 ;; Prevent fuzzy links from matching
10740 ;; themselves.
10741 (and (equal type "fuzzy")
10742 (+ 2 (org-element-property :begin context)))))
10743 (point))))
10744 (unless (and (<= (point-min) destination)
10745 (>= (point-max) destination))
10746 (widen))
10747 (goto-char destination))))
10748 (t (browse-url-at-point))))))
10749 ;; On a footnote reference or at a footnote definition's label.
10750 ((or (eq type 'footnote-reference)
10751 (and (eq type 'footnote-definition)
10752 (save-excursion
10753 ;; Do not validate action when point is on the
10754 ;; spaces right after the footnote label, in
10755 ;; order to be on par with behaviour on links.
10756 (skip-chars-forward " \t")
10757 (let ((begin
10758 (org-element-property :contents-begin context)))
10759 (if begin (< (point) begin)
10760 (= (org-element-property :post-affiliated context)
10761 (line-beginning-position)))))))
10762 (org-footnote-action))
10763 (t (user-error "No link found")))))
10764 (run-hook-with-args 'org-follow-link-hook)))
10766 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10767 "Offer links in the current entry and return the selected link.
10768 If there is only one link, return it.
10769 If NTH is an integer, return the NTH link found.
10770 If ZERO is a string, check also this string for a link, and if
10771 there is one, return it."
10772 (with-current-buffer buffer
10773 (org-with-wide-buffer
10774 (goto-char marker)
10775 (let ((cnt ?0)
10776 have-zero end links link c)
10777 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10778 (push (match-string 0 zero) links)
10779 (setq cnt (1- cnt) have-zero t))
10780 (save-excursion
10781 (org-back-to-heading t)
10782 (setq end (save-excursion (outline-next-heading) (point)))
10783 (while (re-search-forward org-any-link-re end t)
10784 (push (match-string 0) links))
10785 (setq links (org-uniquify (reverse links))))
10786 (cond
10787 ((null links)
10788 (message "No links"))
10789 ((equal (length links) 1)
10790 (setq link (car links)))
10791 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10792 (setq link (nth (if have-zero nth (1- nth)) links)))
10793 (t ; we have to select a link
10794 (save-excursion
10795 (save-window-excursion
10796 (delete-other-windows)
10797 (with-output-to-temp-buffer "*Select Link*"
10798 (dolist (l links)
10799 (cond
10800 ((not (string-match org-bracket-link-regexp l))
10801 (princ (format "[%c] %s\n" (cl-incf cnt)
10802 (org-unbracket-string "<" ">" l))))
10803 ((match-end 3)
10804 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10805 (match-string 3 l) (match-string 1 l))))
10806 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10807 (match-string 1 l)))))))
10808 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10809 (message "Select link to open, RET to open all:")
10810 (setq c (read-char-exclusive))
10811 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10812 (when (equal c ?q) (user-error "Abort"))
10813 (if (equal c ?\C-m)
10814 (setq link links)
10815 (setq nth (- c ?0))
10816 (when have-zero (setq nth (1+ nth)))
10817 (unless (and (integerp nth) (>= (length links) nth))
10818 (user-error "Invalid link selection"))
10819 (setq link (nth (1- nth) links)))))
10820 (cons link end)))))
10822 ;; TODO: These functions are deprecated since `org-open-at-point'
10823 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10824 (defun org-open-file-with-system (path)
10825 "Open file at PATH using the system way of opening it."
10826 (org-open-file path 'system))
10827 (defun org-open-file-with-emacs (path)
10828 "Open file at PATH in Emacs."
10829 (org-open-file path 'emacs))
10832 ;;; File search
10834 (defvar org-create-file-search-functions nil
10835 "List of functions to construct the right search string for a file link.
10836 These functions are called in turn with point at the location to
10837 which the link should point.
10839 A function in the hook should first test if it would like to
10840 handle this file type, for example by checking the `major-mode'
10841 or the file extension. If it decides not to handle this file, it
10842 should just return nil to give other functions a chance. If it
10843 does handle the file, it must return the search string to be used
10844 when following the link. The search string will be part of the
10845 file link, given after a double colon, and `org-open-at-point'
10846 will automatically search for it. If special measures must be
10847 taken to make the search successful, another function should be
10848 added to the companion hook `org-execute-file-search-functions',
10849 which see.
10851 A function in this hook may also use `setq' to set the variable
10852 `description' to provide a suggestion for the descriptive text to
10853 be used for this link when it gets inserted into an Org buffer
10854 with \\[org-insert-link].")
10856 (defvar org-execute-file-search-functions nil
10857 "List of functions to execute a file search triggered by a link.
10859 Functions added to this hook must accept a single argument, the
10860 search string that was part of the file link, the part after the
10861 double colon. The function must first check if it would like to
10862 handle this search, for example by checking the `major-mode' or
10863 the file extension. If it decides not to handle this search, it
10864 should just return nil to give other functions a chance. If it
10865 does handle the search, it must return a non-nil value to keep
10866 other functions from trying.
10868 Each function can access the current prefix argument through the
10869 variable `current-prefix-arg'. Note that a single prefix is used
10870 to force opening a link in Emacs, so it may be good to only use a
10871 numeric or double prefix to guide the search function.
10873 In case this is needed, a function in this hook can also restore
10874 the window configuration before `org-open-at-point' was called using:
10876 (set-window-configuration org-window-config-before-follow-link)")
10878 (defun org-search-radio-target (target)
10879 "Search a radio target matching TARGET in current buffer.
10880 White spaces are not significant."
10881 (let ((re (format "<<<%s>>>"
10882 (mapconcat #'regexp-quote
10883 (org-split-string target "[ \t\n]+")
10884 "[ \t]+\\(?:\n[ \t]*\\)?")))
10885 (origin (point)))
10886 (goto-char (point-min))
10887 (catch :radio-match
10888 (while (re-search-forward re nil t)
10889 (backward-char)
10890 (let ((object (org-element-context)))
10891 (when (eq (org-element-type object) 'radio-target)
10892 (goto-char (org-element-property :begin object))
10893 (org-show-context 'link-search)
10894 (throw :radio-match nil))))
10895 (goto-char origin)
10896 (user-error "No match for radio target: %s" target))))
10898 (defun org-link-search (s &optional avoid-pos stealth)
10899 "Search for a search string S.
10901 If S starts with \"#\", it triggers a custom ID search.
10903 If S is enclosed within parenthesis, it initiates a coderef
10904 search.
10906 If S is surrounded by forward slashes, it is interpreted as
10907 a regular expression. In Org mode files, this will create an
10908 `org-occur' sparse tree. In ordinary files, `occur' will be used
10909 to list matches. If the current buffer is in `dired-mode', grep
10910 will be used to search in all files.
10912 When AVOID-POS is given, ignore matches near that position.
10914 When optional argument STEALTH is non-nil, do not modify
10915 visibility around point, thus ignoring `org-show-context-detail'
10916 variable.
10918 Search is case-insensitive and ignores white spaces. Return type
10919 of matched result, which is either `dedicated' or `fuzzy'."
10920 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10921 (let* ((case-fold-search t)
10922 (origin (point))
10923 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10924 (starred (eq (string-to-char normalized) ?*))
10925 (words (split-string (if starred (substring s 1) s)))
10926 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10927 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10928 type)
10929 (cond
10930 ;; Check if there are any special search functions.
10931 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10932 ((eq (string-to-char s) ?#)
10933 ;; Look for a custom ID S if S starts with "#".
10934 (let* ((id (substring normalized 1))
10935 (match (org-find-property "CUSTOM_ID" id)))
10936 (if match (progn (goto-char match) (setf type 'dedicated))
10937 (error "No match for custom ID: %s" id))))
10938 ((string-match "\\`(\\(.*\\))\\'" normalized)
10939 ;; Look for coderef targets if S is enclosed within parenthesis.
10940 (let ((coderef (match-string-no-properties 1 normalized))
10941 (re (substring s-single-re 1 -1)))
10942 (goto-char (point-min))
10943 (catch :coderef-match
10944 (while (re-search-forward re nil t)
10945 (let ((element (org-element-at-point)))
10946 (when (and (memq (org-element-type element)
10947 '(example-block src-block))
10948 ;; Build proper regexp according to current
10949 ;; block's label format.
10950 (let ((label-fmt
10951 (regexp-quote
10952 (or (org-element-property :label-fmt element)
10953 org-coderef-label-format))))
10954 (save-excursion
10955 (beginning-of-line)
10956 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10957 (format label-fmt coderef))))))
10958 (setq type 'dedicated)
10959 (goto-char (match-beginning 1))
10960 (throw :coderef-match nil))))
10961 (goto-char origin)
10962 (error "No match for coderef: %s" coderef))))
10963 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10964 ;; Look for a regular expression.
10965 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10966 (match-string 1 s)))
10967 ;; From here, we handle fuzzy links.
10969 ;; Look for targets, only if not in a headline search.
10970 ((and (not starred)
10971 (let ((target (format "<<%s>>" s-multi-re)))
10972 (catch :target-match
10973 (goto-char (point-min))
10974 (while (re-search-forward target nil t)
10975 (backward-char)
10976 (let ((context (org-element-context)))
10977 (when (eq (org-element-type context) 'target)
10978 (setq type 'dedicated)
10979 (goto-char (org-element-property :begin context))
10980 (throw :target-match t))))
10981 nil))))
10982 ;; Look for elements named after S, only if not in a headline
10983 ;; search.
10984 ((and (not starred)
10985 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10986 (catch :name-match
10987 (goto-char (point-min))
10988 (while (re-search-forward name nil t)
10989 (let ((element (org-element-at-point)))
10990 (when (equal words
10991 (split-string
10992 (org-element-property :name element)))
10993 (setq type 'dedicated)
10994 (beginning-of-line)
10995 (throw :name-match t))))
10996 nil))))
10997 ;; Regular text search. Prefer headlines in Org mode buffers.
10998 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10999 ;; statistics cookies and tags.
11000 ((and (derived-mode-p 'org-mode)
11001 (let ((title-re
11002 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11003 org-outline-regexp-bol
11004 org-comment-string
11005 (mapconcat #'regexp-quote words ".+")))
11006 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11007 (comment-re (eval-when-compile
11008 (format "\\`%s[ \t]+" org-comment-string))))
11009 (goto-char (point-min))
11010 (catch :found
11011 (while (re-search-forward title-re nil t)
11012 (when (equal words
11013 (split-string
11014 (replace-regexp-in-string
11015 cookie-re ""
11016 (replace-regexp-in-string
11017 comment-re "" (org-get-heading t t t)))))
11018 (throw :found t)))
11019 nil)))
11020 (beginning-of-line)
11021 (setq type 'dedicated))
11022 ;; Offer to create non-existent headline depending on
11023 ;; `org-link-search-must-match-exact-headline'.
11024 ((and (derived-mode-p 'org-mode)
11025 (not org-link-search-inhibit-query)
11026 (eq org-link-search-must-match-exact-headline 'query-to-create)
11027 (yes-or-no-p "No match - create this as a new heading? "))
11028 (goto-char (point-max))
11029 (unless (bolp) (newline))
11030 (org-insert-heading nil t t)
11031 (insert s "\n")
11032 (beginning-of-line 0))
11033 ;; Only headlines are looked after. No need to process
11034 ;; further: throw an error.
11035 ((and (derived-mode-p 'org-mode)
11036 (or starred org-link-search-must-match-exact-headline))
11037 (goto-char origin)
11038 (error "No match for fuzzy expression: %s" normalized))
11039 ;; Regular text search.
11040 ((catch :fuzzy-match
11041 (goto-char (point-min))
11042 (while (re-search-forward s-multi-re nil t)
11043 ;; Skip match if it contains AVOID-POS or it is included in
11044 ;; a link with a description but outside the description.
11045 (unless (or (and avoid-pos
11046 (<= (match-beginning 0) avoid-pos)
11047 (> (match-end 0) avoid-pos))
11048 (and (save-match-data
11049 (org-in-regexp org-bracket-link-regexp))
11050 (match-beginning 3)
11051 (or (> (match-beginning 3) (point))
11052 (<= (match-end 3) (point)))
11053 (org-element-lineage
11054 (save-match-data (org-element-context))
11055 '(link) t)))
11056 (goto-char (match-beginning 0))
11057 (setq type 'fuzzy)
11058 (throw :fuzzy-match t)))
11059 nil))
11060 ;; All failed. Throw an error.
11061 (t (goto-char origin)
11062 (error "No match for fuzzy expression: %s" normalized)))
11063 ;; Disclose surroundings of match, if appropriate.
11064 (when (and (derived-mode-p 'org-mode) (not stealth))
11065 (org-show-context 'link-search))
11066 type))
11068 (defun org-get-buffer-for-internal-link (buffer)
11069 "Return a buffer to be used for displaying the link target of internal links."
11070 (cond
11071 ((not org-display-internal-link-with-indirect-buffer)
11072 buffer)
11073 ((string-suffix-p "(Clone)" (buffer-name buffer))
11074 (message "Buffer is already a clone, not making another one")
11075 ;; we also do not modify visibility in this case
11076 buffer)
11077 (t ; make a new indirect buffer for displaying the link
11078 (let* ((bn (buffer-name buffer))
11079 (ibn (concat bn "(Clone)"))
11080 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11081 (with-current-buffer ib (org-overview))
11082 ib))))
11084 (defun org-do-occur (regexp &optional cleanup)
11085 "Call the Emacs command `occur'.
11086 If CLEANUP is non-nil, remove the printout of the regular expression
11087 in the *Occur* buffer. This is useful if the regex is long and not useful
11088 to read."
11089 (occur regexp)
11090 (when cleanup
11091 (let ((cwin (selected-window)) win beg end)
11092 (when (setq win (get-buffer-window "*Occur*"))
11093 (select-window win))
11094 (goto-char (point-min))
11095 (when (re-search-forward "match[a-z]+" nil t)
11096 (setq beg (match-end 0))
11097 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11098 (setq end (1- (match-beginning 0)))))
11099 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11100 (goto-char (point-min))
11101 (select-window cwin))))
11103 ;;; The mark ring for links jumps
11105 (defvar org-mark-ring nil
11106 "Mark ring for positions before jumps in Org mode.")
11107 (defvar org-mark-ring-last-goto nil
11108 "Last position in the mark ring used to go back.")
11109 ;; Fill and close the ring
11110 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11111 (dotimes (_ org-mark-ring-length)
11112 (push (make-marker) org-mark-ring))
11113 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11114 org-mark-ring)
11116 (defun org-mark-ring-push (&optional pos buffer)
11117 "Put the current position or POS into the mark ring and rotate it."
11118 (interactive)
11119 (setq pos (or pos (point)))
11120 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11121 (move-marker (car org-mark-ring)
11122 (or pos (point))
11123 (or buffer (current-buffer)))
11124 (message "%s"
11125 (substitute-command-keys
11126 "Position saved to mark ring, go back with \
11127 `\\[org-mark-ring-goto]'.")))
11129 (defun org-mark-ring-goto (&optional n)
11130 "Jump to the previous position in the mark ring.
11131 With prefix arg N, jump back that many stored positions. When
11132 called several times in succession, walk through the entire ring.
11133 Org mode commands jumping to a different position in the current file,
11134 or to another Org file, automatically push the old position onto the ring."
11135 (interactive "p")
11136 (let (p m)
11137 (if (eq last-command this-command)
11138 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11139 (setq p org-mark-ring))
11140 (setq org-mark-ring-last-goto p)
11141 (setq m (car p))
11142 (pop-to-buffer-same-window (marker-buffer m))
11143 (goto-char m)
11144 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11146 (defun org-add-angle-brackets (s)
11147 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11148 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11151 ;;; Following specific links
11153 (defvar org-agenda-buffer-tmp-name)
11154 (defvar org-agenda-start-on-weekday)
11155 (defun org-follow-timestamp-link ()
11156 "Open an agenda view for the time-stamp date/range at point."
11157 (cond
11158 ((org-at-date-range-p t)
11159 (let ((org-agenda-start-on-weekday)
11160 (t1 (match-string 1))
11161 (t2 (match-string 2)) tt1 tt2)
11162 (setq tt1 (time-to-days (org-time-string-to-time t1))
11163 tt2 (time-to-days (org-time-string-to-time t2)))
11164 (let ((org-agenda-buffer-tmp-name
11165 (format "*Org Agenda(a:%s)"
11166 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11167 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11168 ((org-at-timestamp-p 'lax)
11169 (let ((org-agenda-buffer-tmp-name
11170 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11171 (org-agenda-list nil (time-to-days (org-time-string-to-time
11172 (substring (match-string 1) 0 10)))
11173 1)))
11174 (t (error "This should not happen"))))
11177 ;;; Following file links
11178 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11179 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11180 (declare-function mailcap-mime-info
11181 "mailcap" (string &optional request no-decode))
11182 (defvar org-wait nil)
11183 (defun org-open-file (path &optional in-emacs line search)
11184 "Open the file at PATH.
11185 First, this expands any special file name abbreviations. Then the
11186 configuration variable `org-file-apps' is checked if it contains an
11187 entry for this file type, and if yes, the corresponding command is launched.
11189 If no application is found, Emacs simply visits the file.
11191 With optional prefix argument IN-EMACS, Emacs will visit the file.
11192 With a double \\[universal-argument] \\[universal-argument] \
11193 prefix arg, Org tries to avoid opening in Emacs
11194 and to use an external application to visit the file.
11196 Optional LINE specifies a line to go to, optional SEARCH a string
11197 to search for. If LINE or SEARCH is given, the file will be
11198 opened in Emacs, unless an entry from org-file-apps that makes
11199 use of groups in a regexp matches.
11201 If you want to change the way frames are used when following a
11202 link, please customize `org-link-frame-setup'.
11204 If the file does not exist, an error is thrown."
11205 (let* ((file (if (equal path "")
11206 buffer-file-name
11207 (substitute-in-file-name (expand-file-name path))))
11208 (file-apps (append org-file-apps (org-default-apps)))
11209 (apps (cl-remove-if
11210 'org-file-apps-entry-match-against-dlink-p file-apps))
11211 (apps-dlink (cl-remove-if-not
11212 'org-file-apps-entry-match-against-dlink-p file-apps))
11213 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11214 (dirp (unless remp (file-directory-p file)))
11215 (file (if (and dirp org-open-directory-means-index-dot-org)
11216 (concat (file-name-as-directory file) "index.org")
11217 file))
11218 (a-m-a-p (assq 'auto-mode apps))
11219 (dfile (downcase file))
11220 ;; Reconstruct the original link from the PATH, LINE and
11221 ;; SEARCH args.
11222 (link (cond (line (concat file "::" (number-to-string line)))
11223 (search (concat file "::" search))
11224 (t file)))
11225 (dlink (downcase link))
11226 (ext
11227 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11228 (match-string 1 dfile)))
11229 (save-position-maybe
11230 (let ((old-buffer (current-buffer))
11231 (old-pos (point))
11232 (old-mode major-mode))
11233 (lambda ()
11234 (and (derived-mode-p 'org-mode)
11235 (eq old-mode 'org-mode)
11236 (or (not (eq old-buffer (current-buffer)))
11237 (not (eq old-pos (point))))
11238 (org-mark-ring-push old-pos old-buffer)))))
11239 cmd link-match-data)
11240 (cond
11241 ((member in-emacs '((16) system))
11242 (setq cmd (cdr (assq 'system apps))))
11243 (in-emacs (setq cmd 'emacs))
11245 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11246 (and dirp (cdr (assq 'directory apps)))
11247 ;; First, try matching against apps-dlink if we
11248 ;; get a match here, store the match data for
11249 ;; later.
11250 (let ((match (assoc-default dlink apps-dlink
11251 'string-match)))
11252 (if match
11253 (progn (setq link-match-data (match-data))
11254 match)
11255 (progn (setq in-emacs (or in-emacs line search))
11256 nil))) ; if we have no match in apps-dlink,
11257 ; always open the file in emacs if line or search
11258 ; is given (for backwards compatibility)
11259 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11260 'string-match)
11261 (cdr (assoc ext apps))
11262 (cdr (assq t apps))))))
11263 (when (eq cmd 'system)
11264 (setq cmd (cdr (assq 'system apps))))
11265 (when (eq cmd 'default)
11266 (setq cmd (cdr (assoc t apps))))
11267 (when (eq cmd 'mailcap)
11268 (require 'mailcap)
11269 (mailcap-parse-mailcaps)
11270 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11271 (command (mailcap-mime-info mime-type)))
11272 (if (stringp command)
11273 (setq cmd command)
11274 (setq cmd 'emacs))))
11275 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11276 (not (file-exists-p file))
11277 (not org-open-non-existing-files))
11278 (user-error "No such file: %s" file))
11279 (cond
11280 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11281 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11282 (while (string-match "['\"]%s['\"]" cmd)
11283 (setq cmd (replace-match "%s" t t cmd)))
11284 (setq cmd (replace-regexp-in-string
11285 "%s"
11286 (shell-quote-argument (convert-standard-filename file))
11288 nil t))
11290 ;; Replace "%1", "%2" etc. in command with group matches from regex
11291 (save-match-data
11292 (let ((match-index 1)
11293 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11294 (set-match-data link-match-data)
11295 (while (<= match-index number-of-groups)
11296 (let ((regex (concat "%" (number-to-string match-index)))
11297 (replace-with (match-string match-index dlink)))
11298 (while (string-match regex cmd)
11299 (setq cmd (replace-match replace-with t t cmd))))
11300 (setq match-index (+ match-index 1)))))
11302 (save-window-excursion
11303 (message "Running %s...done" cmd)
11304 (start-process-shell-command cmd nil cmd)
11305 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11306 ((or (stringp cmd)
11307 (eq cmd 'emacs))
11308 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11309 (widen)
11310 (cond (line (org-goto-line line)
11311 (when (derived-mode-p 'org-mode) (org-reveal)))
11312 (search (condition-case err
11313 (org-link-search search)
11314 ;; Save position before error-ing out so user
11315 ;; can easily move back to the original buffer.
11316 (error (funcall save-position-maybe)
11317 (error (nth 1 err)))))))
11318 ((functionp cmd)
11319 (save-match-data
11320 (set-match-data link-match-data)
11321 (condition-case nil
11322 (funcall cmd file link)
11323 ;; FIXME: Remove this check when most default installations
11324 ;; of Emacs have at least Org 9.0.
11325 ((debug wrong-number-of-arguments wrong-type-argument
11326 invalid-function)
11327 (user-error "Please see Org News for version 9.0 about \
11328 `org-file-apps'--Lisp error: %S" cmd)))))
11329 ((consp cmd)
11330 ;; FIXME: Remove this check when most default installations of
11331 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11332 ;; fall back to `org-link-frame-setup' for an old usage of
11333 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11334 (user-error "Please see Org News for version 9.0 about \
11335 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11336 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11337 (funcall save-position-maybe)))
11339 (defun org-file-apps-entry-match-against-dlink-p (entry)
11340 "This function returns non-nil if `entry' uses a regular
11341 expression which should be matched against the whole link by
11342 org-open-file.
11344 It assumes that is the case when the entry uses a regular
11345 expression which has at least one grouping construct and the
11346 action is either a lisp form or a command string containing
11347 `%1', i.e. using at least one subexpression match as a
11348 parameter."
11349 (let ((selector (car entry))
11350 (action (cdr entry)))
11351 (if (stringp selector)
11352 (and (> (regexp-opt-depth selector) 0)
11353 (or (and (stringp action)
11354 (string-match "%[0-9]" action))
11355 (consp action)))
11356 nil)))
11358 (defun org-default-apps ()
11359 "Return the default applications for this operating system."
11360 (cond
11361 ((eq system-type 'darwin)
11362 org-file-apps-defaults-macosx)
11363 ((eq system-type 'windows-nt)
11364 org-file-apps-defaults-windowsnt)
11365 (t org-file-apps-defaults-gnu)))
11367 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11368 "Convert extensions to regular expressions in the cars of LIST.
11369 Also, weed out any non-string entries, because the return value is used
11370 only for regexp matching.
11371 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11372 point to the symbol `emacs', indicating that the file should
11373 be opened in Emacs."
11374 (append
11375 (delq nil
11376 (mapcar (lambda (x)
11377 (unless (not (stringp (car x)))
11378 (if (string-match "\\W" (car x))
11380 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11381 list))
11382 (when add-auto-mode
11383 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11385 (defvar ange-ftp-name-format)
11386 (defun org-file-remote-p (file)
11387 "Test whether FILE specifies a location on a remote system.
11388 Return non-nil if the location is indeed remote.
11390 For example, the filename \"/user@host:/foo\" specifies a location
11391 on the system \"/user@host:\"."
11392 (cond ((fboundp 'file-remote-p)
11393 (file-remote-p file))
11394 ((fboundp 'tramp-handle-file-remote-p)
11395 (tramp-handle-file-remote-p file))
11396 ((and (boundp 'ange-ftp-name-format)
11397 (string-match (car ange-ftp-name-format) file))
11398 t)))
11401 ;;;; Refiling
11403 (defun org-get-org-file ()
11404 "Read a filename, with default directory `org-directory'."
11405 (let ((default (or org-default-notes-file remember-data-file)))
11406 (read-file-name (format "File name [%s]: " default)
11407 (file-name-as-directory org-directory)
11408 default)))
11410 (defun org-notes-order-reversed-p ()
11411 "Check if the current file should receive notes in reversed order."
11412 (cond
11413 ((not org-reverse-note-order) nil)
11414 ((eq t org-reverse-note-order) t)
11415 ((not (listp org-reverse-note-order)) nil)
11416 (t (catch 'exit
11417 (dolist (entry org-reverse-note-order)
11418 (when (string-match (car entry) buffer-file-name)
11419 (throw 'exit (cdr entry))))))))
11421 (defvar org-refile-target-table nil
11422 "The list of refile targets, created by `org-refile'.")
11424 (defvar org-agenda-new-buffers nil
11425 "Buffers created to visit agenda files.")
11427 (defvar org-refile-cache nil
11428 "Cache for refile targets.")
11430 (defvar org-refile-markers nil
11431 "All the markers used for caching refile locations.")
11433 (defun org-refile-marker (pos)
11434 "Get a new refile marker, but only if caching is in use."
11435 (if (not org-refile-use-cache)
11437 (let ((m (make-marker)))
11438 (move-marker m pos)
11439 (push m org-refile-markers)
11440 m)))
11442 (defun org-refile-cache-clear ()
11443 "Clear the refile cache and disable all the markers."
11444 (dolist (m org-refile-markers) (move-marker m nil))
11445 (setq org-refile-markers nil)
11446 (setq org-refile-cache nil)
11447 (message "Refile cache has been cleared"))
11449 (defun org-refile-cache-check-set (set)
11450 "Check if all the markers in the cache still have live buffers."
11451 (let (marker)
11452 (catch 'exit
11453 (while (and set (setq marker (nth 3 (pop set))))
11454 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11455 (when (and marker (null (marker-buffer marker)))
11456 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11457 (sit-for 3)
11458 (throw 'exit nil)))
11459 t)))
11461 (defun org-refile-cache-put (set &rest identifiers)
11462 "Push the refile targets SET into the cache, under IDENTIFIERS."
11463 (let* ((key (sha1 (prin1-to-string identifiers)))
11464 (entry (assoc key org-refile-cache)))
11465 (if entry
11466 (setcdr entry set)
11467 (push (cons key set) org-refile-cache))))
11469 (defun org-refile-cache-get (&rest identifiers)
11470 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11471 (cond
11472 ((not org-refile-cache) nil)
11473 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11475 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11476 org-refile-cache))))
11477 (and set (org-refile-cache-check-set set) set)))))
11479 (defvar org-outline-path-cache nil
11480 "Alist between buffer positions and outline paths.
11481 It value is an alist (POSITION . PATH) where POSITION is the
11482 buffer position at the beginning of an entry and PATH is a list
11483 of strings describing the outline path for that entry, in reverse
11484 order.")
11486 (defun org-refile-get-targets (&optional default-buffer)
11487 "Produce a table with refile targets."
11488 (let ((case-fold-search nil)
11489 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11490 (entries (or org-refile-targets '((nil . (:level . 1)))))
11491 targets tgs files desc descre)
11492 (message "Getting targets...")
11493 (with-current-buffer (or default-buffer (current-buffer))
11494 (dolist (entry entries)
11495 (setq files (car entry) desc (cdr entry))
11496 (cond
11497 ((null files) (setq files (list (current-buffer))))
11498 ((eq files 'org-agenda-files)
11499 (setq files (org-agenda-files 'unrestricted)))
11500 ((and (symbolp files) (fboundp files))
11501 (setq files (funcall files)))
11502 ((and (symbolp files) (boundp files))
11503 (setq files (symbol-value files))))
11504 (when (stringp files) (setq files (list files)))
11505 (cond
11506 ((eq (car desc) :tag)
11507 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11508 ((eq (car desc) :todo)
11509 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11510 ((eq (car desc) :regexp)
11511 (setq descre (cdr desc)))
11512 ((eq (car desc) :level)
11513 (setq descre (concat "^\\*\\{" (number-to-string
11514 (if org-odd-levels-only
11515 (1- (* 2 (cdr desc)))
11516 (cdr desc)))
11517 "\\}[ \t]")))
11518 ((eq (car desc) :maxlevel)
11519 (setq descre (concat "^\\*\\{1," (number-to-string
11520 (if org-odd-levels-only
11521 (1- (* 2 (cdr desc)))
11522 (cdr desc)))
11523 "\\}[ \t]")))
11524 (t (error "Bad refiling target description %s" desc)))
11525 (dolist (f files)
11526 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11528 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11529 (progn
11530 (when (bufferp f)
11531 (setq f (buffer-file-name (buffer-base-buffer f))))
11532 (setq f (and f (expand-file-name f)))
11533 (when (eq org-refile-use-outline-path 'file)
11534 (push (list (file-name-nondirectory f) f nil nil) tgs))
11535 (when (eq org-refile-use-outline-path 'buffer-name)
11536 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11537 (when (eq org-refile-use-outline-path 'full-file-path)
11538 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11539 (org-with-wide-buffer
11540 (goto-char (point-min))
11541 (setq org-outline-path-cache nil)
11542 (while (re-search-forward descre nil t)
11543 (beginning-of-line)
11544 (let ((case-fold-search nil))
11545 (looking-at org-complex-heading-regexp))
11546 (let ((begin (point))
11547 (heading (match-string-no-properties 4)))
11548 (unless (or (and
11549 org-refile-target-verify-function
11550 (not
11551 (funcall org-refile-target-verify-function)))
11552 (not heading))
11553 (let ((re (format org-complex-heading-regexp-format
11554 (regexp-quote heading)))
11555 (target
11556 (if (not org-refile-use-outline-path) heading
11557 (mapconcat
11558 #'identity
11559 (append
11560 (pcase org-refile-use-outline-path
11561 (`file (list (file-name-nondirectory
11562 (buffer-file-name
11563 (buffer-base-buffer)))))
11564 (`full-file-path
11565 (list (buffer-file-name
11566 (buffer-base-buffer))))
11567 (`buffer-name
11568 (list (buffer-name
11569 (buffer-base-buffer))))
11570 (_ nil))
11571 (mapcar (lambda (s) (replace-regexp-in-string
11572 "/" "\\/" s nil t))
11573 (org-get-outline-path t t)))
11574 "/"))))
11575 (push (list target f re (org-refile-marker (point)))
11576 tgs)))
11577 (when (= (point) begin)
11578 ;; Verification function has not moved point.
11579 (end-of-line)))))))
11580 (when org-refile-use-cache
11581 (org-refile-cache-put tgs (buffer-file-name) descre))
11582 (setq targets (append tgs targets))))))
11583 (message "Getting targets...done")
11584 (delete-dups (nreverse targets))))
11586 (defun org--get-outline-path-1 (&optional use-cache)
11587 "Return outline path to current headline.
11589 Outline path is a list of strings, in reverse order. When
11590 optional argument USE-CACHE is non-nil, make use of a cache. See
11591 `org-get-outline-path' for details.
11593 Assume buffer is widened and point is on a headline."
11594 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11595 (let ((p (point))
11596 (heading (let ((case-fold-search nil))
11597 (looking-at org-complex-heading-regexp)
11598 (if (not (match-end 4)) ""
11599 ;; Remove statistics cookies.
11600 (org-trim
11601 (org-link-display-format
11602 (replace-regexp-in-string
11603 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11604 (match-string-no-properties 4))))))))
11605 (if (org-up-heading-safe)
11606 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11607 (when use-cache
11608 (push (cons p path) org-outline-path-cache))
11609 path)
11610 ;; This is a new root node. Since we assume we are moving
11611 ;; forward, we can drop previous cache so as to limit number
11612 ;; of associations there.
11613 (let ((path (list heading)))
11614 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11615 path)))))
11617 (defun org-get-outline-path (&optional with-self use-cache)
11618 "Return the outline path to the current entry.
11620 An outline path is a list of ancestors for current headline, as
11621 a list of strings. Statistics cookies are removed and links are
11622 replaced with their description, if any, or their path otherwise.
11624 When optional argument WITH-SELF is non-nil, the path also
11625 includes the current headline.
11627 When optional argument USE-CACHE is non-nil, cache outline paths
11628 between calls to this function so as to avoid backtracking. This
11629 argument is useful when planning to find more than one outline
11630 path in the same document. In that case, there are two
11631 conditions to satisfy:
11632 - `org-outline-path-cache' is set to nil before starting the
11633 process;
11634 - outline paths are computed by increasing buffer positions."
11635 (org-with-wide-buffer
11636 (and (or (and with-self (org-back-to-heading t))
11637 (org-up-heading-safe))
11638 (reverse (org--get-outline-path-1 use-cache)))))
11640 (defun org-format-outline-path (path &optional width prefix separator)
11641 "Format the outline path PATH for display.
11642 WIDTH is the maximum number of characters that is available.
11643 PREFIX is a prefix to be included in the returned string,
11644 such as the file name.
11645 SEPARATOR is inserted between the different parts of the path,
11646 the default is \"/\"."
11647 (setq width (or width 79))
11648 (setq path (delq nil path))
11649 (unless (> width 0)
11650 (user-error "Argument `width' must be positive"))
11651 (setq separator (or separator "/"))
11652 (let* ((org-odd-levels-only nil)
11653 (fpath (concat
11654 prefix (and prefix path separator)
11655 (mapconcat
11656 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11657 (cl-loop for head in path
11658 for n from 0
11659 collect (org-add-props
11660 head nil 'face
11661 (nth (% n org-n-level-faces) org-level-faces)))
11662 separator))))
11663 (when (> (length fpath) width)
11664 (if (< width 7)
11665 ;; It's unlikely that `width' will be this small, but don't
11666 ;; waste characters by adding ".." if it is.
11667 (setq fpath (substring fpath 0 width))
11668 (setf (substring fpath (- width 2)) "..")))
11669 fpath))
11671 (defun org-display-outline-path (&optional file current separator just-return-string)
11672 "Display the current outline path in the echo area.
11674 If FILE is non-nil, prepend the output with the file name.
11675 If CURRENT is non-nil, append the current heading to the output.
11676 SEPARATOR is passed through to `org-format-outline-path'. It separates
11677 the different parts of the path and defaults to \"/\".
11678 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11679 (interactive "P")
11680 (let* (case-fold-search
11681 (bfn (buffer-file-name (buffer-base-buffer)))
11682 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11683 res)
11684 (when current (setq path (append path
11685 (save-excursion
11686 (org-back-to-heading t)
11687 (when (looking-at org-complex-heading-regexp)
11688 (list (match-string 4)))))))
11689 (setq res
11690 (org-format-outline-path
11691 path
11692 (1- (frame-width))
11693 (and file bfn (concat (file-name-nondirectory bfn) separator))
11694 separator))
11695 (if just-return-string
11696 (org-no-properties res)
11697 (org-unlogged-message "%s" res))))
11699 (defvar org-refile-history nil
11700 "History for refiling operations.")
11702 (defvar org-after-refile-insert-hook nil
11703 "Hook run after `org-refile' has inserted its stuff at the new location.
11704 Note that this is still *before* the stuff will be removed from
11705 the *old* location.")
11707 (defvar org-capture-last-stored-marker)
11708 (defvar org-refile-keep nil
11709 "Non-nil means `org-refile' will copy instead of refile.")
11711 (defun org-copy ()
11712 "Like `org-refile', but copy."
11713 (interactive)
11714 (let ((org-refile-keep t))
11715 (funcall 'org-refile nil nil nil "Copy")))
11717 (defun org-refile (&optional arg default-buffer rfloc msg)
11718 "Move the entry or entries at point to another heading.
11720 The list of target headings is compiled using the information in
11721 `org-refile-targets', which see.
11723 At the target location, the entry is filed as a subitem of the
11724 target heading. Depending on `org-reverse-note-order', the new
11725 subitem will either be the first or the last subitem.
11727 If there is an active region, all entries in that region will be
11728 refiled. However, the region must fulfill the requirement that
11729 the first heading sets the top-level of the moved text.
11731 With a `\\[universal-argument]' ARG, the command will only visit the target \
11732 location
11733 and not actually move anything.
11735 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11736 location where the last
11737 refiling operation has put the subtree.
11739 With a numeric prefix argument of `2', refile to the running clock.
11741 With a numeric prefix argument of `3', emulate `org-refile-keep'
11742 being set to t and copy to the target location, don't move it.
11743 Beware that keeping refiled entries may result in duplicated ID
11744 properties.
11746 RFLOC can be a refile location obtained in a different way.
11748 MSG is a string to replace \"Refile\" in the default prompt with
11749 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11751 See also `org-refile-use-outline-path'.
11753 If you are using target caching (see `org-refile-use-cache'), you
11754 have to clear the target cache in order to find new targets.
11755 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11756 prefix argument (`C-u C-u C-u C-c C-w')."
11757 (interactive "P")
11758 (if (member arg '(0 (64)))
11759 (org-refile-cache-clear)
11760 (let* ((actionmsg (cond (msg msg)
11761 ((equal arg 3) "Refile (and keep)")
11762 (t "Refile")))
11763 (regionp (org-region-active-p))
11764 (region-start (and regionp (region-beginning)))
11765 (region-end (and regionp (region-end)))
11766 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11767 pos it nbuf file level reversed)
11768 (setq last-command nil)
11769 (when regionp
11770 (goto-char region-start)
11771 (or (bolp) (goto-char (point-at-bol)))
11772 (setq region-start (point))
11773 (unless (or (org-kill-is-subtree-p
11774 (buffer-substring region-start region-end))
11775 (prog1 org-refile-active-region-within-subtree
11776 (let ((s (point-at-eol)))
11777 (org-toggle-heading)
11778 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11779 (user-error "The region is not a (sequence of) subtree(s)")))
11780 (if (equal arg '(16))
11781 (org-refile-goto-last-stored)
11782 (when (or
11783 (and (equal arg 2)
11784 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11785 (prog1
11786 (setq it (list (or org-clock-heading "running clock")
11787 (buffer-file-name
11788 (marker-buffer org-clock-hd-marker))
11790 (marker-position org-clock-hd-marker)))
11791 (setq arg nil)))
11792 (setq it
11793 (or rfloc
11794 (let (heading-text)
11795 (save-excursion
11796 (unless (and arg (listp arg))
11797 (org-back-to-heading t)
11798 (setq heading-text
11799 (replace-regexp-in-string
11800 org-bracket-link-regexp
11801 "\\3"
11802 (or (nth 4 (org-heading-components))
11803 ""))))
11804 (org-refile-get-location
11805 (cond ((and arg (listp arg)) "Goto")
11806 (regionp (concat actionmsg " region to"))
11807 (t (concat actionmsg " subtree \""
11808 heading-text "\" to")))
11809 default-buffer
11810 (and (not (equal '(4) arg))
11811 org-refile-allow-creating-parent-nodes)))))))
11812 (setq file (nth 1 it)
11813 pos (nth 3 it))
11814 (when (and (not arg)
11816 (equal (buffer-file-name) file)
11817 (if regionp
11818 (and (>= pos region-start)
11819 (<= pos region-end))
11820 (and (>= pos (point))
11821 (< pos (save-excursion
11822 (org-end-of-subtree t t))))))
11823 (error "Cannot refile to position inside the tree or region"))
11824 (setq nbuf (or (find-buffer-visiting file)
11825 (find-file-noselect file)))
11826 (if (and arg (not (equal arg 3)))
11827 (progn
11828 (pop-to-buffer-same-window nbuf)
11829 (goto-char pos)
11830 (org-show-context 'org-goto))
11831 (if regionp
11832 (progn
11833 (org-kill-new (buffer-substring region-start region-end))
11834 (org-save-markers-in-region region-start region-end))
11835 (org-copy-subtree 1 nil t))
11836 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11837 (find-file-noselect file)))
11838 (setq reversed (org-notes-order-reversed-p))
11839 (org-with-wide-buffer
11840 (if pos
11841 (progn
11842 (goto-char pos)
11843 (setq level (org-get-valid-level (funcall outline-level) 1))
11844 (goto-char
11845 (if reversed
11846 (or (outline-next-heading) (point-max))
11847 (or (save-excursion (org-get-next-sibling))
11848 (org-end-of-subtree t t)
11849 (point-max)))))
11850 (setq level 1)
11851 (if (not reversed)
11852 (goto-char (point-max))
11853 (goto-char (point-min))
11854 (or (outline-next-heading) (goto-char (point-max)))))
11855 (unless (bolp) (newline))
11856 (org-paste-subtree level nil nil t)
11857 (when org-log-refile
11858 (org-add-log-setup 'refile nil nil org-log-refile)
11859 (unless (eq org-log-refile 'note)
11860 (save-excursion (org-add-log-note))))
11861 (and org-auto-align-tags
11862 (let ((org-loop-over-headlines-in-active-region nil))
11863 (org-set-tags nil t)))
11864 (let ((bookmark-name (plist-get org-bookmark-names-plist
11865 :last-refile)))
11866 (when bookmark-name
11867 (with-demoted-errors
11868 (bookmark-set bookmark-name))))
11869 ;; If we are refiling for capture, make sure that the
11870 ;; last-capture pointers point here
11871 (when (bound-and-true-p org-capture-is-refiling)
11872 (let ((bookmark-name (plist-get org-bookmark-names-plist
11873 :last-capture-marker)))
11874 (when bookmark-name
11875 (with-demoted-errors
11876 (bookmark-set bookmark-name))))
11877 (move-marker org-capture-last-stored-marker (point)))
11878 (when (fboundp 'deactivate-mark) (deactivate-mark))
11879 (run-hooks 'org-after-refile-insert-hook)))
11880 (unless org-refile-keep
11881 (if regionp
11882 (delete-region (point) (+ (point) (- region-end region-start)))
11883 (delete-region
11884 (and (org-back-to-heading t) (point))
11885 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11886 (when (featurep 'org-inlinetask)
11887 (org-inlinetask-remove-END-maybe))
11888 (setq org-markers-to-move nil)
11889 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11891 (defun org-refile-goto-last-stored ()
11892 "Go to the location where the last refile was stored."
11893 (interactive)
11894 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11895 (message "This is the location of the last refile"))
11897 (defun org-refile--get-location (refloc tbl)
11898 "When user refile to REFLOC, find the associated target in TBL.
11899 Also check `org-refile-target-table'."
11900 (car (delq
11902 (mapcar
11903 (lambda (r) (or (assoc r tbl)
11904 (assoc r org-refile-target-table)))
11905 (list (replace-regexp-in-string "/$" "" refloc)
11906 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11908 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11909 "Prompt the user for a refile location, using PROMPT.
11910 PROMPT should not be suffixed with a colon and a space, because
11911 this function appends the default value from
11912 `org-refile-history' automatically, if that is not empty."
11913 (let ((org-refile-targets org-refile-targets)
11914 (org-refile-use-outline-path org-refile-use-outline-path))
11915 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11916 (unless org-refile-target-table
11917 (user-error "No refile targets"))
11918 (let* ((cbuf (current-buffer))
11919 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11920 (cfunc (if (and org-refile-use-outline-path
11921 org-outline-path-complete-in-steps)
11922 #'org-olpath-completing-read
11923 #'completing-read))
11924 (extra (if org-refile-use-outline-path "/" ""))
11925 (cbnex (concat (buffer-name) extra))
11926 (filename (and cfn (expand-file-name cfn)))
11927 (tbl (mapcar
11928 (lambda (x)
11929 (if (and (not (member org-refile-use-outline-path
11930 '(file full-file-path)))
11931 (not (equal filename (nth 1 x))))
11932 (cons (concat (car x) extra " ("
11933 (file-name-nondirectory (nth 1 x)) ")")
11934 (cdr x))
11935 (cons (concat (car x) extra) (cdr x))))
11936 org-refile-target-table))
11937 (completion-ignore-case t)
11938 cdef
11939 (prompt (concat prompt
11940 (or (and (car org-refile-history)
11941 (concat " (default " (car org-refile-history) ")"))
11942 (and (assoc cbnex tbl) (setq cdef cbnex)
11943 (concat " (default " cbnex ")"))) ": "))
11944 pa answ parent-target child parent old-hist)
11945 (setq old-hist org-refile-history)
11946 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11947 nil 'org-refile-history (or cdef (car org-refile-history))))
11948 (if (setq pa (org-refile--get-location answ tbl))
11949 (progn
11950 (org-refile-check-position pa)
11951 (when (or (not org-refile-history)
11952 (not (eq old-hist org-refile-history))
11953 (not (equal (car pa) (car org-refile-history))))
11954 (setq org-refile-history
11955 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11956 org-refile-history
11957 (cdr org-refile-history))))
11958 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11959 (pop org-refile-history)))
11961 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11962 (progn
11963 (setq parent (match-string 1 answ)
11964 child (match-string 2 answ))
11965 (setq parent-target (org-refile--get-location parent tbl))
11966 (when (and parent-target
11967 (or (eq new-nodes t)
11968 (and (eq new-nodes 'confirm)
11969 (y-or-n-p (format "Create new node \"%s\"? "
11970 child)))))
11971 (org-refile-new-child parent-target child)))
11972 (user-error "Invalid target location")))))
11974 (declare-function org-string-nw-p "org-macs" (s))
11975 (defun org-refile-check-position (refile-pointer)
11976 "Check if the refile pointer matches the headline to which it points."
11977 (let* ((file (nth 1 refile-pointer))
11978 (re (nth 2 refile-pointer))
11979 (pos (nth 3 refile-pointer))
11980 buffer)
11981 (if (and (not (markerp pos)) (not file))
11982 (user-error "Please indicate a target file in the refile path")
11983 (when (org-string-nw-p re)
11984 (setq buffer (if (markerp pos)
11985 (marker-buffer pos)
11986 (or (find-buffer-visiting file)
11987 (find-file-noselect file))))
11988 (with-current-buffer buffer
11989 (org-with-wide-buffer
11990 (goto-char pos)
11991 (beginning-of-line 1)
11992 (unless (looking-at-p re)
11993 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11995 (defun org-refile-new-child (parent-target child)
11996 "Use refile target PARENT-TARGET to add new CHILD below it."
11997 (unless parent-target
11998 (error "Cannot find parent for new node"))
11999 (let ((file (nth 1 parent-target))
12000 (pos (nth 3 parent-target))
12001 level)
12002 (with-current-buffer (or (find-buffer-visiting file)
12003 (find-file-noselect file))
12004 (org-with-wide-buffer
12005 (if pos
12006 (goto-char pos)
12007 (goto-char (point-max))
12008 (unless (bolp) (newline)))
12009 (when (looking-at org-outline-regexp)
12010 (setq level (funcall outline-level))
12011 (org-end-of-subtree t t))
12012 (org-back-over-empty-lines)
12013 (insert "\n" (make-string
12014 (if pos (org-get-valid-level level 1) 1) ?*)
12015 " " child "\n")
12016 (beginning-of-line 0)
12017 (list (concat (car parent-target) "/" child) file "" (point))))))
12019 (defun org-olpath-completing-read (prompt collection &rest args)
12020 "Read an outline path like a file name."
12021 (let ((thetable collection))
12022 (apply #'completing-read
12023 prompt
12024 (lambda (string predicate &optional flag)
12025 (cond
12026 ((eq flag nil) (try-completion string thetable))
12027 ((eq flag t)
12028 (let ((l (length string)))
12029 (mapcar (lambda (x)
12030 (let ((r (substring x l))
12031 (f (if (string-match " ([^)]*)$" x)
12032 (match-string 0 x)
12033 "")))
12034 (if (string-match "/" r)
12035 (concat string (substring r 0 (match-end 0)) f)
12036 x)))
12037 (all-completions string thetable predicate))))
12038 ;; Exact match?
12039 ((eq flag 'lambda) (assoc string thetable))))
12040 args)))
12042 ;;;; Dynamic blocks
12044 (defun org-find-dblock (name)
12045 "Find the first dynamic block with name NAME in the buffer.
12046 If not found, stay at current position and return nil."
12047 (let ((case-fold-search t) pos)
12048 (save-excursion
12049 (goto-char (point-min))
12050 (setq pos (and (re-search-forward
12051 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12052 (match-beginning 0))))
12053 (when pos (goto-char pos))
12054 pos))
12056 (defun org-create-dblock (plist)
12057 "Create a dynamic block section, with parameters taken from PLIST.
12058 PLIST must contain a :name entry which is used as the name of the block."
12059 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12060 (end-of-line 1)
12061 (newline))
12062 (let ((col (current-column))
12063 (name (plist-get plist :name)))
12064 (insert "#+BEGIN: " name)
12065 (while plist
12066 (if (eq (car plist) :name)
12067 (setq plist (cddr plist))
12068 (insert " " (prin1-to-string (pop plist)))))
12069 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12070 (beginning-of-line -2)))
12072 (defun org-prepare-dblock ()
12073 "Prepare dynamic block for refresh.
12074 This empties the block, puts the cursor at the insert position and returns
12075 the property list including an extra property :name with the block name."
12076 (unless (looking-at org-dblock-start-re)
12077 (user-error "Not at a dynamic block"))
12078 (let* ((begdel (1+ (match-end 0)))
12079 (name (org-no-properties (match-string 1)))
12080 (params (append (list :name name)
12081 (read (concat "(" (match-string 3) ")")))))
12082 (save-excursion
12083 (beginning-of-line 1)
12084 (skip-chars-forward " \t")
12085 (setq params (plist-put params :indentation-column (current-column))))
12086 (unless (re-search-forward org-dblock-end-re nil t)
12087 (error "Dynamic block not terminated"))
12088 (setq params
12089 (append params
12090 (list :content (buffer-substring
12091 begdel (match-beginning 0)))))
12092 (delete-region begdel (match-beginning 0))
12093 (goto-char begdel)
12094 (open-line 1)
12095 params))
12097 (defun org-map-dblocks (&optional command)
12098 "Apply COMMAND to all dynamic blocks in the current buffer.
12099 If COMMAND is not given, use `org-update-dblock'."
12100 (let ((cmd (or command 'org-update-dblock)))
12101 (save-excursion
12102 (goto-char (point-min))
12103 (while (re-search-forward org-dblock-start-re nil t)
12104 (goto-char (match-beginning 0))
12105 (save-excursion
12106 (condition-case nil
12107 (funcall cmd)
12108 (error (message "Error during update of dynamic block"))))
12109 (unless (re-search-forward org-dblock-end-re nil t)
12110 (error "Dynamic block not terminated"))))))
12112 (defun org-dblock-update (&optional arg)
12113 "User command for updating dynamic blocks.
12114 Update the dynamic block at point. With prefix ARG, update all dynamic
12115 blocks in the buffer."
12116 (interactive "P")
12117 (if arg
12118 (org-update-all-dblocks)
12119 (or (looking-at org-dblock-start-re)
12120 (org-beginning-of-dblock))
12121 (org-update-dblock)))
12123 (defun org-update-dblock ()
12124 "Update the dynamic block at point.
12125 This means to empty the block, parse for parameters and then call
12126 the correct writing function."
12127 (interactive)
12128 (save-excursion
12129 (let* ((win (selected-window))
12130 (pos (point))
12131 (line (org-current-line))
12132 (params (org-prepare-dblock))
12133 (name (plist-get params :name))
12134 (indent (plist-get params :indentation-column))
12135 (cmd (intern (concat "org-dblock-write:" name))))
12136 (message "Updating dynamic block `%s' at line %d..." name line)
12137 (funcall cmd params)
12138 (message "Updating dynamic block `%s' at line %d...done" name line)
12139 (goto-char pos)
12140 (when (and indent (> indent 0))
12141 (setq indent (make-string indent ?\ ))
12142 (save-excursion
12143 (select-window win)
12144 (org-beginning-of-dblock)
12145 (forward-line 1)
12146 (while (not (looking-at org-dblock-end-re))
12147 (insert indent)
12148 (beginning-of-line 2))
12149 (when (looking-at org-dblock-end-re)
12150 (and (looking-at "[ \t]+")
12151 (replace-match ""))
12152 (insert indent)))))))
12154 (defun org-beginning-of-dblock ()
12155 "Find the beginning of the dynamic block at point.
12156 Error if there is no such block at point."
12157 (let ((pos (point))
12158 beg)
12159 (end-of-line 1)
12160 (if (and (re-search-backward org-dblock-start-re nil t)
12161 (setq beg (match-beginning 0))
12162 (re-search-forward org-dblock-end-re nil t)
12163 (> (match-end 0) pos))
12164 (goto-char beg)
12165 (goto-char pos)
12166 (error "Not in a dynamic block"))))
12168 (defun org-update-all-dblocks ()
12169 "Update all dynamic blocks in the buffer.
12170 This function can be used in a hook."
12171 (interactive)
12172 (when (derived-mode-p 'org-mode)
12173 (org-map-dblocks 'org-update-dblock)))
12176 ;;;; Completion
12178 (declare-function org-export-backend-options "ox" (cl-x) t)
12179 (defun org-get-export-keywords ()
12180 "Return a list of all currently understood export keywords.
12181 Export keywords include options, block names, attributes and
12182 keywords relative to each registered export back-end."
12183 (let (keywords)
12184 (dolist (backend
12185 (bound-and-true-p org-export-registered-backends)
12186 (delq nil keywords))
12187 ;; Back-end name (for keywords, like #+LATEX:)
12188 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12189 (dolist (option-entry (org-export-backend-options backend))
12190 ;; Back-end options.
12191 (push (nth 1 option-entry) keywords)))))
12193 (defconst org-options-keywords
12194 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12195 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12196 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12197 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12198 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12200 (defcustom org-structure-template-alist
12201 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12202 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12203 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12204 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12205 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12206 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12207 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12208 ("L" "#+LaTeX: ")
12209 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12210 ("H" "#+HTML: ")
12211 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12212 ("A" "#+ASCII: ")
12213 ("i" "#+INDEX: ?")
12214 ("I" "#+INCLUDE: %file ?"))
12215 "Structure completion elements.
12216 This is a list of abbreviation keys and values. The value gets inserted
12217 if you type `<' followed by the key and then press the completion key,
12218 usually `TAB'. %file will be replaced by a file name after prompting
12219 for the file using completion. The cursor will be placed at the position
12220 of the `?' in the template.
12221 There are two templates for each key, the first uses the original Org syntax,
12222 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12223 the default when the /org-mtags.el/ module has been loaded. See also the
12224 variable `org-mtags-prefer-muse-templates'."
12225 :group 'org-completion
12226 :type '(repeat
12227 (list
12228 (string :tag "Key")
12229 (string :tag "Template")))
12230 :version "26.1"
12231 :package-version '(Org . "8.3"))
12233 (defun org-try-structure-completion ()
12234 "Try to complete a structure template before point.
12235 This looks for strings like \"<e\" on an otherwise empty line and
12236 expands them."
12237 (let ((l (buffer-substring (point-at-bol) (point)))
12239 (when (and (looking-at "[ \t]*$")
12240 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12241 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12242 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12243 (match-beginning 1)) a)
12244 t)))
12246 (defun org-complete-expand-structure-template (start cell)
12247 "Expand a structure template."
12248 (let ((rpl (nth 1 cell))
12249 (ind ""))
12250 (delete-region start (point))
12251 (when (string-match "\\`[ \t]*#\\+" rpl)
12252 (cond
12253 ((bolp))
12254 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12255 (setq ind (buffer-substring (point-at-bol) (point))))
12256 (t (newline))))
12257 (setq start (point))
12258 (when (string-match "%file" rpl)
12259 (setq rpl (replace-match
12260 (concat
12261 "\""
12262 (save-match-data
12263 (abbreviate-file-name (read-file-name "Include file: ")))
12264 "\"")
12265 t t rpl)))
12266 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12267 (concat "\n" ind)))
12268 (insert rpl)
12269 (when (re-search-backward "\\?" start t) (delete-char 1))))
12271 ;;;; TODO, DEADLINE, Comments
12273 (defun org-toggle-comment ()
12274 "Change the COMMENT state of an entry."
12275 (interactive)
12276 (save-excursion
12277 (org-back-to-heading)
12278 (let ((case-fold-search nil))
12279 (looking-at org-complex-heading-regexp))
12280 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12281 (skip-chars-forward " \t")
12282 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12283 (if (org-in-commented-heading-p t)
12284 (delete-region (point)
12285 (progn (search-forward " " (line-end-position) 'move)
12286 (skip-chars-forward " \t")
12287 (point)))
12288 (insert org-comment-string)
12289 (unless (eolp) (insert " ")))))
12291 (defvar org-last-todo-state-is-todo nil
12292 "This is non-nil when the last TODO state change led to a TODO state.
12293 If the last change removed the TODO tag or switched to DONE, then
12294 this is nil.")
12296 (defvar org-setting-tags nil) ; dynamically skipped
12298 (defvar org-todo-setup-filter-hook nil
12299 "Hook for functions that pre-filter todo specs.
12300 Each function takes a todo spec and returns either nil or the spec
12301 transformed into canonical form." )
12303 (defvar org-todo-get-default-hook nil
12304 "Hook for functions that get a default item for todo.
12305 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12306 nil or a string to be used for the todo mark." )
12308 (defvar org-agenda-headline-snapshot-before-repeat)
12310 (defun org-current-effective-time ()
12311 "Return current time adjusted for `org-extend-today-until' variable."
12312 (let* ((ct (org-current-time))
12313 (dct (decode-time ct))
12314 (ct1
12315 (cond
12316 (org-use-last-clock-out-time-as-effective-time
12317 (or (org-clock-get-last-clock-out-time) ct))
12318 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12319 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12320 (t ct))))
12321 ct1))
12323 (defun org-todo-yesterday (&optional arg)
12324 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12325 (interactive "P")
12326 (if (eq major-mode 'org-agenda-mode)
12327 (apply 'org-agenda-todo-yesterday arg)
12328 (let* ((org-use-effective-time t)
12329 (hour (nth 2 (decode-time (org-current-time))))
12330 (org-extend-today-until (1+ hour)))
12331 (org-todo arg))))
12333 (defvar org-block-entry-blocking ""
12334 "First entry preventing the TODO state change.")
12336 (defun org-cancel-repeater ()
12337 "Cancel a repeater by setting its numeric value to zero."
12338 (interactive)
12339 (save-excursion
12340 (org-back-to-heading t)
12341 (let ((bound1 (point))
12342 (bound0 (save-excursion (outline-next-heading) (point))))
12343 (when (and (re-search-forward
12344 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12345 org-deadline-time-regexp "\\)\\|\\("
12346 org-ts-regexp "\\)")
12347 bound0 t)
12348 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12349 bound1 t))
12350 (replace-match "0" t nil nil 1)))))
12352 (defvar org-state)
12353 (defvar org-blocked-by-checkboxes)
12354 (defun org-todo (&optional arg)
12355 "Change the TODO state of an item.
12357 The state of an item is given by a keyword at the start of the heading,
12358 like
12359 *** TODO Write paper
12360 *** DONE Call mom
12362 The different keywords are specified in the variable `org-todo-keywords'.
12363 By default the available states are \"TODO\" and \"DONE\". So, for this
12364 example: when the item starts with TODO, it is changed to DONE.
12365 When it starts with DONE, the DONE is removed. And when neither TODO nor
12366 DONE are present, add TODO at the beginning of the heading.
12368 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12369 state.
12370 With numeric prefix ARG, switch to that state.
12371 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12372 next set of TODO \
12373 keywords (nextset).
12374 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12375 prefix, circumvent any state blocking.
12376 With a numeric prefix arg of 0, inhibit note taking for the change.
12377 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12379 When called through ELisp, arg is also interpreted in the following way:
12380 `none' -> empty state
12381 \"\" -> switch to empty state
12382 `done' -> switch to DONE
12383 `nextset' -> switch to the next set of keywords
12384 `previousset' -> switch to the previous set of keywords
12385 \"WAITING\" -> switch to the specified keyword, but only if it
12386 really is a member of `org-todo-keywords'."
12387 (interactive "P")
12388 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12389 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12390 'region-start-level 'region))
12391 org-loop-over-headlines-in-active-region)
12392 (org-map-entries
12393 `(org-todo ,arg)
12394 org-loop-over-headlines-in-active-region
12395 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12396 (when (equal arg '(16)) (setq arg 'nextset))
12397 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12398 (let ((org-blocker-hook org-blocker-hook)
12399 commentp
12400 case-fold-search)
12401 (when (equal arg '(64))
12402 (setq arg nil org-blocker-hook nil))
12403 (when (and org-blocker-hook
12404 (or org-inhibit-blocking
12405 (org-entry-get nil "NOBLOCKING")))
12406 (setq org-blocker-hook nil))
12407 (save-excursion
12408 (catch 'exit
12409 (org-back-to-heading t)
12410 (when (org-in-commented-heading-p t)
12411 (org-toggle-comment)
12412 (setq commentp t))
12413 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12414 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12415 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12416 (let* ((match-data (match-data))
12417 (startpos (point-at-bol))
12418 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12419 (org-log-done org-log-done)
12420 (org-log-repeat org-log-repeat)
12421 (org-todo-log-states org-todo-log-states)
12422 (org-inhibit-logging
12423 (if (equal arg 0)
12424 (progn (setq arg nil) 'note) org-inhibit-logging))
12425 (this (match-string 1))
12426 (hl-pos (match-beginning 0))
12427 (head (org-get-todo-sequence-head this))
12428 (ass (assoc head org-todo-kwd-alist))
12429 (interpret (nth 1 ass))
12430 (done-word (nth 3 ass))
12431 (final-done-word (nth 4 ass))
12432 (org-last-state (or this ""))
12433 (completion-ignore-case t)
12434 (member (member this org-todo-keywords-1))
12435 (tail (cdr member))
12436 (org-state (cond
12437 ((and org-todo-key-trigger
12438 (or (and (equal arg '(4))
12439 (eq org-use-fast-todo-selection 'prefix))
12440 (and (not arg) org-use-fast-todo-selection
12441 (not (eq org-use-fast-todo-selection
12442 'prefix)))))
12443 ;; Use fast selection.
12444 (org-fast-todo-selection))
12445 ((and (equal arg '(4))
12446 (or (not org-use-fast-todo-selection)
12447 (not org-todo-key-trigger)))
12448 ;; Read a state with completion.
12449 (completing-read
12450 "State: " (mapcar #'list org-todo-keywords-1)
12451 nil t))
12452 ((eq arg 'right)
12453 (if this
12454 (if tail (car tail) nil)
12455 (car org-todo-keywords-1)))
12456 ((eq arg 'left)
12457 (unless (equal member org-todo-keywords-1)
12458 (if this
12459 (nth (- (length org-todo-keywords-1)
12460 (length tail) 2)
12461 org-todo-keywords-1)
12462 (org-last org-todo-keywords-1))))
12463 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12464 (setq arg nil))) ;hack to fall back to cycling
12465 (arg
12466 ;; User or caller requests a specific state.
12467 (cond
12468 ((equal arg "") nil)
12469 ((eq arg 'none) nil)
12470 ((eq arg 'done) (or done-word (car org-done-keywords)))
12471 ((eq arg 'nextset)
12472 (or (car (cdr (member head org-todo-heads)))
12473 (car org-todo-heads)))
12474 ((eq arg 'previousset)
12475 (let ((org-todo-heads (reverse org-todo-heads)))
12476 (or (car (cdr (member head org-todo-heads)))
12477 (car org-todo-heads))))
12478 ((car (member arg org-todo-keywords-1)))
12479 ((stringp arg)
12480 (user-error "State `%s' not valid in this file" arg))
12481 ((nth (1- (prefix-numeric-value arg))
12482 org-todo-keywords-1))))
12483 ((null member) (or head (car org-todo-keywords-1)))
12484 ((equal this final-done-word) nil) ;-> make empty
12485 ((null tail) nil) ;-> first entry
12486 ((memq interpret '(type priority))
12487 (if (eq this-command last-command)
12488 (car tail)
12489 (if (> (length tail) 0)
12490 (or done-word (car org-done-keywords))
12491 nil)))
12493 (car tail))))
12494 (org-state (or
12495 (run-hook-with-args-until-success
12496 'org-todo-get-default-hook org-state org-last-state)
12497 org-state))
12498 (next (if org-state (concat " " org-state " ") " "))
12499 (change-plist (list :type 'todo-state-change :from this :to org-state
12500 :position startpos))
12501 dolog now-done-p)
12502 (when org-blocker-hook
12503 (let (org-blocked-by-checkboxes block-reason)
12504 (setq org-last-todo-state-is-todo
12505 (not (member this org-done-keywords)))
12506 (unless (save-excursion
12507 (save-match-data
12508 (org-with-wide-buffer
12509 (run-hook-with-args-until-failure
12510 'org-blocker-hook change-plist))))
12511 (setq block-reason (if org-blocked-by-checkboxes
12512 "contained checkboxes"
12513 (format "\"%s\"" org-block-entry-blocking)))
12514 (if (called-interactively-p 'interactive)
12515 (user-error "TODO state change from %s to %s blocked (by %s)"
12516 this org-state block-reason)
12517 ;; Fail silently.
12518 (message "TODO state change from %s to %s blocked (by %s)"
12519 this org-state block-reason)
12520 (throw 'exit nil)))))
12521 (store-match-data match-data)
12522 (replace-match next t t)
12523 (cond ((equal this org-state)
12524 (message "TODO state was already %s" (org-trim next)))
12525 ((pos-visible-in-window-p hl-pos)
12526 (message "TODO state changed to %s" (org-trim next))))
12527 (unless head
12528 (setq head (org-get-todo-sequence-head org-state)
12529 ass (assoc head org-todo-kwd-alist)
12530 interpret (nth 1 ass)
12531 done-word (nth 3 ass)
12532 final-done-word (nth 4 ass)))
12533 (when (memq arg '(nextset previousset))
12534 (message "Keyword-Set %d/%d: %s"
12535 (- (length org-todo-sets) -1
12536 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12537 (length org-todo-sets)
12538 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12539 (setq org-last-todo-state-is-todo
12540 (not (member org-state org-done-keywords)))
12541 (setq now-done-p (and (member org-state org-done-keywords)
12542 (not (member this org-done-keywords))))
12543 (and logging (org-local-logging logging))
12544 (when (and (or org-todo-log-states org-log-done)
12545 (not (eq org-inhibit-logging t))
12546 (not (memq arg '(nextset previousset))))
12547 ;; We need to look at recording a time and note.
12548 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12549 (nth 2 (assoc this org-todo-log-states))))
12550 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12551 (setq dolog 'time))
12552 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12553 (and org-state
12554 (member org-state org-not-done-keywords)
12555 (not (member this org-not-done-keywords))))
12556 ;; This is now a todo state and was not one before
12557 ;; If there was a CLOSED time stamp, get rid of it.
12558 (org-add-planning-info nil nil 'closed))
12559 (when (and now-done-p org-log-done)
12560 ;; It is now done, and it was not done before.
12561 (org-add-planning-info 'closed (org-current-effective-time))
12562 (when (and (not dolog) (eq 'note org-log-done))
12563 (org-add-log-setup 'done org-state this 'note)))
12564 (when (and org-state dolog)
12565 ;; This is a non-nil state, and we need to log it.
12566 (org-add-log-setup 'state org-state this dolog)))
12567 ;; Fixup tag positioning.
12568 (org-todo-trigger-tag-changes org-state)
12569 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12570 (when org-provide-todo-statistics
12571 (org-update-parent-todo-statistics))
12572 (run-hooks 'org-after-todo-state-change-hook)
12573 (when (and arg (not (member org-state org-done-keywords)))
12574 (setq head (org-get-todo-sequence-head org-state)))
12575 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12576 ;; Do we need to trigger a repeat?
12577 (when now-done-p
12578 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12579 ;; This is for the agenda, take a snapshot of the headline.
12580 (save-match-data
12581 (setq org-agenda-headline-snapshot-before-repeat
12582 (org-get-heading))))
12583 (org-auto-repeat-maybe org-state))
12584 ;; Fixup cursor location if close to the keyword.
12585 (when (and (outline-on-heading-p)
12586 (not (bolp))
12587 (save-excursion (beginning-of-line 1)
12588 (looking-at org-todo-line-regexp))
12589 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12590 (goto-char (or (match-end 2) (match-end 1)))
12591 (and (looking-at " ") (just-one-space)))
12592 (when org-trigger-hook
12593 (save-excursion
12594 (run-hook-with-args 'org-trigger-hook change-plist)))
12595 (when commentp (org-toggle-comment))))))))
12597 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12598 "Block turning an entry into a TODO, using the hierarchy.
12599 This checks whether the current task should be blocked from state
12600 changes. Such blocking occurs when:
12602 1. The task has children which are not all in a completed state.
12604 2. A task has a parent with the property :ORDERED:, and there
12605 are siblings prior to the current task with incomplete
12606 status.
12608 3. The parent of the task is blocked because it has siblings that should
12609 be done first, or is child of a block grandparent TODO entry."
12611 (if (not org-enforce-todo-dependencies)
12612 t ; if locally turned off don't block
12613 (catch 'dont-block
12614 ;; If this is not a todo state change, or if this entry is already DONE,
12615 ;; do not block
12616 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12617 (member (plist-get change-plist :from)
12618 (cons 'done org-done-keywords))
12619 (member (plist-get change-plist :to)
12620 (cons 'todo org-not-done-keywords))
12621 (not (plist-get change-plist :to)))
12622 (throw 'dont-block t))
12623 ;; If this task has children, and any are undone, it's blocked
12624 (save-excursion
12625 (org-back-to-heading t)
12626 (let ((this-level (funcall outline-level)))
12627 (outline-next-heading)
12628 (let ((child-level (funcall outline-level)))
12629 (while (and (not (eobp))
12630 (> child-level this-level))
12631 ;; this todo has children, check whether they are all
12632 ;; completed
12633 (when (and (not (org-entry-is-done-p))
12634 (org-entry-is-todo-p))
12635 (setq org-block-entry-blocking (org-get-heading))
12636 (throw 'dont-block nil))
12637 (outline-next-heading)
12638 (setq child-level (funcall outline-level))))))
12639 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12640 ;; any previous siblings are undone, it's blocked
12641 (save-excursion
12642 (org-back-to-heading t)
12643 (let* ((pos (point))
12644 (parent-pos (and (org-up-heading-safe) (point)))
12645 (case-fold-search nil))
12646 (unless parent-pos (throw 'dont-block t)) ; no parent
12647 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12648 (forward-line 1)
12649 (re-search-forward org-not-done-heading-regexp pos t))
12650 (setq org-block-entry-blocking (match-string 0))
12651 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12652 ;; Search further up the hierarchy, to see if an ancestor is blocked
12653 (while t
12654 (goto-char parent-pos)
12655 (unless (looking-at org-not-done-heading-regexp)
12656 (throw 'dont-block t)) ; do not block, parent is not a TODO
12657 (setq pos (point))
12658 (setq parent-pos (and (org-up-heading-safe) (point)))
12659 (unless parent-pos (throw 'dont-block t)) ; no parent
12660 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12661 (forward-line 1)
12662 (re-search-forward org-not-done-heading-regexp pos t)
12663 (setq org-block-entry-blocking (org-get-heading)))
12664 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12666 (defcustom org-track-ordered-property-with-tag nil
12667 "Should the ORDERED property also be shown as a tag?
12668 The ORDERED property decides if an entry should require subtasks to be
12669 completed in sequence. Since a property is not very visible, setting
12670 this option means that toggling the ORDERED property with the command
12671 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12672 not relevant for the behavior, but it makes things more visible.
12674 Note that toggling the tag with tags commands will not change the property
12675 and therefore not influence behavior!
12677 This can be t, meaning the tag ORDERED should be used, It can also be a
12678 string to select a different tag for this task."
12679 :group 'org-todo
12680 :type '(choice
12681 (const :tag "No tracking" nil)
12682 (const :tag "Track with ORDERED tag" t)
12683 (string :tag "Use other tag")))
12685 (defun org-toggle-ordered-property ()
12686 "Toggle the ORDERED property of the current entry.
12687 For better visibility, you can track the value of this property with a tag.
12688 See variable `org-track-ordered-property-with-tag'."
12689 (interactive)
12690 (let* ((t1 org-track-ordered-property-with-tag)
12691 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12692 (save-excursion
12693 (org-back-to-heading)
12694 (if (org-entry-get nil "ORDERED")
12695 (progn
12696 (org-delete-property "ORDERED")
12697 (and tag (org-toggle-tag tag 'off))
12698 (message "Subtasks can be completed in arbitrary order"))
12699 (org-entry-put nil "ORDERED" "t")
12700 (and tag (org-toggle-tag tag 'on))
12701 (message "Subtasks must be completed in sequence")))))
12703 (defun org-block-todo-from-checkboxes (change-plist)
12704 "Block turning an entry into a TODO, using checkboxes.
12705 This checks whether the current task should be blocked from state
12706 changes because there are unchecked boxes in this entry."
12707 (if (not org-enforce-todo-checkbox-dependencies)
12708 t ; if locally turned off don't block
12709 (catch 'dont-block
12710 ;; If this is not a todo state change, or if this entry is already DONE,
12711 ;; do not block
12712 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12713 (member (plist-get change-plist :from)
12714 (cons 'done org-done-keywords))
12715 (member (plist-get change-plist :to)
12716 (cons 'todo org-not-done-keywords))
12717 (not (plist-get change-plist :to)))
12718 (throw 'dont-block t))
12719 ;; If this task has checkboxes that are not checked, it's blocked
12720 (save-excursion
12721 (org-back-to-heading t)
12722 (let ((beg (point)) end)
12723 (outline-next-heading)
12724 (setq end (point))
12725 (goto-char beg)
12726 (when (org-list-search-forward
12727 (concat (org-item-beginning-re)
12728 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12729 "\\[[- ]\\]")
12730 end t)
12731 (when (boundp 'org-blocked-by-checkboxes)
12732 (setq org-blocked-by-checkboxes t))
12733 (throw 'dont-block nil))))
12734 t))) ; do not block
12736 (defun org-entry-blocked-p ()
12737 "Non-nil if entry at point is blocked."
12738 (and (not (org-entry-get nil "NOBLOCKING"))
12739 (member (org-entry-get nil "TODO") org-not-done-keywords)
12740 (not (run-hook-with-args-until-failure
12741 'org-blocker-hook
12742 (list :type 'todo-state-change
12743 :position (point)
12744 :from 'todo
12745 :to 'done)))))
12747 (defun org-update-statistics-cookies (all)
12748 "Update the statistics cookie, either from TODO or from checkboxes.
12749 This should be called with the cursor in a line with a statistics
12750 cookie. When called with a \\[universal-argument] prefix, update
12751 all statistics cookies in the buffer."
12752 (interactive "P")
12753 (if all
12754 (progn
12755 (org-update-checkbox-count 'all)
12756 (org-map-entries 'org-update-parent-todo-statistics))
12757 (if (not (org-at-heading-p))
12758 (org-update-checkbox-count)
12759 (let ((pos (point-marker))
12760 end l1 l2)
12761 (ignore-errors (org-back-to-heading t))
12762 (if (not (org-at-heading-p))
12763 (org-update-checkbox-count)
12764 (setq l1 (org-outline-level))
12765 (setq end (save-excursion
12766 (outline-next-heading)
12767 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12768 (point)))
12769 (if (and (save-excursion
12770 (re-search-forward
12771 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12772 (not (save-excursion (re-search-forward
12773 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12774 (org-update-checkbox-count)
12775 (if (and l2 (> l2 l1))
12776 (progn
12777 (goto-char end)
12778 (org-update-parent-todo-statistics))
12779 (goto-char pos)
12780 (beginning-of-line 1)
12781 (while (re-search-forward
12782 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12783 (point-at-eol) t)
12784 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12785 (goto-char pos)
12786 (move-marker pos nil)))))
12788 (defvar org-entry-property-inherited-from) ;; defined below
12789 (defun org-update-parent-todo-statistics ()
12790 "Update any statistics cookie in the parent of the current headline.
12791 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12792 the entire subtree and this will travel up the hierarchy and update
12793 statistics everywhere."
12794 (let* ((prop (save-excursion (org-up-heading-safe)
12795 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12796 (recursive (or (not org-hierarchical-todo-statistics)
12797 (and prop (string-match "\\<recursive\\>" prop))))
12798 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12800 (first t)
12801 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12802 level ltoggle l1 new ndel
12803 (cnt-all 0) (cnt-done 0) is-percent kwd
12804 checkbox-beg cookie-present)
12805 (catch 'exit
12806 (save-excursion
12807 (beginning-of-line 1)
12808 (setq ltoggle (funcall outline-level))
12809 ;; Three situations are to consider:
12811 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12812 ;; to the top-level ancestor on the headline;
12814 ;; 2. If parent has "recursive" property, repeat up to the
12815 ;; headline setting that property, taking inheritance into
12816 ;; account;
12818 ;; 3. Else, move up to direct parent and proceed only once.
12819 (while (and (setq level (org-up-heading-safe))
12820 (or recursive first)
12821 (>= (point) lim))
12822 (setq first nil cookie-present nil)
12823 (unless (and level
12824 (not (string-match
12825 "\\<checkbox\\>"
12826 (downcase (or (org-entry-get nil "COOKIE_DATA")
12827 "")))))
12828 (throw 'exit nil))
12829 (while (re-search-forward box-re (point-at-eol) t)
12830 (setq cnt-all 0 cnt-done 0 cookie-present t)
12831 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12832 (save-match-data
12833 (unless (outline-next-heading) (throw 'exit nil))
12834 (while (and (looking-at org-complex-heading-regexp)
12835 (> (setq l1 (length (match-string 1))) level))
12836 (setq kwd (and (or recursive (= l1 ltoggle))
12837 (match-string 2)))
12838 (if (or (eq org-provide-todo-statistics 'all-headlines)
12839 (and (eq org-provide-todo-statistics t)
12840 (or (member kwd org-done-keywords)))
12841 (and (listp org-provide-todo-statistics)
12842 (stringp (car org-provide-todo-statistics))
12843 (or (member kwd org-provide-todo-statistics)
12844 (member kwd org-done-keywords)))
12845 (and (listp org-provide-todo-statistics)
12846 (listp (car org-provide-todo-statistics))
12847 (or (member kwd (car org-provide-todo-statistics))
12848 (and (member kwd org-done-keywords)
12849 (member kwd (cadr org-provide-todo-statistics))))))
12850 (setq cnt-all (1+ cnt-all))
12851 (and (eq org-provide-todo-statistics t)
12853 (setq cnt-all (1+ cnt-all))))
12854 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12855 (member kwd org-done-keywords))
12856 (and (listp org-provide-todo-statistics)
12857 (listp (car org-provide-todo-statistics))
12858 (member kwd org-done-keywords)
12859 (member kwd (cadr org-provide-todo-statistics)))
12860 (and (listp org-provide-todo-statistics)
12861 (stringp (car org-provide-todo-statistics))
12862 (member kwd org-done-keywords)))
12863 (setq cnt-done (1+ cnt-done)))
12864 (outline-next-heading)))
12865 (setq new
12866 (if is-percent
12867 (format "[%d%%]" (floor (* 100.0 cnt-done)
12868 (max 1 cnt-all)))
12869 (format "[%d/%d]" cnt-done cnt-all))
12870 ndel (- (match-end 0) checkbox-beg))
12871 (goto-char checkbox-beg)
12872 (insert new)
12873 (delete-region (point) (+ (point) ndel))
12874 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12875 (when cookie-present
12876 (run-hook-with-args 'org-after-todo-statistics-hook
12877 cnt-done (- cnt-all cnt-done))))))
12878 (run-hooks 'org-todo-statistics-hook)))
12880 (defvar org-after-todo-statistics-hook nil
12881 "Hook that is called after a TODO statistics cookie has been updated.
12882 Each function is called with two arguments: the number of not-done entries
12883 and the number of done entries.
12885 For example, the following function, when added to this hook, will switch
12886 an entry to DONE when all children are done, and back to TODO when new
12887 entries are set to a TODO status. Note that this hook is only called
12888 when there is a statistics cookie in the headline!
12890 (defun org-summary-todo (n-done n-not-done)
12891 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12892 (let (org-log-done org-log-states) ; turn off logging
12893 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12896 (defvar org-todo-statistics-hook nil
12897 "Hook that is run whenever Org thinks TODO statistics should be updated.
12898 This hook runs even if there is no statistics cookie present, in which case
12899 `org-after-todo-statistics-hook' would not run.")
12901 (defun org-todo-trigger-tag-changes (state)
12902 "Apply the changes defined in `org-todo-state-tags-triggers'."
12903 (let ((l org-todo-state-tags-triggers)
12904 changes)
12905 (when (or (not state) (equal state ""))
12906 (setq changes (append changes (cdr (assoc "" l)))))
12907 (when (and (stringp state) (> (length state) 0))
12908 (setq changes (append changes (cdr (assoc state l)))))
12909 (when (member state org-not-done-keywords)
12910 (setq changes (append changes (cdr (assq 'todo l)))))
12911 (when (member state org-done-keywords)
12912 (setq changes (append changes (cdr (assq 'done l)))))
12913 (dolist (c changes)
12914 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12916 (defun org-local-logging (value)
12917 "Get logging settings from a property VALUE."
12918 ;; Directly set the variables, they are already local.
12919 (setq org-log-done nil
12920 org-log-repeat nil
12921 org-todo-log-states nil)
12922 (dolist (w (org-split-string value))
12923 (let (a)
12924 (cond
12925 ((setq a (assoc w org-startup-options))
12926 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12927 (set (nth 1 a) (nth 2 a))))
12928 ((setq a (org-extract-log-state-settings w))
12929 (and (member (car a) org-todo-keywords-1)
12930 (push a org-todo-log-states)))))))
12932 (defun org-get-todo-sequence-head (kwd)
12933 "Return the head of the TODO sequence to which KWD belongs.
12934 If KWD is not set, check if there is a text property remembering the
12935 right sequence."
12936 (let (p)
12937 (cond
12938 ((not kwd)
12939 (or (get-text-property (point-at-bol) 'org-todo-head)
12940 (progn
12941 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12942 nil (point-at-eol)))
12943 (get-text-property p 'org-todo-head))))
12944 ((not (member kwd org-todo-keywords-1))
12945 (car org-todo-keywords-1))
12946 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12948 (defun org-fast-todo-selection ()
12949 "Fast TODO keyword selection with single keys.
12950 Returns the new TODO keyword, or nil if no state change should occur."
12951 (let* ((fulltable org-todo-key-alist)
12952 (done-keywords org-done-keywords) ;; needed for the faces.
12953 (maxlen (apply 'max (mapcar
12954 (lambda (x)
12955 (if (stringp (car x)) (string-width (car x)) 0))
12956 fulltable)))
12957 (expert nil)
12958 (fwidth (+ maxlen 3 1 3))
12959 (ncol (/ (- (window-width) 4) fwidth))
12960 tg cnt e c tbl
12961 groups ingroup)
12962 (save-excursion
12963 (save-window-excursion
12964 (if expert
12965 (set-buffer (get-buffer-create " *Org todo*"))
12966 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12967 (erase-buffer)
12968 (setq-local org-done-keywords done-keywords)
12969 (setq tbl fulltable cnt 0)
12970 (while (setq e (pop tbl))
12971 (cond
12972 ((equal e '(:startgroup))
12973 (push '() groups) (setq ingroup t)
12974 (unless (= cnt 0)
12975 (setq cnt 0)
12976 (insert "\n"))
12977 (insert "{ "))
12978 ((equal e '(:endgroup))
12979 (setq ingroup nil cnt 0)
12980 (insert "}\n"))
12981 ((equal e '(:newline))
12982 (unless (= cnt 0)
12983 (setq cnt 0)
12984 (insert "\n")
12985 (setq e (car tbl))
12986 (while (equal (car tbl) '(:newline))
12987 (insert "\n")
12988 (setq tbl (cdr tbl)))))
12990 (setq tg (car e) c (cdr e))
12991 (when ingroup (push tg (car groups)))
12992 (setq tg (org-add-props tg nil 'face
12993 (org-get-todo-face tg)))
12994 (when (and (= cnt 0) (not ingroup)) (insert " "))
12995 (insert "[" c "] " tg (make-string
12996 (- fwidth 4 (length tg)) ?\ ))
12997 (when (= (setq cnt (1+ cnt)) ncol)
12998 (insert "\n")
12999 (when ingroup (insert " "))
13000 (setq cnt 0)))))
13001 (insert "\n")
13002 (goto-char (point-min))
13003 (unless expert (org-fit-window-to-buffer))
13004 (message "[a-z..]:Set [SPC]:clear")
13005 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13006 (cond
13007 ((or (= c ?\C-g)
13008 (and (= c ?q) (not (rassoc c fulltable))))
13009 (setq quit-flag t))
13010 ((= c ?\ ) nil)
13011 ((setq e (rassoc c fulltable) tg (car e))
13013 (t (setq quit-flag t)))))))
13015 (defun org-entry-is-todo-p ()
13016 (member (org-get-todo-state) org-not-done-keywords))
13018 (defun org-entry-is-done-p ()
13019 (member (org-get-todo-state) org-done-keywords))
13021 (defun org-get-todo-state ()
13022 "Return the TODO keyword of the current subtree."
13023 (save-excursion
13024 (org-back-to-heading t)
13025 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13026 (match-end 2)
13027 (match-string 2))))
13029 (defun org-at-date-range-p (&optional inactive-ok)
13030 "Non-nil if point is inside a date range.
13032 When optional argument INACTIVE-OK is non-nil, also consider
13033 inactive time ranges.
13035 When this function returns a non-nil value, match data is set
13036 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13037 on INACTIVE-OK."
13038 (interactive)
13039 (save-excursion
13040 (catch 'exit
13041 (let ((pos (point)))
13042 (skip-chars-backward "^[<\r\n")
13043 (skip-chars-backward "<[")
13044 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13045 (>= (match-end 0) pos)
13046 (throw 'exit t))
13047 (skip-chars-backward "^<[\r\n")
13048 (skip-chars-backward "<[")
13049 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13050 (>= (match-end 0) pos)
13051 (throw 'exit t)))
13052 nil)))
13054 (defun org-get-repeat (&optional timestamp)
13055 "Check if there is a time-stamp with repeater in this entry.
13057 Return the repeater, as a string, or nil. Also return nil when
13058 this function is called before first heading.
13060 When optional argument TIMESTAMP is a string, extract the
13061 repeater from there instead."
13062 (save-match-data
13063 (cond (timestamp
13064 (and (string-match org-repeat-re timestamp)
13065 (match-string-no-properties 1 timestamp)))
13066 ((org-before-first-heading-p) nil)
13068 (save-excursion
13069 (org-back-to-heading t)
13070 (let ((end (org-entry-end-position)))
13071 (catch :repeat
13072 (while (re-search-forward org-repeat-re end t)
13073 (when (save-match-data (org-at-timestamp-p 'agenda))
13074 (throw :repeat (match-string-no-properties 1)))))))))))
13076 (defvar org-last-changed-timestamp)
13077 (defvar org-last-inserted-timestamp)
13078 (defvar org-log-post-message)
13079 (defvar org-log-note-purpose)
13080 (defvar org-log-note-how nil)
13081 (defvar org-log-note-extra)
13082 (defun org-auto-repeat-maybe (done-word)
13083 "Check if the current headline contains a repeated time-stamp.
13085 If yes, set TODO state back to what it was and change the base date
13086 of repeating deadline/scheduled time stamps to new date.
13088 This function is run automatically after each state change to a DONE state."
13089 (let* ((repeat (org-get-repeat))
13090 (aa (assoc org-last-state org-todo-kwd-alist))
13091 (interpret (nth 1 aa))
13092 (head (nth 2 aa))
13093 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13094 (msg "Entry repeats: ")
13095 (org-log-done nil)
13096 (org-todo-log-states nil)
13097 (end (copy-marker (org-entry-end-position))))
13098 (unwind-protect
13099 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13100 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13101 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13102 org-todo-repeat-to-state)))
13103 (org-todo (cond
13104 ((and to-state (member to-state org-todo-keywords-1))
13105 to-state)
13106 ((eq interpret 'type) org-last-state)
13107 (head)
13108 (t 'none))))
13109 (org-back-to-heading t)
13110 (org-add-planning-info nil nil 'closed)
13111 ;; When `org-log-repeat' is non-nil or entry contains
13112 ;; a clock, set LAST_REPEAT property.
13113 (when (or org-log-repeat
13114 (catch :clock
13115 (while (re-search-forward org-clock-line-re end t)
13116 (when (org-at-clock-log-p) (throw :clock t)))))
13117 (org-entry-put nil "LAST_REPEAT" (format-time-string
13118 (org-time-stamp-format t t)
13119 (current-time))))
13120 (when org-log-repeat
13121 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13122 (memq 'org-add-log-note post-command-hook))
13123 ;; We are already setup for some record.
13124 (when (eq org-log-repeat 'note)
13125 ;; Make sure we take a note, not only a time stamp.
13126 (setq org-log-note-how 'note))
13127 ;; Set up for taking a record.
13128 (org-add-log-setup 'state
13129 (or done-word (car org-done-keywords))
13130 org-last-state
13131 org-log-repeat)))
13132 (let ((planning-re (regexp-opt
13133 (list org-scheduled-string org-deadline-string))))
13134 (while (re-search-forward org-ts-regexp end t)
13135 (let* ((ts (match-string 0))
13136 (planning? (org-at-planning-p))
13137 (type (if (not planning?) "Plain:"
13138 (save-excursion
13139 (re-search-backward
13140 planning-re (line-beginning-position) t)
13141 (match-string 0)))))
13142 (cond
13143 ;; Ignore fake time-stamps (e.g., within comments).
13144 ((not (org-at-timestamp-p 'agenda)))
13145 ;; Time-stamps without a repeater are usually
13146 ;; skipped. However, a SCHEDULED time-stamp without
13147 ;; one is removed, as they are no longer relevant.
13148 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13149 ts))
13150 (when (equal type org-scheduled-string)
13151 (org-remove-timestamp-with-keyword type)))
13153 (let ((n (string-to-number (match-string 2 ts)))
13154 (what (match-string 3 ts)))
13155 (when (equal what "w") (setq n (* n 7) what "d"))
13156 (when (and (equal what "h")
13157 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13158 ts)))
13159 (user-error
13160 "Cannot repeat in Repeat in %d hour(s) because no hour \
13161 has been set"
13163 ;; Preparation, see if we need to modify the start
13164 ;; date for the change.
13165 (when (match-end 1)
13166 (let ((time (save-match-data
13167 (org-time-string-to-time ts))))
13168 (cond
13169 ((equal (match-string 1 ts) ".")
13170 ;; Shift starting date to today
13171 (org-timestamp-change
13172 (- (org-today) (time-to-days time))
13173 'day))
13174 ((equal (match-string 1 ts) "+")
13175 (let ((nshiftmax 10)
13176 (nshift 0))
13177 (while (or (= nshift 0)
13178 (not (time-less-p (current-time) time)))
13179 (when (= (cl-incf nshift) nshiftmax)
13180 (or (y-or-n-p
13181 (format "%d repeater intervals were not \
13182 enough to shift date past today. Continue? "
13183 nshift))
13184 (user-error "Abort")))
13185 (org-timestamp-change n (cdr (assoc what whata)))
13186 (org-in-regexp org-ts-regexp3)
13187 (setq ts (match-string 1))
13188 (setq time
13189 (save-match-data
13190 (org-time-string-to-time ts)))))
13191 (org-timestamp-change (- n) (cdr (assoc what whata)))
13192 ;; Rematch, so that we have everything in place
13193 ;; for the real shift.
13194 (org-in-regexp org-ts-regexp3)
13195 (setq ts (match-string 1))
13196 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13197 ts)))))
13198 (save-excursion
13199 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13200 (setq msg
13201 (concat
13202 msg type " " org-last-changed-timestamp " "))))))))
13203 (setq org-log-post-message msg)
13204 (message "%s" msg))
13205 (set-marker end nil))))
13207 (defun org-show-todo-tree (arg)
13208 "Make a compact tree which shows all headlines marked with TODO.
13209 The tree will show the lines where the regexp matches, and all higher
13210 headlines above the match.
13211 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13212 With a numeric prefix N, construct a sparse tree for the Nth element
13213 of `org-todo-keywords-1'."
13214 (interactive "P")
13215 (let ((case-fold-search nil)
13216 (kwd-re
13217 (cond ((null arg) org-not-done-regexp)
13218 ((equal arg '(4))
13219 (let ((kwd
13220 (completing-read "Keyword (or KWD1|KWD2|...): "
13221 (mapcar #'list org-todo-keywords-1))))
13222 (concat "\\("
13223 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13224 "\\)\\>")))
13225 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13226 (regexp-quote (nth (1- (prefix-numeric-value arg))
13227 org-todo-keywords-1)))
13228 (t (user-error "Invalid prefix argument: %s" arg)))))
13229 (message "%d TODO entries found"
13230 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13232 (defun org--deadline-or-schedule (arg type time)
13233 "Insert DEADLINE or SCHEDULE information in current entry.
13234 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13235 `org-schedule' for information about ARG and TIME arguments."
13236 (let* ((deadline? (eq type 'deadline))
13237 (keyword (if deadline? org-deadline-string org-scheduled-string))
13238 (log (if deadline? org-log-redeadline org-log-reschedule))
13239 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13240 (old-date-time (and old-date (org-time-string-to-time old-date)))
13241 ;; Save repeater cookie from either TIME or current scheduled
13242 ;; time stamp. We are going to insert it back at the end of
13243 ;; the process.
13244 (repeater (or (and (org-string-nw-p time)
13245 ;; We use `org-repeat-re' because we need
13246 ;; to tell the difference between a real
13247 ;; repeater and a time delta, e.g. "+2d".
13248 (string-match org-repeat-re time)
13249 (match-string 1 time))
13250 (and (org-string-nw-p old-date)
13251 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13252 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13253 old-date)
13254 (match-string 1 old-date)))))
13255 (pcase arg
13256 (`(4)
13257 (when (and old-date log)
13258 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13259 nil old-date log))
13260 (org-remove-timestamp-with-keyword keyword)
13261 (message (if deadline? "Item no longer has a deadline."
13262 "Item is no longer scheduled.")))
13263 (`(16)
13264 (save-excursion
13265 (org-back-to-heading t)
13266 (let ((regexp (if deadline? org-deadline-time-regexp
13267 org-scheduled-time-regexp)))
13268 (if (not (re-search-forward regexp (line-end-position 2) t))
13269 (user-error (if deadline? "No deadline information to update"
13270 "No scheduled information to update"))
13271 (let* ((rpl0 (match-string 1))
13272 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13273 (msg (if deadline? "Warn starting from" "Delay until")))
13274 (replace-match
13275 (concat keyword
13276 " <" rpl
13277 (format " -%dd"
13278 (abs (- (time-to-days
13279 (save-match-data
13280 (org-read-date
13281 nil t nil msg old-date-time)))
13282 (time-to-days old-date-time))))
13283 ">") t t))))))
13285 (org-add-planning-info type time 'closed)
13286 (when (and old-date
13288 (not (equal old-date org-last-inserted-timestamp)))
13289 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13290 org-last-inserted-timestamp
13291 old-date
13292 log))
13293 (when repeater
13294 (save-excursion
13295 (org-back-to-heading t)
13296 (when (re-search-forward
13297 (concat keyword " " org-last-inserted-timestamp)
13298 (line-end-position 2)
13300 (goto-char (1- (match-end 0)))
13301 (insert " " repeater)
13302 (setq org-last-inserted-timestamp
13303 (concat (substring org-last-inserted-timestamp 0 -1)
13304 " " repeater
13305 (substring org-last-inserted-timestamp -1))))))
13306 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13307 org-last-inserted-timestamp)))))
13309 (defun org-deadline (arg &optional time)
13310 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13311 With one universal prefix argument, remove any deadline from the item.
13312 With two universal prefix arguments, prompt for a warning delay.
13313 With argument TIME, set the deadline at the corresponding date. TIME
13314 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13315 (interactive "P")
13316 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13317 (org-map-entries
13318 (lambda () (org--deadline-or-schedule arg 'deadline time))
13320 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13321 'region-start-level
13322 'region)
13323 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13324 (org--deadline-or-schedule arg 'deadline time)))
13326 (defun org-schedule (arg &optional time)
13327 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13328 With one universal prefix argument, remove any scheduling date from the item.
13329 With two universal prefix arguments, prompt for a delay cookie.
13330 With argument TIME, scheduled at the corresponding date. TIME can
13331 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13332 (interactive "P")
13333 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13334 (org-map-entries
13335 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13337 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13338 'region-start-level
13339 'region)
13340 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13341 (org--deadline-or-schedule arg 'scheduled time)))
13343 (defun org-get-scheduled-time (pom &optional inherit)
13344 "Get the scheduled time as a time tuple, of a format suitable
13345 for calling org-schedule with, or if there is no scheduling,
13346 returns nil."
13347 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13348 (when time
13349 (apply 'encode-time (org-parse-time-string time)))))
13351 (defun org-get-deadline-time (pom &optional inherit)
13352 "Get the deadline as a time tuple, of a format suitable for
13353 calling org-deadline with, or if there is no scheduling, returns
13354 nil."
13355 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13356 (when time
13357 (apply 'encode-time (org-parse-time-string time)))))
13359 (defun org-remove-timestamp-with-keyword (keyword)
13360 "Remove all time stamps with KEYWORD in the current entry."
13361 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13362 beg)
13363 (save-excursion
13364 (org-back-to-heading t)
13365 (setq beg (point))
13366 (outline-next-heading)
13367 (while (re-search-backward re beg t)
13368 (replace-match "")
13369 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13370 (equal (char-before) ?\ ))
13371 (backward-delete-char 1)
13372 (when (string-match "^[ \t]*$" (buffer-substring
13373 (point-at-bol) (point-at-eol)))
13374 (delete-region (point-at-bol)
13375 (min (point-max) (1+ (point-at-eol))))))))))
13377 (defvar org-time-was-given) ; dynamically scoped parameter
13378 (defvar org-end-time-was-given) ; dynamically scoped parameter
13380 (defun org-at-planning-p ()
13381 "Non-nil when point is on a planning info line."
13382 ;; This is as accurate and faster than `org-element-at-point' since
13383 ;; planning info location is fixed in the section.
13384 (org-with-wide-buffer
13385 (beginning-of-line)
13386 (and (looking-at-p org-planning-line-re)
13387 (eq (point)
13388 (ignore-errors
13389 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13390 (org-back-to-heading t)
13391 (org-with-limited-levels (org-back-to-heading t)))
13392 (line-beginning-position 2))))))
13394 (defun org-add-planning-info (what &optional time &rest remove)
13395 "Insert new timestamp with keyword in the planning line.
13396 WHAT indicates what kind of time stamp to add. It is a symbol
13397 among `closed', `deadline', `scheduled' and nil. TIME indicates
13398 the time to use. If none is given, the user is prompted for
13399 a date. REMOVE indicates what kind of entries to remove. An old
13400 WHAT entry will also be removed."
13401 (let (org-time-was-given org-end-time-was-given default-time default-input)
13402 (catch 'exit
13403 (when (and (memq what '(scheduled deadline))
13404 (or (not time)
13405 (and (stringp time)
13406 (string-match "^[-+]+[0-9]" time))))
13407 ;; Try to get a default date/time from existing timestamp
13408 (save-excursion
13409 (org-back-to-heading t)
13410 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13411 (when (re-search-forward (if (eq what 'scheduled)
13412 org-scheduled-time-regexp
13413 org-deadline-time-regexp)
13414 end t)
13415 (setq ts (match-string 1)
13416 default-time (apply 'encode-time (org-parse-time-string ts))
13417 default-input (and ts (org-get-compact-tod ts)))))))
13418 (when what
13419 (setq time
13420 (if (stringp time)
13421 ;; This is a string (relative or absolute), set
13422 ;; proper date.
13423 (apply #'encode-time
13424 (org-read-date-analyze
13425 time default-time (decode-time default-time)))
13426 ;; If necessary, get the time from the user
13427 (or time (org-read-date nil 'to-time nil nil
13428 default-time default-input)))))
13430 (org-with-wide-buffer
13431 (org-back-to-heading t)
13432 (forward-line)
13433 (unless (bolp) (insert "\n"))
13434 (cond ((looking-at-p org-planning-line-re)
13435 ;; Move to current indentation.
13436 (skip-chars-forward " \t")
13437 ;; Check if we have to remove something.
13438 (dolist (type (if what (cons what remove) remove))
13439 (save-excursion
13440 (when (re-search-forward
13441 (cl-case type
13442 (closed org-closed-time-regexp)
13443 (deadline org-deadline-time-regexp)
13444 (scheduled org-scheduled-time-regexp)
13445 (otherwise
13446 (error "Invalid planning type: %s" type)))
13447 (line-end-position) t)
13448 ;; Delete until next keyword or end of line.
13449 (delete-region
13450 (match-beginning 0)
13451 (if (re-search-forward org-keyword-time-not-clock-regexp
13452 (line-end-position)
13454 (match-beginning 0)
13455 (line-end-position))))))
13456 ;; If there is nothing more to add and no more keyword
13457 ;; is left, remove the line completely.
13458 (if (and (looking-at-p "[ \t]*$") (not what))
13459 (delete-region (line-beginning-position)
13460 (line-beginning-position 2))
13461 ;; If we removed last keyword, do not leave trailing
13462 ;; white space at the end of line.
13463 (let ((p (point)))
13464 (save-excursion
13465 (end-of-line)
13466 (unless (= (skip-chars-backward " \t" p) 0)
13467 (delete-region (point) (line-end-position)))))))
13468 ((not what) (throw 'exit nil)) ; Nothing to do.
13469 (t (insert-before-markers "\n")
13470 (backward-char 1)
13471 (when org-adapt-indentation
13472 (indent-to-column (1+ (org-outline-level))))))
13473 (when what
13474 ;; Insert planning keyword.
13475 (insert (cl-case what
13476 (closed org-closed-string)
13477 (deadline org-deadline-string)
13478 (scheduled org-scheduled-string)
13479 (otherwise (error "Invalid planning type: %s" what)))
13480 " ")
13481 ;; Insert associated timestamp.
13482 (let ((ts (org-insert-time-stamp
13483 time
13484 (or org-time-was-given
13485 (and (eq what 'closed) org-log-done-with-time))
13486 (eq what 'closed)
13487 nil nil (list org-end-time-was-given))))
13488 (unless (eolp) (insert " "))
13489 ts))))))
13491 (defvar org-log-note-marker (make-marker)
13492 "Marker pointing at the entry where the note is to be inserted.")
13493 (defvar org-log-note-purpose nil)
13494 (defvar org-log-note-state nil)
13495 (defvar org-log-note-previous-state nil)
13496 (defvar org-log-note-extra nil)
13497 (defvar org-log-note-window-configuration nil)
13498 (defvar org-log-note-return-to (make-marker))
13499 (defvar org-log-note-effective-time nil
13500 "Remembered current time so that dynamically scoped
13501 `org-extend-today-until' affects timestamps in state change log")
13503 (defvar org-log-post-message nil
13504 "Message to be displayed after a log note has been stored.
13505 The auto-repeater uses this.")
13507 (defun org-add-note ()
13508 "Add a note to the current entry.
13509 This is done in the same way as adding a state change note."
13510 (interactive)
13511 (org-add-log-setup 'note))
13513 (defun org-log-beginning (&optional create)
13514 "Return expected start of log notes in current entry.
13515 When optional argument CREATE is non-nil, the function creates
13516 a drawer to store notes, if necessary. Returned position ignores
13517 narrowing."
13518 (org-with-wide-buffer
13519 (let ((drawer (org-log-into-drawer)))
13520 (cond
13521 (drawer
13522 (org-end-of-meta-data)
13523 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13524 (end (if (org-at-heading-p) (point)
13525 (save-excursion (outline-next-heading) (point))))
13526 (case-fold-search t))
13527 (catch 'exit
13528 ;; Try to find existing drawer.
13529 (while (re-search-forward regexp end t)
13530 (let ((element (org-element-at-point)))
13531 (when (eq (org-element-type element) 'drawer)
13532 (let ((cend (org-element-property :contents-end element)))
13533 (when (and (not org-log-states-order-reversed) cend)
13534 (goto-char cend)))
13535 (throw 'exit nil))))
13536 ;; No drawer found. Create one, if permitted.
13537 (when create
13538 (unless (bolp) (insert "\n"))
13539 (let ((beg (point)))
13540 (insert ":" drawer ":\n:END:\n")
13541 (org-indent-region beg (point)))
13542 (end-of-line -1)))))
13544 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13545 (skip-chars-forward " \t\n")
13546 (beginning-of-line)
13547 (unless org-log-states-order-reversed
13548 (org-skip-over-state-notes)
13549 (skip-chars-backward " \t\n")
13550 (forward-line)))))
13551 (if (bolp) (point) (line-beginning-position 2))))
13553 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13554 "Set up the post command hook to take a note.
13555 If this is about to TODO state change, the new state is expected in STATE.
13556 HOW is an indicator what kind of note should be created.
13557 EXTRA is additional text that will be inserted into the notes buffer."
13558 (move-marker org-log-note-marker (point))
13559 (setq org-log-note-purpose purpose
13560 org-log-note-state state
13561 org-log-note-previous-state prev-state
13562 org-log-note-how how
13563 org-log-note-extra extra
13564 org-log-note-effective-time (org-current-effective-time))
13565 (add-hook 'post-command-hook 'org-add-log-note 'append))
13567 (defun org-skip-over-state-notes ()
13568 "Skip past the list of State notes in an entry."
13569 (when (ignore-errors (goto-char (org-in-item-p)))
13570 (let* ((struct (org-list-struct))
13571 (prevs (org-list-prevs-alist struct))
13572 (regexp
13573 (concat "[ \t]*- +"
13574 (replace-regexp-in-string
13575 " +" " +"
13576 (org-replace-escapes
13577 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13578 `(("%d" . ,org-ts-regexp-inactive)
13579 ("%D" . ,org-ts-regexp)
13580 ("%s" . "\"\\S-+\"")
13581 ("%S" . "\"\\S-+\"")
13582 ("%t" . ,org-ts-regexp-inactive)
13583 ("%T" . ,org-ts-regexp)
13584 ("%u" . ".*?")
13585 ("%U" . ".*?")))))))
13586 (while (looking-at-p regexp)
13587 (goto-char (or (org-list-get-next-item (point) struct prevs)
13588 (org-list-get-item-end (point) struct)))))))
13590 (defun org-add-log-note (&optional _purpose)
13591 "Pop up a window for taking a note, and add this note later."
13592 (remove-hook 'post-command-hook 'org-add-log-note)
13593 (setq org-log-note-window-configuration (current-window-configuration))
13594 (delete-other-windows)
13595 (move-marker org-log-note-return-to (point))
13596 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13597 (goto-char org-log-note-marker)
13598 (org-switch-to-buffer-other-window "*Org Note*")
13599 (erase-buffer)
13600 (if (memq org-log-note-how '(time state))
13601 (let (current-prefix-arg) (org-store-log-note))
13602 (let ((org-inhibit-startup t)) (org-mode))
13603 (insert (format "# Insert note for %s.
13604 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13605 (cond
13606 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13607 ((eq org-log-note-purpose 'done) "closed todo item")
13608 ((eq org-log-note-purpose 'state)
13609 (format "state change from \"%s\" to \"%s\""
13610 (or org-log-note-previous-state "")
13611 (or org-log-note-state "")))
13612 ((eq org-log-note-purpose 'reschedule)
13613 "rescheduling")
13614 ((eq org-log-note-purpose 'delschedule)
13615 "no longer scheduled")
13616 ((eq org-log-note-purpose 'redeadline)
13617 "changing deadline")
13618 ((eq org-log-note-purpose 'deldeadline)
13619 "removing deadline")
13620 ((eq org-log-note-purpose 'refile)
13621 "refiling")
13622 ((eq org-log-note-purpose 'note)
13623 "this entry")
13624 (t (error "This should not happen")))))
13625 (when org-log-note-extra (insert org-log-note-extra))
13626 (setq-local org-finish-function 'org-store-log-note)
13627 (run-hooks 'org-log-buffer-setup-hook)))
13629 (defvar org-note-abort nil) ; dynamically scoped
13630 (defun org-store-log-note ()
13631 "Finish taking a log note, and insert it to where it belongs."
13632 (let ((txt (prog1 (buffer-string)
13633 (kill-buffer)))
13634 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13635 lines)
13636 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13637 (setq txt (replace-match "" t t txt)))
13638 (when (string-match "\\s-+\\'" txt)
13639 (setq txt (replace-match "" t t txt)))
13640 (setq lines (org-split-string txt "\n"))
13641 (when (org-string-nw-p note)
13642 (setq note
13643 (org-replace-escapes
13644 note
13645 (list (cons "%u" (user-login-name))
13646 (cons "%U" user-full-name)
13647 (cons "%t" (format-time-string
13648 (org-time-stamp-format 'long 'inactive)
13649 org-log-note-effective-time))
13650 (cons "%T" (format-time-string
13651 (org-time-stamp-format 'long nil)
13652 org-log-note-effective-time))
13653 (cons "%d" (format-time-string
13654 (org-time-stamp-format nil 'inactive)
13655 org-log-note-effective-time))
13656 (cons "%D" (format-time-string
13657 (org-time-stamp-format nil nil)
13658 org-log-note-effective-time))
13659 (cons "%s" (cond
13660 ((not org-log-note-state) "")
13661 ((string-match-p org-ts-regexp
13662 org-log-note-state)
13663 (format "\"[%s]\""
13664 (substring org-log-note-state 1 -1)))
13665 (t (format "\"%s\"" org-log-note-state))))
13666 (cons "%S"
13667 (cond
13668 ((not org-log-note-previous-state) "")
13669 ((string-match-p org-ts-regexp
13670 org-log-note-previous-state)
13671 (format "\"[%s]\""
13672 (substring
13673 org-log-note-previous-state 1 -1)))
13674 (t (format "\"%s\""
13675 org-log-note-previous-state)))))))
13676 (when lines (setq note (concat note " \\\\")))
13677 (push note lines))
13678 (when (and lines (not (or current-prefix-arg org-note-abort)))
13679 (with-current-buffer (marker-buffer org-log-note-marker)
13680 (org-with-wide-buffer
13681 ;; Find location for the new note.
13682 (goto-char org-log-note-marker)
13683 (set-marker org-log-note-marker nil)
13684 ;; Note associated to a clock is to be located right after
13685 ;; the clock. Do not move point.
13686 (unless (eq org-log-note-purpose 'clock-out)
13687 (goto-char (org-log-beginning t)))
13688 ;; Make sure point is at the beginning of an empty line.
13689 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13690 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13691 ;; In an existing list, add a new item at the top level.
13692 ;; Otherwise, indent line like a regular one.
13693 (let ((itemp (org-in-item-p)))
13694 (if itemp
13695 (indent-line-to
13696 (let ((struct (save-excursion
13697 (goto-char itemp) (org-list-struct))))
13698 (org-list-get-ind (org-list-get-top-point struct) struct)))
13699 (org-indent-line)))
13700 (insert (org-list-bullet-string "-") (pop lines))
13701 (let ((ind (org-list-item-body-column (line-beginning-position))))
13702 (dolist (line lines)
13703 (insert "\n")
13704 (indent-line-to ind)
13705 (insert line)))
13706 (message "Note stored")
13707 (org-back-to-heading t)
13708 (org-cycle-hide-drawers 'children))
13709 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13710 ;; from within `org-add-log-note' because `buffer-undo-list'
13711 ;; is then modified outside of `org-with-remote-undo'.
13712 (when (eq this-command 'org-agenda-todo)
13713 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13714 ;; Don't add undo information when called from `org-agenda-todo'.
13715 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13716 (set-window-configuration org-log-note-window-configuration)
13717 (with-current-buffer (marker-buffer org-log-note-return-to)
13718 (goto-char org-log-note-return-to))
13719 (move-marker org-log-note-return-to nil)
13720 (when org-log-post-message (message "%s" org-log-post-message))))
13722 (defun org-remove-empty-drawer-at (pos)
13723 "Remove an empty drawer at position POS.
13724 POS may also be a marker."
13725 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13726 (org-with-wide-buffer
13727 (goto-char pos)
13728 (let ((drawer (org-element-at-point)))
13729 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13730 (not (org-element-property :contents-begin drawer)))
13731 (delete-region (org-element-property :begin drawer)
13732 (progn (goto-char (org-element-property :end drawer))
13733 (skip-chars-backward " \r\t\n")
13734 (forward-line)
13735 (point))))))))
13737 (defvar org-ts-type nil)
13738 (defun org-sparse-tree (&optional arg type)
13739 "Create a sparse tree, prompt for the details.
13740 This command can create sparse trees. You first need to select the type
13741 of match used to create the tree:
13743 t Show all TODO entries.
13744 T Show entries with a specific TODO keyword.
13745 m Show entries selected by a tags/property match.
13746 p Enter a property name and its value (both with completion on existing
13747 names/values) and show entries with that property.
13748 r Show entries matching a regular expression (`/' can be used as well).
13749 b Show deadlines and scheduled items before a date.
13750 a Show deadlines and scheduled items after a date.
13751 d Show deadlines due within `org-deadline-warning-days'.
13752 D Show deadlines and scheduled items between a date range."
13753 (interactive "P")
13754 (setq type (or type org-sparse-tree-default-date-type))
13755 (setq org-ts-type type)
13756 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13757 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13758 \[c]ycle through date types: %s"
13759 (cl-case type
13760 (all "all timestamps")
13761 (scheduled "only scheduled")
13762 (deadline "only deadline")
13763 (active "only active timestamps")
13764 (inactive "only inactive timestamps")
13765 (closed "with a closed time-stamp")
13766 (otherwise "scheduled/deadline")))
13767 (let ((answer (read-char-exclusive)))
13768 (cl-case answer
13770 (org-sparse-tree
13772 (cadr
13773 (memq type '(nil all scheduled deadline active inactive closed)))))
13774 (?d (call-interactively 'org-check-deadlines))
13775 (?b (call-interactively 'org-check-before-date))
13776 (?a (call-interactively 'org-check-after-date))
13777 (?D (call-interactively 'org-check-dates-range))
13778 (?t (call-interactively 'org-show-todo-tree))
13779 (?T (org-show-todo-tree '(4)))
13780 (?m (call-interactively 'org-match-sparse-tree))
13781 ((?p ?P)
13782 (let* ((kwd (completing-read
13783 "Property: " (mapcar #'list (org-buffer-property-keys))))
13784 (value (completing-read
13785 "Value: " (mapcar #'list (org-property-values kwd)))))
13786 (unless (string-match "\\`{.*}\\'" value)
13787 (setq value (concat "\"" value "\"")))
13788 (org-match-sparse-tree arg (concat kwd "=" value))))
13789 ((?r ?R ?/) (call-interactively 'org-occur))
13790 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13792 (defvar-local org-occur-highlights nil
13793 "List of overlays used for occur matches.")
13794 (defvar-local org-occur-parameters nil
13795 "Parameters of the active org-occur calls.
13796 This is a list, each call to org-occur pushes as cons cell,
13797 containing the regular expression and the callback, onto the list.
13798 The list can contain several entries if `org-occur' has been called
13799 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13800 will only contain one set of parameters. When the highlights are
13801 removed (for example with `C-c C-c', or with the next edit (depending
13802 on `org-remove-highlights-with-change'), this variable is emptied
13803 as well.")
13805 (defun org-occur (regexp &optional keep-previous callback)
13806 "Make a compact tree which shows all matches of REGEXP.
13808 The tree will show the lines where the regexp matches, and any other context
13809 defined in `org-show-context-detail', which see.
13811 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13812 done by a previous call to `org-occur' will be kept, to allow stacking of
13813 calls to this command.
13815 Optional argument CALLBACK can be a function of no argument. In this case,
13816 it is called with point at the end of the match, match data being set
13817 accordingly. Current match is shown only if the return value is non-nil.
13818 The function must neither move point nor alter narrowing."
13819 (interactive "sRegexp: \nP")
13820 (when (equal regexp "")
13821 (user-error "Regexp cannot be empty"))
13822 (unless keep-previous
13823 (org-remove-occur-highlights nil nil t))
13824 (push (cons regexp callback) org-occur-parameters)
13825 (let ((cnt 0))
13826 (save-excursion
13827 (goto-char (point-min))
13828 (when (or (not keep-previous) ; do not want to keep
13829 (not org-occur-highlights)) ; no previous matches
13830 ;; hide everything
13831 (org-overview))
13832 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13833 (isearch-no-upper-case-p regexp t)
13834 org-occur-case-fold-search)))
13835 (while (re-search-forward regexp nil t)
13836 (when (or (not callback)
13837 (save-match-data (funcall callback)))
13838 (setq cnt (1+ cnt))
13839 (when org-highlight-sparse-tree-matches
13840 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13841 (org-show-context 'occur-tree)))))
13842 (when org-remove-highlights-with-change
13843 (add-hook 'before-change-functions 'org-remove-occur-highlights
13844 nil 'local))
13845 (unless org-sparse-tree-open-archived-trees
13846 (org-hide-archived-subtrees (point-min) (point-max)))
13847 (run-hooks 'org-occur-hook)
13848 (when (called-interactively-p 'interactive)
13849 (message "%d match(es) for regexp %s" cnt regexp))
13850 cnt))
13852 (defun org-occur-next-match (&optional n _reset)
13853 "Function for `next-error-function' to find sparse tree matches.
13854 N is the number of matches to move, when negative move backwards.
13855 This function always goes back to the starting point when no
13856 match is found."
13857 (let* ((limit (if (< n 0) (point-min) (point-max)))
13858 (search-func (if (< n 0)
13859 'previous-single-char-property-change
13860 'next-single-char-property-change))
13861 (n (abs n))
13862 (pos (point))
13864 (catch 'exit
13865 (while (setq p1 (funcall search-func (point) 'org-type))
13866 (when (equal p1 limit)
13867 (goto-char pos)
13868 (user-error "No more matches"))
13869 (when (equal (get-char-property p1 'org-type) 'org-occur)
13870 (setq n (1- n))
13871 (when (= n 0)
13872 (goto-char p1)
13873 (throw 'exit (point))))
13874 (goto-char p1))
13875 (goto-char p1)
13876 (user-error "No more matches"))))
13878 (defun org-show-context (&optional key)
13879 "Make sure point and context are visible.
13880 Optional argument KEY, when non-nil, is a symbol. See
13881 `org-show-context-detail' for allowed values and how much is to
13882 be shown."
13883 (org-show-set-visibility
13884 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13885 ((cdr (assq key org-show-context-detail)))
13886 (t (cdr (assq 'default org-show-context-detail))))))
13888 (defun org-show-set-visibility (detail)
13889 "Set visibility around point according to DETAIL.
13890 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13891 `tree', `canonical' or t. See `org-show-context-detail' for more
13892 information."
13893 ;; Show current heading and possibly its entry, following headline
13894 ;; or all children.
13895 (if (and (org-at-heading-p) (not (eq detail 'local)))
13896 (org-flag-heading nil)
13897 (org-show-entry)
13898 ;; If point is hidden within a drawer or a block, make sure to
13899 ;; expose it.
13900 (dolist (o (overlays-at (point)))
13901 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13902 (delete-overlay o)))
13903 (unless (org-before-first-heading-p)
13904 (org-with-limited-levels
13905 (cl-case detail
13906 ((tree canonical t) (org-show-children))
13907 ((nil minimal ancestors))
13908 (t (save-excursion
13909 (outline-next-heading)
13910 (org-flag-heading nil)))))))
13911 ;; Show all siblings.
13912 (when (eq detail 'lineage) (org-show-siblings))
13913 ;; Show ancestors, possibly with their children.
13914 (when (memq detail '(ancestors lineage tree canonical t))
13915 (save-excursion
13916 (while (org-up-heading-safe)
13917 (org-flag-heading nil)
13918 (when (memq detail '(canonical t)) (org-show-entry))
13919 (when (memq detail '(tree canonical t)) (org-show-children))))))
13921 (defvar org-reveal-start-hook nil
13922 "Hook run before revealing a location.")
13924 (defun org-reveal (&optional siblings)
13925 "Show current entry, hierarchy above it, and the following headline.
13927 This can be used to show a consistent set of context around
13928 locations exposed with `org-show-context'.
13930 With optional argument SIBLINGS, on each level of the hierarchy all
13931 siblings are shown. This repairs the tree structure to what it would
13932 look like when opened with hierarchical calls to `org-cycle'.
13934 With a \\[universal-argument] \\[universal-argument] prefix, \
13935 go to the parent and show the entire tree."
13936 (interactive "P")
13937 (run-hooks 'org-reveal-start-hook)
13938 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13939 ((equal siblings '(16))
13940 (save-excursion
13941 (when (org-up-heading-safe)
13942 (org-show-subtree)
13943 (run-hook-with-args 'org-cycle-hook 'subtree))))
13944 (t (org-show-set-visibility 'lineage))))
13946 (defun org-highlight-new-match (beg end)
13947 "Highlight from BEG to END and mark the highlight is an occur headline."
13948 (let ((ov (make-overlay beg end)))
13949 (overlay-put ov 'face 'secondary-selection)
13950 (overlay-put ov 'org-type 'org-occur)
13951 (push ov org-occur-highlights)))
13953 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13954 "Remove the occur highlights from the buffer.
13955 BEG and END are ignored. If NOREMOVE is nil, remove this function
13956 from the `before-change-functions' in the current buffer."
13957 (interactive)
13958 (unless org-inhibit-highlight-removal
13959 (mapc #'delete-overlay org-occur-highlights)
13960 (setq org-occur-highlights nil)
13961 (setq org-occur-parameters nil)
13962 (unless noremove
13963 (remove-hook 'before-change-functions
13964 'org-remove-occur-highlights 'local))))
13966 ;;;; Priorities
13968 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13969 "Regular expression matching the priority indicator.")
13971 (defvar org-remove-priority-next-time nil)
13973 (defun org-priority-up ()
13974 "Increase the priority of the current item."
13975 (interactive)
13976 (org-priority 'up))
13978 (defun org-priority-down ()
13979 "Decrease the priority of the current item."
13980 (interactive)
13981 (org-priority 'down))
13983 (defun org-priority (&optional action _show)
13984 "Change the priority of an item.
13985 ACTION can be `set', `up', `down', or a character."
13986 (interactive "P")
13987 (if (equal action '(4))
13988 (org-show-priority)
13989 (unless org-enable-priority-commands
13990 (user-error "Priority commands are disabled"))
13991 (setq action (or action 'set))
13992 (let (current new news have remove)
13993 (save-excursion
13994 (org-back-to-heading t)
13995 (when (looking-at org-priority-regexp)
13996 (setq current (string-to-char (match-string 2))
13997 have t))
13998 (cond
13999 ((eq action 'remove)
14000 (setq remove t new ?\ ))
14001 ((or (eq action 'set)
14002 (integerp action))
14003 (if (not (eq action 'set))
14004 (setq new action)
14005 (message "Priority %c-%c, SPC to remove: "
14006 org-highest-priority org-lowest-priority)
14007 (save-match-data
14008 (setq new (read-char-exclusive))))
14009 (when (and (= (upcase org-highest-priority) org-highest-priority)
14010 (= (upcase org-lowest-priority) org-lowest-priority))
14011 (setq new (upcase new)))
14012 (cond ((equal new ?\ ) (setq remove t))
14013 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14014 (user-error "Priority must be between `%c' and `%c'"
14015 org-highest-priority org-lowest-priority))))
14016 ((eq action 'up)
14017 (setq new (if have
14018 (1- current) ; normal cycling
14019 ;; last priority was empty
14020 (if (eq last-command this-command)
14021 org-lowest-priority ; wrap around empty to lowest
14022 ;; default
14023 (if org-priority-start-cycle-with-default
14024 org-default-priority
14025 (1- org-default-priority))))))
14026 ((eq action 'down)
14027 (setq new (if have
14028 (1+ current) ; normal cycling
14029 ;; last priority was empty
14030 (if (eq last-command this-command)
14031 org-highest-priority ; wrap around empty to highest
14032 ;; default
14033 (if org-priority-start-cycle-with-default
14034 org-default-priority
14035 (1+ org-default-priority))))))
14036 (t (user-error "Invalid action")))
14037 (when (or (< (upcase new) org-highest-priority)
14038 (> (upcase new) org-lowest-priority))
14039 (if (and (memq action '(up down))
14040 (not have) (not (eq last-command this-command)))
14041 ;; `new' is from default priority
14042 (error
14043 "The default can not be set, see `org-default-priority' why")
14044 ;; normal cycling: `new' is beyond highest/lowest priority
14045 ;; and is wrapped around to the empty priority
14046 (setq remove t)))
14047 (setq news (format "%c" new))
14048 (if have
14049 (if remove
14050 (replace-match "" t t nil 1)
14051 (replace-match news t t nil 2))
14052 (if remove
14053 (user-error "No priority cookie found in line")
14054 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14055 (if (match-end 2)
14056 (progn
14057 (goto-char (match-end 2))
14058 (insert " [#" news "]"))
14059 (goto-char (match-beginning 3))
14060 (insert "[#" news "] "))))
14061 (org-set-tags nil 'align))
14062 (if remove
14063 (message "Priority removed")
14064 (message "Priority of current item set to %s" news)))))
14066 (defun org-show-priority ()
14067 "Show the priority of the current item.
14068 This priority is composed of the main priority given with the [#A] cookies,
14069 and by additional input from the age of a schedules or deadline entry."
14070 (interactive)
14071 (let ((pri (if (eq major-mode 'org-agenda-mode)
14072 (org-get-at-bol 'priority)
14073 (save-excursion
14074 (save-match-data
14075 (beginning-of-line)
14076 (and (looking-at org-heading-regexp)
14077 (org-get-priority (match-string 0))))))))
14078 (message "Priority is %d" (if pri pri -1000))))
14080 (defun org-get-priority (s)
14081 "Find priority cookie and return priority."
14082 (save-match-data
14083 (if (functionp org-get-priority-function)
14084 (funcall org-get-priority-function)
14085 (if (not (string-match org-priority-regexp s))
14086 (* 1000 (- org-lowest-priority org-default-priority))
14087 (* 1000 (- org-lowest-priority
14088 (string-to-char (match-string 2 s))))))))
14090 ;;;; Tags
14092 (defvar org-agenda-archives-mode)
14093 (defvar org-map-continue-from nil
14094 "Position from where mapping should continue.
14095 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14097 (defvar org-scanner-tags nil
14098 "The current tag list while the tags scanner is running.")
14100 (defvar org-trust-scanner-tags nil
14101 "Should `org-get-tags-at' use the tags for the scanner.
14102 This is for internal dynamical scoping only.
14103 When this is non-nil, the function `org-get-tags-at' will return the value
14104 of `org-scanner-tags' instead of building the list by itself. This
14105 can lead to large speed-ups when the tags scanner is used in a file with
14106 many entries, and when the list of tags is retrieved, for example to
14107 obtain a list of properties. Building the tags list for each entry in such
14108 a file becomes an N^2 operation - but with this variable set, it scales
14109 as N.")
14111 (defvar org--matcher-tags-todo-only nil)
14113 (defun org-scan-tags (action matcher todo-only &optional start-level)
14114 "Scan headline tags with inheritance and produce output ACTION.
14116 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14117 or `agenda' to produce an entry list for an agenda view. It can also be
14118 a Lisp form or a function that should be called at each matched headline, in
14119 this case the return value is a list of all return values from these calls.
14121 MATCHER is a function accepting three arguments, returning
14122 a non-nil value whenever a given set of tags qualifies a headline
14123 for inclusion. See `org-make-tags-matcher' for more information.
14124 As a special case, it can also be set to t (respectively nil) in
14125 order to match all (respectively none) headline.
14127 When TODO-ONLY is non-nil, only lines with a not-done TODO
14128 keyword are included in the output.
14130 START-LEVEL can be a string with asterisks, reducing the scope to
14131 headlines matching this string."
14132 (require 'org-agenda)
14133 (let* ((re (concat "^"
14134 (if start-level
14135 ;; Get the correct level to match
14136 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14137 org-outline-regexp)
14138 " *\\(\\<\\("
14139 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14140 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14141 (props (list 'face 'default
14142 'done-face 'org-agenda-done
14143 'undone-face 'default
14144 'mouse-face 'highlight
14145 'org-not-done-regexp org-not-done-regexp
14146 'org-todo-regexp org-todo-regexp
14147 'org-complex-heading-regexp org-complex-heading-regexp
14148 'help-echo
14149 (format "mouse-2 or RET jump to org file %s"
14150 (abbreviate-file-name
14151 (or (buffer-file-name (buffer-base-buffer))
14152 (buffer-name (buffer-base-buffer)))))))
14153 (org-map-continue-from nil)
14154 lspos tags tags-list
14155 (tags-alist (list (cons 0 org-file-tags)))
14156 (llast 0) rtn rtn1 level category i txt
14157 todo marker entry priority
14158 ts-date ts-date-type ts-date-pair)
14159 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14160 (setq action (list 'lambda nil action)))
14161 (save-excursion
14162 (goto-char (point-min))
14163 (when (eq action 'sparse-tree)
14164 (org-overview)
14165 (org-remove-occur-highlights))
14166 (while (let (case-fold-search)
14167 (re-search-forward re nil t))
14168 (setq org-map-continue-from nil)
14169 (catch :skip
14170 (setq todo
14171 ;; TODO: is the 1-2 difference a bug?
14172 (when (match-end 1) (match-string-no-properties 2))
14173 tags (when (match-end 4) (match-string-no-properties 4)))
14174 (goto-char (setq lspos (match-beginning 0)))
14175 (setq level (org-reduced-level (org-outline-level))
14176 category (org-get-category))
14177 (when (eq action 'agenda)
14178 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14179 ts-date (car ts-date-pair)
14180 ts-date-type (cdr ts-date-pair)))
14181 (setq i llast llast level)
14182 ;; remove tag lists from same and sublevels
14183 (while (>= i level)
14184 (when (setq entry (assoc i tags-alist))
14185 (setq tags-alist (delete entry tags-alist)))
14186 (setq i (1- i)))
14187 ;; add the next tags
14188 (when tags
14189 (setq tags (org-split-string tags ":")
14190 tags-alist
14191 (cons (cons level tags) tags-alist)))
14192 ;; compile tags for current headline
14193 (setq tags-list
14194 (if org-use-tag-inheritance
14195 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14196 tags)
14197 org-scanner-tags tags-list)
14198 (when org-use-tag-inheritance
14199 (setcdr (car tags-alist)
14200 (mapcar (lambda (x)
14201 (setq x (copy-sequence x))
14202 (org-add-prop-inherited x))
14203 (cdar tags-alist))))
14204 (when (and tags org-use-tag-inheritance
14205 (or (not (eq t org-use-tag-inheritance))
14206 org-tags-exclude-from-inheritance))
14207 ;; Selective inheritance, remove uninherited ones.
14208 (setcdr (car tags-alist)
14209 (org-remove-uninherited-tags (cdar tags-alist))))
14210 (when (and
14212 ;; eval matcher only when the todo condition is OK
14213 (and (or (not todo-only) (member todo org-not-done-keywords))
14214 (if (functionp matcher)
14215 (let ((case-fold-search t) (org-trust-scanner-tags t))
14216 (funcall matcher todo tags-list level))
14217 matcher))
14219 ;; Call the skipper, but return t if it does not
14220 ;; skip, so that the `and' form continues evaluating.
14221 (progn
14222 (unless (eq action 'sparse-tree) (org-agenda-skip))
14225 ;; Check if timestamps are deselecting this entry
14226 (or (not todo-only)
14227 (and (member todo org-not-done-keywords)
14228 (or (not org-agenda-tags-todo-honor-ignore-options)
14229 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14231 ;; select this headline
14232 (cond
14233 ((eq action 'sparse-tree)
14234 (and org-highlight-sparse-tree-matches
14235 (org-get-heading) (match-end 0)
14236 (org-highlight-new-match
14237 (match-beginning 1) (match-end 1)))
14238 (org-show-context 'tags-tree))
14239 ((eq action 'agenda)
14240 (setq txt (org-agenda-format-item
14242 (concat
14243 (if (eq org-tags-match-list-sublevels 'indented)
14244 (make-string (1- level) ?.) "")
14245 (org-get-heading))
14246 (make-string level ?\s)
14247 category
14248 tags-list)
14249 priority (org-get-priority txt))
14250 (goto-char lspos)
14251 (setq marker (org-agenda-new-marker))
14252 (org-add-props txt props
14253 'org-marker marker 'org-hd-marker marker 'org-category category
14254 'todo-state todo
14255 'ts-date ts-date
14256 'priority priority
14257 'type (concat "tagsmatch" ts-date-type))
14258 (push txt rtn))
14259 ((functionp action)
14260 (setq org-map-continue-from nil)
14261 (save-excursion
14262 (setq rtn1 (funcall action))
14263 (push rtn1 rtn)))
14264 (t (user-error "Invalid action")))
14266 ;; if we are to skip sublevels, jump to end of subtree
14267 (unless org-tags-match-list-sublevels
14268 (org-end-of-subtree t)
14269 (backward-char 1))))
14270 ;; Get the correct position from where to continue
14271 (if org-map-continue-from
14272 (goto-char org-map-continue-from)
14273 (and (= (point) lspos) (end-of-line 1)))))
14274 (when (and (eq action 'sparse-tree)
14275 (not org-sparse-tree-open-archived-trees))
14276 (org-hide-archived-subtrees (point-min) (point-max)))
14277 (nreverse rtn)))
14279 (defun org-remove-uninherited-tags (tags)
14280 "Remove all tags that are not inherited from the list TAGS."
14281 (cond
14282 ((eq org-use-tag-inheritance t)
14283 (if org-tags-exclude-from-inheritance
14284 (org-delete-all org-tags-exclude-from-inheritance tags)
14285 tags))
14286 ((not org-use-tag-inheritance) nil)
14287 ((stringp org-use-tag-inheritance)
14288 (delq nil (mapcar
14289 (lambda (x)
14290 (if (and (string-match org-use-tag-inheritance x)
14291 (not (member x org-tags-exclude-from-inheritance)))
14292 x nil))
14293 tags)))
14294 ((listp org-use-tag-inheritance)
14295 (delq nil (mapcar
14296 (lambda (x)
14297 (if (member x org-use-tag-inheritance) x nil))
14298 tags)))))
14300 (defun org-match-sparse-tree (&optional todo-only match)
14301 "Create a sparse tree according to tags string MATCH.
14303 MATCH is a string with match syntax. It can contain a selection
14304 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14305 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14306 those. See the manual for details.
14308 If optional argument TODO-ONLY is non-nil, only select lines that
14309 are also TODO tasks."
14310 (interactive "P")
14311 (org-agenda-prepare-buffers (list (current-buffer)))
14312 (let ((org--matcher-tags-todo-only todo-only))
14313 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14314 org--matcher-tags-todo-only)))
14316 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14318 (defvar org-cached-props nil)
14319 (defun org-cached-entry-get (pom property)
14320 (if (or (eq t org-use-property-inheritance)
14321 (and (stringp org-use-property-inheritance)
14322 (let ((case-fold-search t))
14323 (string-match-p org-use-property-inheritance property)))
14324 (and (listp org-use-property-inheritance)
14325 (member-ignore-case property org-use-property-inheritance)))
14326 ;; Caching is not possible, check it directly.
14327 (org-entry-get pom property 'inherit)
14328 ;; Get all properties, so we can do complicated checks easily.
14329 (cdr (assoc-string property
14330 (or org-cached-props
14331 (setq org-cached-props (org-entry-properties pom)))
14332 t))))
14334 (defun org-global-tags-completion-table (&optional files)
14335 "Return the list of all tags in all agenda buffer/files.
14336 Optional FILES argument is a list of files which can be used
14337 instead of the agenda files."
14338 (save-excursion
14339 (org-uniquify
14340 (delq nil
14341 (apply #'append
14342 (mapcar
14343 (lambda (file)
14344 (set-buffer (find-file-noselect file))
14345 (mapcar (lambda (x)
14346 (and (stringp (car-safe x))
14347 (list (car-safe x))))
14348 (or org-current-tag-alist (org-get-buffer-tags))))
14349 (if (car-safe files) files
14350 (org-agenda-files))))))))
14352 (defun org-make-tags-matcher (match)
14353 "Create the TAGS/TODO matcher form for the selection string MATCH.
14355 Returns a cons of the selection string MATCH and a function
14356 implementing the matcher.
14358 The matcher is to be called at an Org entry, with point on the
14359 headline, and returns non-nil if the entry matches the selection
14360 string MATCH. It must be called with three arguments: the TODO
14361 keyword at the entry (or nil if none), the list of all tags at
14362 the entry including inherited ones and the reduced level of the
14363 headline. Additionally, the category of the entry, if any, must
14364 be specified as the text property `org-category' on the headline.
14366 This function sets the variable `org--matcher-tags-todo-only' to
14367 a non-nil value if the matcher restricts matching to TODO
14368 entries, otherwise it is not touched.
14370 See also `org-scan-tags'."
14371 (unless match
14372 ;; Get a new match request, with completion against the global
14373 ;; tags table and the local tags in current buffer.
14374 (let ((org-last-tags-completion-table
14375 (org-uniquify
14376 (delq nil (append (org-get-buffer-tags)
14377 (org-global-tags-completion-table))))))
14378 (setq match
14379 (completing-read
14380 "Match: "
14381 'org-tags-completion-function nil nil nil 'org-tags-history))))
14383 (let ((match0 match)
14384 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14385 (start 0)
14386 tagsmatch todomatch tagsmatcher todomatcher)
14388 ;; Expand group tags.
14389 (setq match (org-tags-expand match))
14391 ;; Check if there is a TODO part of this match, which would be the
14392 ;; part after a "/". To make sure that this slash is not part of
14393 ;; a property value to be matched against, we also check that
14394 ;; there is no / after that slash. First, find the last slash.
14395 (let ((s 0))
14396 (while (string-match "/+" match s)
14397 (setq start (match-beginning 0))
14398 (setq s (match-end 0))))
14399 (if (and (string-match "/+" match start)
14400 (not (string-match-p "\"" match start)))
14401 ;; Match contains also a TODO-matching request.
14402 (progn
14403 (setq tagsmatch (substring match 0 (match-beginning 0)))
14404 (setq todomatch (substring match (match-end 0)))
14405 (when (string-prefix-p "!" todomatch)
14406 (setq org--matcher-tags-todo-only t)
14407 (setq todomatch (substring todomatch 1)))
14408 (when (string-match "\\`\\s-*\\'" todomatch)
14409 (setq todomatch nil)))
14410 ;; Only matching tags.
14411 (setq tagsmatch match)
14412 (setq todomatch nil))
14414 ;; Make the tags matcher.
14415 (when (org-string-nw-p tagsmatch)
14416 (let ((orlist nil)
14417 (orterms (org-split-string tagsmatch "|"))
14418 term)
14419 (while (setq term (pop orterms))
14420 (while (and (equal (substring term -1) "\\") orterms)
14421 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14422 (while (string-match re term)
14423 (let* ((rest (substring term (match-end 0)))
14424 (minus (and (match-end 1)
14425 (equal (match-string 1 term) "-")))
14426 (tag (save-match-data
14427 (replace-regexp-in-string
14428 "\\\\-" "-" (match-string 2 term))))
14429 (regexp (eq (string-to-char tag) ?{))
14430 (levelp (match-end 4))
14431 (propp (match-end 5))
14433 (cond
14434 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14435 (levelp
14436 `(,(org-op-to-function (match-string 3 term))
14437 level
14438 ,(string-to-number (match-string 4 term))))
14439 (propp
14440 (let* ((gv (pcase (upcase (match-string 5 term))
14441 ("CATEGORY"
14442 '(get-text-property (point) 'org-category))
14443 ("TODO" 'todo)
14444 (p `(org-cached-entry-get nil ,p))))
14445 (pv (match-string 7 term))
14446 (regexp (eq (string-to-char pv) ?{))
14447 (strp (eq (string-to-char pv) ?\"))
14448 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14449 (po (org-op-to-function (match-string 6 term)
14450 (if timep 'time strp))))
14451 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14452 (when timep (setq pv (org-matcher-time pv)))
14453 (cond ((and regexp (eq po 'org<>))
14454 `(not (string-match ,pv (or ,gv ""))))
14455 (regexp `(string-match ,pv (or ,gv "")))
14456 (strp `(,po (or ,gv "") ,pv))
14458 `(,po
14459 (string-to-number (or ,gv ""))
14460 ,(string-to-number pv))))))
14461 (t `(member ,tag tags-list)))))
14462 (push (if minus `(not ,mm) mm) tagsmatcher)
14463 (setq term rest)))
14464 (push `(and ,@tagsmatcher) orlist)
14465 (setq tagsmatcher nil))
14466 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14468 ;; Make the TODO matcher.
14469 (when (org-string-nw-p todomatch)
14470 (let ((orlist nil))
14471 (dolist (term (org-split-string todomatch "|"))
14472 (while (string-match re term)
14473 (let* ((minus (and (match-end 1)
14474 (equal (match-string 1 term) "-")))
14475 (kwd (match-string 2 term))
14476 (regexp (eq (string-to-char kwd) ?{))
14477 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14478 `(equal todo ,kwd))))
14479 (push (if minus `(not ,mm) mm) todomatcher))
14480 (setq term (substring term (match-end 0))))
14481 (push (if (> (length todomatcher) 1)
14482 (cons 'and todomatcher)
14483 (car todomatcher))
14484 orlist)
14485 (setq todomatcher nil))
14486 (setq todomatcher (cons 'or orlist))))
14488 ;; Return the string and function of the matcher. If no
14489 ;; tags-specific or todo-specific matcher exists, match
14490 ;; everything.
14491 (let ((matcher (if (and tagsmatcher todomatcher)
14492 `(and ,tagsmatcher ,todomatcher)
14493 (or tagsmatcher todomatcher t))))
14494 (when org--matcher-tags-todo-only
14495 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14496 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14498 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14499 "Expand group tags in MATCH.
14501 This replaces every group tag in MATCH with a regexp tag search.
14502 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14503 will be replaced like this:
14505 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14506 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14507 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14509 Replacing by a regexp preserves the structure of the match.
14510 E.g., this expansion
14512 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14514 will match anything tagged with \"Lab\" and \"Home\", or tagged
14515 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14517 A group tag in MATCH can contain regular expressions of its own.
14518 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14519 will be replaced like this:
14521 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14523 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14524 assumed to be a single group tag, and the function will return
14525 the list of tags in this group.
14527 When DOWNCASE is non-nil, expand downcased TAGS."
14528 (if org-group-tags
14529 (let* ((case-fold-search t)
14530 (stable org-mode-syntax-table)
14531 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14532 (taggroups (if downcased
14533 (mapcar (lambda (tg) (mapcar #'downcase tg))
14534 taggroups)
14535 taggroups))
14536 (taggroups-keys (mapcar #'car taggroups))
14537 (return-match (if downcased (downcase match) match))
14538 (count 0)
14539 (work-already-expanded tags-already-expanded)
14540 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14541 ;; @ and _ are allowed as word-components in tags.
14542 (modify-syntax-entry ?@ "w" stable)
14543 (modify-syntax-entry ?_ "w" stable)
14544 ;; Temporarily replace regexp-expressions in the match-expression.
14545 (while (string-match "{.+?}" return-match)
14546 (cl-incf count)
14547 (push (match-string 0 return-match) regexps-in-match)
14548 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14549 (while (and taggroups-keys
14550 (with-syntax-table stable
14551 (string-match
14552 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14553 (regexp-opt taggroups-keys) "\\>\\)")
14554 return-match)))
14555 (let* ((dir (match-string 1 return-match))
14556 (tag (match-string 2 return-match))
14557 (tag (if downcased (downcase tag) tag)))
14558 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14559 (member tag work-already-expanded))
14560 (setq tags-in-group (assoc tag taggroups))
14561 (push tag work-already-expanded)
14562 ;; Recursively expand each tag in the group, if the tag hasn't
14563 ;; already been expanded. Restore the match-data after all recursive calls.
14564 (save-match-data
14565 (let (tags-expanded)
14566 (dolist (x (cdr tags-in-group))
14567 (if (and (member x taggroups-keys)
14568 (not (member x work-already-expanded)))
14569 (setq tags-expanded
14570 (delete-dups
14571 (append
14572 (org-tags-expand x t downcased
14573 work-already-expanded)
14574 tags-expanded)))
14575 (setq tags-expanded
14576 (append (list x) tags-expanded)))
14577 (setq work-already-expanded
14578 (delete-dups
14579 (append tags-expanded
14580 work-already-expanded))))
14581 (setq tags-in-group
14582 (delete-dups (cons (car tags-in-group)
14583 tags-expanded)))))
14584 ;; Filter tag-regexps from tags.
14585 (setq regexp-in-group-escaped
14586 (delq nil (mapcar (lambda (x)
14587 (if (stringp x)
14588 (and (equal "{" (substring x 0 1))
14589 (equal "}" (substring x -1))
14592 tags-in-group))
14593 regexp-in-group
14594 (mapcar (lambda (x)
14595 (substring x 1 -1))
14596 regexp-in-group-escaped)
14597 tags-in-group
14598 (delq nil (mapcar (lambda (x)
14599 (if (stringp x)
14600 (and (not (equal "{" (substring x 0 1)))
14601 (not (equal "}" (substring x -1)))
14604 tags-in-group)))
14605 ;; If single-as-list, do no more in the while-loop.
14606 (if (not single-as-list)
14607 (progn
14608 (when regexp-in-group
14609 (setq regexp-in-group
14610 (concat "\\|"
14611 (mapconcat 'identity regexp-in-group
14612 "\\|"))))
14613 (setq tags-in-group
14614 (concat dir
14615 "{\\<"
14616 (regexp-opt tags-in-group)
14617 "\\>"
14618 regexp-in-group
14619 "}"))
14620 (when (stringp tags-in-group)
14621 (org-add-props tags-in-group '(grouptag t)))
14622 (setq return-match
14623 (replace-match tags-in-group t t return-match)))
14624 (setq tags-in-group
14625 (append regexp-in-group-escaped tags-in-group))))
14626 (setq taggroups-keys (delete tag taggroups-keys))))
14627 ;; Add the regular expressions back into the match-expression again.
14628 (while regexps-in-match
14629 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14630 (pop regexps-in-match)
14631 return-match t t))
14632 (cl-decf count))
14633 (if single-as-list
14634 (if tags-in-group tags-in-group (list return-match))
14635 return-match))
14636 (if single-as-list
14637 (list (if downcased (downcase match) match))
14638 match)))
14640 (defun org-op-to-function (op &optional stringp)
14641 "Turn an operator into the appropriate function."
14642 (setq op
14643 (cond
14644 ((equal op "<" ) '(< string< org-time<))
14645 ((equal op ">" ) '(> org-string> org-time>))
14646 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14647 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14648 ((member op '("=" "==")) '(= string= org-time=))
14649 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14650 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14652 (defun org<> (a b) (not (= a b)))
14653 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14654 (defun org-string>= (a b) (not (string< a b)))
14655 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14656 (defun org-string<> (a b) (not (string= a b)))
14657 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14658 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14659 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14660 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14661 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14662 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14663 (defun org-2ft (s)
14664 "Convert S to a floating point time.
14665 If S is already a number, just return it. If it is a string, parse
14666 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14667 (cond
14668 ((numberp s) s)
14669 ((stringp s)
14670 (condition-case nil
14671 (float-time (apply 'encode-time (org-parse-time-string s)))
14672 (error 0.)))
14673 (t 0.)))
14675 (defun org-time-today ()
14676 "Time in seconds today at 0:00.
14677 Returns the float number of seconds since the beginning of the
14678 epoch to the beginning of today (00:00)."
14679 (float-time (apply 'encode-time
14680 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14682 (defun org-matcher-time (s)
14683 "Interpret a time comparison value."
14684 (save-match-data
14685 (cond
14686 ((string= s "<now>") (float-time))
14687 ((string= s "<today>") (org-time-today))
14688 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14689 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14690 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14691 (+ (org-time-today)
14692 (* (string-to-number (match-string 1 s))
14693 (cdr (assoc (match-string 2 s)
14694 '(("d" . 86400.0) ("w" . 604800.0)
14695 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14696 (t (org-2ft s)))))
14698 (defun org-match-any-p (re list)
14699 "Does re match any element of list?"
14700 (setq list (mapcar (lambda (x) (string-match re x)) list))
14701 (delq nil list))
14703 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14704 (defvar org-tags-overlay (make-overlay 1 1))
14705 (delete-overlay org-tags-overlay)
14707 (defun org-get-local-tags-at (&optional pos)
14708 "Get a list of tags defined in the current headline."
14709 (org-get-tags-at pos 'local))
14711 (defun org-get-local-tags ()
14712 "Get a list of tags defined in the current headline."
14713 (org-get-tags-at nil 'local))
14715 (defun org-get-tags-at (&optional pos local)
14716 "Get a list of all headline tags applicable at POS.
14717 POS defaults to point. If tags are inherited, the list contains
14718 the targets in the same sequence as the headlines appear, i.e.
14719 the tags of the current headline come last.
14720 When LOCAL is non-nil, only return tags from the current headline,
14721 ignore inherited ones."
14722 (interactive)
14723 (if (and org-trust-scanner-tags
14724 (or (not pos) (equal pos (point)))
14725 (not local))
14726 org-scanner-tags
14727 (let (tags ltags lastpos parent)
14728 (save-excursion
14729 (save-restriction
14730 (widen)
14731 (goto-char (or pos (point)))
14732 (save-match-data
14733 (catch 'done
14734 (condition-case nil
14735 (progn
14736 (org-back-to-heading t)
14737 (while (not (equal lastpos (point)))
14738 (setq lastpos (point))
14739 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14740 (setq ltags (org-split-string
14741 (match-string-no-properties 1) ":"))
14742 (when parent
14743 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14744 (setq tags (append
14745 (if parent
14746 (org-remove-uninherited-tags ltags)
14747 ltags)
14748 tags)))
14749 (or org-use-tag-inheritance (throw 'done t))
14750 (when local (throw 'done t))
14751 (or (org-up-heading-safe) (error nil))
14752 (setq parent t)))
14753 (error nil)))))
14754 (if local
14755 tags
14756 (reverse (delete-dups
14757 (reverse (append
14758 (org-remove-uninherited-tags
14759 org-file-tags)
14760 tags)))))))))
14762 (defun org-add-prop-inherited (s)
14763 (add-text-properties 0 (length s) '(inherited t) s)
14766 (defun org-toggle-tag (tag &optional onoff)
14767 "Toggle the tag TAG for the current line.
14768 If ONOFF is `on' or `off', don't toggle but set to this state."
14769 (let (res current)
14770 (save-excursion
14771 (org-back-to-heading t)
14772 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14773 (point-at-eol) t)
14774 (progn
14775 (setq current (match-string 1))
14776 (replace-match ""))
14777 (setq current ""))
14778 (setq current (nreverse (org-split-string current ":")))
14779 (cond
14780 ((eq onoff 'on)
14781 (setq res t)
14782 (or (member tag current) (push tag current)))
14783 ((eq onoff 'off)
14784 (or (not (member tag current)) (setq current (delete tag current))))
14785 (t (if (member tag current)
14786 (setq current (delete tag current))
14787 (setq res t)
14788 (push tag current))))
14789 (end-of-line 1)
14790 (if current
14791 (progn
14792 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14793 (org-set-tags nil t))
14794 (delete-horizontal-space))
14795 (run-hooks 'org-after-tags-change-hook))
14796 res))
14798 (defun org--align-tags-here (to-col)
14799 "Align tags on the current headline to TO-COL.
14800 Assume point is on a headline."
14801 (let ((pos (point)))
14802 (beginning-of-line)
14803 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14804 (>= pos (match-beginning 2)))
14805 ;; No tags or point within tags: do not align.
14806 (goto-char pos)
14807 (goto-char (match-beginning 1))
14808 (let ((shift (max (- (if (>= to-col 0) to-col
14809 (- (abs to-col) (string-width (match-string 2))))
14810 (current-column))
14811 1)))
14812 (replace-match (make-string shift ?\s) nil nil nil 1)
14813 ;; Preserve initial position, if possible. In any case, stop
14814 ;; before tags.
14815 (when (< pos (point)) (goto-char pos))))))
14817 (defun org-set-tags-command (&optional arg just-align)
14818 "Call the set-tags command for the current entry."
14819 (interactive "P")
14820 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14821 (org-set-tags arg just-align)
14822 (save-excursion
14823 (unless (and (org-region-active-p)
14824 org-loop-over-headlines-in-active-region)
14825 (org-back-to-heading t))
14826 (org-set-tags arg just-align))))
14828 (defun org-set-tags-to (data)
14829 "Set the tags of the current entry to DATA, replacing the current tags.
14830 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14831 If DATA is nil or the empty string, any tags will be removed."
14832 (interactive "sTags: ")
14833 (setq data
14834 (cond
14835 ((eq data nil) "")
14836 ((equal data "") "")
14837 ((stringp data)
14838 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14839 ":"))
14840 ((listp data)
14841 (concat ":" (mapconcat 'identity data ":") ":"))))
14842 (when data
14843 (save-excursion
14844 (org-back-to-heading t)
14845 (when (let ((case-fold-search nil))
14846 (looking-at org-complex-heading-regexp))
14847 (if (match-end 5)
14848 (progn
14849 (goto-char (match-beginning 5))
14850 (insert data)
14851 (delete-region (point) (point-at-eol))
14852 (org-set-tags nil 'align))
14853 (goto-char (point-at-eol))
14854 (insert " " data)
14855 (org-set-tags nil 'align)))
14856 (beginning-of-line 1)
14857 (when (looking-at ".*?\\([ \t]+\\)$")
14858 (delete-region (match-beginning 1) (match-end 1))))))
14860 (defun org-align-all-tags ()
14861 "Align the tags in all headings."
14862 (interactive)
14863 (save-excursion
14864 (or (ignore-errors (org-back-to-heading t))
14865 (outline-next-heading))
14866 (if (org-at-heading-p)
14867 (org-set-tags t)
14868 (message "No headings"))))
14870 (defvar org-indent-indentation-per-level)
14871 (defun org-set-tags (&optional arg just-align)
14872 "Set the tags for the current headline.
14873 With prefix ARG, realign all tags in headings in the current buffer.
14874 When JUST-ALIGN is non-nil, only align tags."
14875 (interactive "P")
14876 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14877 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14878 'region-start-level
14879 'region))
14880 org-loop-over-headlines-in-active-region)
14881 (org-map-entries
14882 ;; We don't use ARG and JUST-ALIGN here because these args
14883 ;; are not useful when looping over headlines.
14884 #'org-set-tags
14885 org-loop-over-headlines-in-active-region
14887 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14888 (let ((org-setting-tags t))
14889 (if arg
14890 (save-excursion
14891 (goto-char (point-min))
14892 (while (re-search-forward org-outline-regexp-bol nil t)
14893 (org-set-tags nil t)
14894 (end-of-line))
14895 (message "All tags realigned to column %d" org-tags-column))
14896 (let* ((current (org-get-tags-string))
14897 (tags
14898 (if just-align current
14899 ;; Get a new set of tags from the user.
14900 (save-excursion
14901 (let* ((seen)
14902 (table
14903 (setq
14904 org-last-tags-completion-table
14905 ;; Uniquify tags in alists, yet preserve
14906 ;; structure (i.e., keywords).
14907 (delq nil
14908 (mapcar
14909 (lambda (pair)
14910 (let ((head (car pair)))
14911 (cond ((symbolp head) pair)
14912 ((member head seen) nil)
14913 (t (push head seen)
14914 pair))))
14915 (append
14916 (or org-current-tag-alist
14917 (org-get-buffer-tags))
14918 (and
14919 org-complete-tags-always-offer-all-agenda-tags
14920 (org-global-tags-completion-table
14921 (org-agenda-files))))))))
14922 (current-tags (org-split-string current ":"))
14923 (inherited-tags
14924 (nreverse (nthcdr (length current-tags)
14925 (nreverse (org-get-tags-at))))))
14926 (replace-regexp-in-string
14927 "\\([-+&]+\\|,\\)"
14929 (if (or (eq t org-use-fast-tag-selection)
14930 (and org-use-fast-tag-selection
14931 (delq nil (mapcar #'cdr table))))
14932 (org-fast-tag-selection
14933 current-tags inherited-tags table
14934 (and org-fast-tag-selection-include-todo
14935 org-todo-key-alist))
14936 (let ((org-add-colon-after-tag-completion
14937 (< 1 (length table))))
14938 (org-trim
14939 (completing-read
14940 "Tags: "
14941 #'org-tags-completion-function
14942 nil nil current 'org-tags-history))))))))))
14944 (when org-tags-sort-function
14945 (setq tags
14946 (mapconcat
14947 #'identity
14948 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14949 org-tags-sort-function)
14950 ":")))
14952 (if (or (string= ":" tags)
14953 (string= "::" tags))
14954 (setq tags ""))
14955 (if (not (org-string-nw-p tags)) (setq tags "")
14956 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14957 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14959 ;; Insert new tags at the correct column.
14960 (unless (equal current tags)
14961 (save-excursion
14962 (beginning-of-line)
14963 (let ((case-fold-search nil))
14964 (looking-at org-complex-heading-regexp))
14965 ;; Remove current tags, if any.
14966 (when (match-end 5) (replace-match "" nil nil nil 5))
14967 ;; Insert new tags, if any. Otherwise, remove trailing
14968 ;; white spaces.
14969 (end-of-line)
14970 (if (not (equal tags ""))
14971 ;; When text is being inserted on an invisible
14972 ;; region boundary, it can be inadvertently sucked
14973 ;; into invisibility.
14974 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14975 (skip-chars-backward " \t")
14976 (delete-region (point) (line-end-position)))))
14977 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14978 ;; is on.
14979 (unless (equal tags "")
14980 (let* ((level (save-excursion
14981 (beginning-of-line)
14982 (skip-chars-forward "\\*")))
14983 (offset (if (bound-and-true-p org-indent-mode)
14984 (* (1- org-indent-indentation-per-level)
14985 (1- level))
14987 (tags-column
14988 (+ org-tags-column
14989 (if (> org-tags-column 0) (- offset) offset))))
14990 (org--align-tags-here tags-column))))
14991 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14993 (defun org-change-tag-in-region (beg end tag off)
14994 "Add or remove TAG for each entry in the region.
14995 This works in the agenda, and also in an Org buffer."
14996 (interactive
14997 (list (region-beginning) (region-end)
14998 (let ((org-last-tags-completion-table
14999 (if (derived-mode-p 'org-mode)
15000 (org-uniquify
15001 (delq nil (append (org-get-buffer-tags)
15002 (org-global-tags-completion-table))))
15003 (org-global-tags-completion-table))))
15004 (completing-read
15005 "Tag: " 'org-tags-completion-function nil nil nil
15006 'org-tags-history))
15007 (progn
15008 (message "[s]et or [r]emove? ")
15009 (equal (read-char-exclusive) ?r))))
15010 (when (fboundp 'deactivate-mark) (deactivate-mark))
15011 (let ((agendap (equal major-mode 'org-agenda-mode))
15012 l1 l2 m buf pos newhead (cnt 0))
15013 (goto-char end)
15014 (setq l2 (1- (org-current-line)))
15015 (goto-char beg)
15016 (setq l1 (org-current-line))
15017 (cl-loop for l from l1 to l2 do
15018 (org-goto-line l)
15019 (setq m (get-text-property (point) 'org-hd-marker))
15020 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15021 (and agendap m))
15022 (setq buf (if agendap (marker-buffer m) (current-buffer))
15023 pos (if agendap m (point)))
15024 (with-current-buffer buf
15025 (save-excursion
15026 (save-restriction
15027 (goto-char pos)
15028 (setq cnt (1+ cnt))
15029 (org-toggle-tag tag (if off 'off 'on))
15030 (setq newhead (org-get-heading)))))
15031 (and agendap (org-agenda-change-all-lines newhead m))))
15032 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15034 (defun org-tags-completion-function (string _predicate &optional flag)
15035 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15036 (confirm (lambda (x) (stringp (car x)))))
15037 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15038 (setq s1 (match-string 1 string)
15039 s2 (match-string 2 string))
15040 (setq s1 "" s2 string))
15041 (cond
15042 ((eq flag nil)
15043 ;; try completion
15044 (setq rtn (try-completion s2 ctable confirm))
15045 (when (stringp rtn)
15046 (setq rtn
15047 (concat s1 s2 (substring rtn (length s2))
15048 (if (and org-add-colon-after-tag-completion
15049 (assoc rtn ctable))
15050 ":" ""))))
15051 rtn)
15052 ((eq flag t)
15053 ;; all-completions
15054 (all-completions s2 ctable confirm))
15055 ((eq flag 'lambda)
15056 ;; exact match?
15057 (assoc s2 ctable)))))
15059 (defun org-fast-tag-insert (kwd tags face &optional end)
15060 "Insert KDW, and the TAGS, the latter with face FACE.
15061 Also insert END."
15062 (insert (format "%-12s" (concat kwd ":"))
15063 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15064 (or end "")))
15066 (defun org-fast-tag-show-exit (flag)
15067 (save-excursion
15068 (org-goto-line 3)
15069 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15070 (replace-match ""))
15071 (when flag
15072 (end-of-line 1)
15073 (org-move-to-column (- (window-width) 19) t)
15074 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15076 (defun org-set-current-tags-overlay (current prefix)
15077 "Add an overlay to CURRENT tag with PREFIX."
15078 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15079 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15080 (org-overlay-display org-tags-overlay (concat prefix s))))
15082 (defvar org-last-tag-selection-key nil)
15083 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15084 "Fast tag selection with single keys.
15085 CURRENT is the current list of tags in the headline, INHERITED is the
15086 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15087 possibly with grouping information. TODO-TABLE is a similar table with
15088 TODO keywords, should these have keys assigned to them.
15089 If the keys are nil, a-z are automatically assigned.
15090 Returns the new tags string, or nil to not change the current settings."
15091 (let* ((fulltable (append table todo-table))
15092 (maxlen (apply 'max (mapcar
15093 (lambda (x)
15094 (if (stringp (car x)) (string-width (car x)) 0))
15095 fulltable)))
15096 (buf (current-buffer))
15097 (expert (eq org-fast-tag-selection-single-key 'expert))
15098 (buffer-tags nil)
15099 (fwidth (+ maxlen 3 1 3))
15100 (ncol (/ (- (window-width) 4) fwidth))
15101 (i-face 'org-done)
15102 (c-face 'org-todo)
15103 tg cnt e c char c1 c2 ntable tbl rtn
15104 ov-start ov-end ov-prefix
15105 (exit-after-next org-fast-tag-selection-single-key)
15106 (done-keywords org-done-keywords)
15107 groups ingroup intaggroup)
15108 (save-excursion
15109 (beginning-of-line 1)
15110 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15111 (setq ov-start (match-beginning 1)
15112 ov-end (match-end 1)
15113 ov-prefix "")
15114 (setq ov-start (1- (point-at-eol))
15115 ov-end (1+ ov-start))
15116 (skip-chars-forward "^\n\r")
15117 (setq ov-prefix
15118 (concat
15119 (buffer-substring (1- (point)) (point))
15120 (if (> (current-column) org-tags-column)
15122 (make-string (- org-tags-column (current-column)) ?\ ))))))
15123 (move-overlay org-tags-overlay ov-start ov-end)
15124 (save-window-excursion
15125 (if expert
15126 (set-buffer (get-buffer-create " *Org tags*"))
15127 (delete-other-windows)
15128 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15129 (org-switch-to-buffer-other-window " *Org tags*"))
15130 (erase-buffer)
15131 (setq-local org-done-keywords done-keywords)
15132 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15133 (org-fast-tag-insert "Current" current c-face "\n\n")
15134 (org-fast-tag-show-exit exit-after-next)
15135 (org-set-current-tags-overlay current ov-prefix)
15136 (setq tbl fulltable char ?a cnt 0)
15137 (while (setq e (pop tbl))
15138 (cond
15139 ((eq (car e) :startgroup)
15140 (push '() groups) (setq ingroup t)
15141 (unless (zerop cnt)
15142 (setq cnt 0)
15143 (insert "\n"))
15144 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15145 ((eq (car e) :endgroup)
15146 (setq ingroup nil cnt 0)
15147 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15148 ((eq (car e) :startgrouptag)
15149 (setq intaggroup t)
15150 (unless (zerop cnt)
15151 (setq cnt 0)
15152 (insert "\n"))
15153 (insert "[ "))
15154 ((eq (car e) :endgrouptag)
15155 (setq intaggroup nil cnt 0)
15156 (insert "]\n"))
15157 ((equal e '(:newline))
15158 (unless (zerop cnt)
15159 (setq cnt 0)
15160 (insert "\n")
15161 (setq e (car tbl))
15162 (while (equal (car tbl) '(:newline))
15163 (insert "\n")
15164 (setq tbl (cdr tbl)))))
15165 ((equal e '(:grouptags)) (insert " : "))
15167 (setq tg (copy-sequence (car e)) c2 nil)
15168 (if (cdr e)
15169 (setq c (cdr e))
15170 ;; automatically assign a character.
15171 (setq c1 (string-to-char
15172 (downcase (substring
15173 tg (if (= (string-to-char tg) ?@) 1 0)))))
15174 (if (or (rassoc c1 ntable) (rassoc c1 table))
15175 (while (or (rassoc char ntable) (rassoc char table))
15176 (setq char (1+ char)))
15177 (setq c2 c1))
15178 (setq c (or c2 char)))
15179 (when ingroup (push tg (car groups)))
15180 (setq tg (org-add-props tg nil 'face
15181 (cond
15182 ((not (assoc tg table))
15183 (org-get-todo-face tg))
15184 ((member tg current) c-face)
15185 ((member tg inherited) i-face))))
15186 (when (equal (caar tbl) :grouptags)
15187 (org-add-props tg nil 'face 'org-tag-group))
15188 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15189 (insert "[" c "] " tg (make-string
15190 (- fwidth 4 (length tg)) ?\ ))
15191 (push (cons tg c) ntable)
15192 (when (= (cl-incf cnt) ncol)
15193 (insert "\n")
15194 (when (or ingroup intaggroup) (insert " "))
15195 (setq cnt 0)))))
15196 (setq ntable (nreverse ntable))
15197 (insert "\n")
15198 (goto-char (point-min))
15199 (unless expert (org-fit-window-to-buffer))
15200 (setq rtn
15201 (catch 'exit
15202 (while t
15203 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15204 (if (not groups) "no " "")
15205 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15206 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15207 (setq org-last-tag-selection-key c)
15208 (cond
15209 ((= c ?\r) (throw 'exit t))
15210 ((= c ?!)
15211 (setq groups (not groups))
15212 (goto-char (point-min))
15213 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15214 ((= c ?\C-c)
15215 (if (not expert)
15216 (org-fast-tag-show-exit
15217 (setq exit-after-next (not exit-after-next)))
15218 (setq expert nil)
15219 (delete-other-windows)
15220 (set-window-buffer (split-window-vertically) " *Org tags*")
15221 (org-switch-to-buffer-other-window " *Org tags*")
15222 (org-fit-window-to-buffer)))
15223 ((or (= c ?\C-g)
15224 (and (= c ?q) (not (rassoc c ntable))))
15225 (delete-overlay org-tags-overlay)
15226 (setq quit-flag t))
15227 ((= c ?\ )
15228 (setq current nil)
15229 (when exit-after-next (setq exit-after-next 'now)))
15230 ((= c ?\t)
15231 (condition-case nil
15232 (setq tg (completing-read
15233 "Tag: "
15234 (or buffer-tags
15235 (with-current-buffer buf
15236 (setq buffer-tags
15237 (org-get-buffer-tags))))))
15238 (quit (setq tg "")))
15239 (when (string-match "\\S-" tg)
15240 (cl-pushnew (list tg) buffer-tags :test #'equal)
15241 (if (member tg current)
15242 (setq current (delete tg current))
15243 (push tg current)))
15244 (when exit-after-next (setq exit-after-next 'now)))
15245 ((setq e (rassoc c todo-table) tg (car e))
15246 (with-current-buffer buf
15247 (save-excursion (org-todo tg)))
15248 (when exit-after-next (setq exit-after-next 'now)))
15249 ((setq e (rassoc c ntable) tg (car e))
15250 (if (member tg current)
15251 (setq current (delete tg current))
15252 (cl-loop for g in groups do
15253 (when (member tg g)
15254 (dolist (x g) (setq current (delete x current)))))
15255 (push tg current))
15256 (when exit-after-next (setq exit-after-next 'now))))
15258 ;; Create a sorted list
15259 (setq current
15260 (sort current
15261 (lambda (a b)
15262 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15263 (when (eq exit-after-next 'now) (throw 'exit t))
15264 (goto-char (point-min))
15265 (beginning-of-line 2)
15266 (delete-region (point) (point-at-eol))
15267 (org-fast-tag-insert "Current" current c-face)
15268 (org-set-current-tags-overlay current ov-prefix)
15269 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15270 (setq tg (match-string 1))
15271 (add-text-properties
15272 (match-beginning 1) (match-end 1)
15273 (list 'face
15274 (cond
15275 ((member tg current) c-face)
15276 ((member tg inherited) i-face)
15277 (t (get-text-property (match-beginning 1) 'face))))))
15278 (goto-char (point-min)))))
15279 (delete-overlay org-tags-overlay)
15280 (if rtn
15281 (mapconcat 'identity current ":")
15282 nil))))
15284 (defun org-get-tags-string ()
15285 "Get the TAGS string in the current headline."
15286 (unless (org-at-heading-p t)
15287 (user-error "Not on a heading"))
15288 (save-excursion
15289 (beginning-of-line 1)
15290 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15291 (match-string-no-properties 1)
15292 "")))
15294 (defun org-get-tags ()
15295 "Get the list of tags specified in the current headline."
15296 (org-split-string (org-get-tags-string) ":"))
15298 (defun org-get-buffer-tags ()
15299 "Get a table of all tags used in the buffer, for completion."
15300 (org-with-wide-buffer
15301 (goto-char (point-min))
15302 (let ((tag-re (concat org-outline-regexp-bol
15303 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15304 tags)
15305 (while (re-search-forward tag-re nil t)
15306 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15307 (push tag tags)))
15308 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15310 ;;;; The mapping API
15312 (defvar org-agenda-skip-comment-trees)
15313 (defvar org-agenda-skip-function)
15314 (defun org-map-entries (func &optional match scope &rest skip)
15315 "Call FUNC at each headline selected by MATCH in SCOPE.
15317 FUNC is a function or a lisp form. The function will be called without
15318 arguments, with the cursor positioned at the beginning of the headline.
15319 The return values of all calls to the function will be collected and
15320 returned as a list.
15322 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15323 does not need to preserve point. After evaluation, the cursor will be
15324 moved to the end of the line (presumably of the headline of the
15325 processed entry) and search continues from there. Under some
15326 circumstances, this may not produce the wanted results. For example,
15327 if you have removed (e.g. archived) the current (sub)tree it could
15328 mean that the next entry will be skipped entirely. In such cases, you
15329 can specify the position from where search should continue by making
15330 FUNC set the variable `org-map-continue-from' to the desired buffer
15331 position.
15333 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15334 Only headlines that are matched by this query will be considered during
15335 the iteration. When MATCH is nil or t, all headlines will be
15336 visited by the iteration.
15338 SCOPE determines the scope of this command. It can be any of:
15340 nil The current buffer, respecting the restriction if any
15341 tree The subtree started with the entry at point
15342 region The entries within the active region, if any
15343 region-start-level
15344 The entries within the active region, but only those at
15345 the same level than the first one.
15346 file The current buffer, without restriction
15347 file-with-archives
15348 The current buffer, and any archives associated with it
15349 agenda All agenda files
15350 agenda-with-archives
15351 All agenda files with any archive files associated with them
15352 \(file1 file2 ...)
15353 If this is a list, all files in the list will be scanned
15355 The remaining args are treated as settings for the skipping facilities of
15356 the scanner. The following items can be given here:
15358 archive skip trees with the archive tag
15359 comment skip trees with the COMMENT keyword
15360 function or Emacs Lisp form:
15361 will be used as value for `org-agenda-skip-function', so
15362 whenever the function returns a position, FUNC will not be
15363 called for that entry and search will continue from the
15364 position returned
15366 If your function needs to retrieve the tags including inherited tags
15367 at the *current* entry, you can use the value of the variable
15368 `org-scanner-tags' which will be much faster than getting the value
15369 with `org-get-tags-at'. If your function gets properties with
15370 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15371 to t around the call to `org-entry-properties' to get the same speedup.
15372 Note that if your function moves around to retrieve tags and properties at
15373 a *different* entry, you cannot use these techniques."
15374 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15375 (not (org-region-active-p)))
15376 (let* ((org-agenda-archives-mode nil) ; just to make sure
15377 (org-agenda-skip-archived-trees (memq 'archive skip))
15378 (org-agenda-skip-comment-trees (memq 'comment skip))
15379 (org-agenda-skip-function
15380 (car (org-delete-all '(comment archive) skip)))
15381 (org-tags-match-list-sublevels t)
15382 (start-level (eq scope 'region-start-level))
15383 matcher res
15384 org-todo-keywords-for-agenda
15385 org-done-keywords-for-agenda
15386 org-todo-keyword-alist-for-agenda
15387 org-tag-alist-for-agenda
15388 org--matcher-tags-todo-only)
15390 (cond
15391 ((eq match t) (setq matcher t))
15392 ((eq match nil) (setq matcher t))
15393 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15395 (save-excursion
15396 (save-restriction
15397 (cond ((eq scope 'tree)
15398 (org-back-to-heading t)
15399 (org-narrow-to-subtree)
15400 (setq scope nil))
15401 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15402 (org-region-active-p))
15403 ;; If needed, set start-level to a string like "2"
15404 (when start-level
15405 (save-excursion
15406 (goto-char (region-beginning))
15407 (unless (org-at-heading-p) (outline-next-heading))
15408 (setq start-level (org-current-level))))
15409 (narrow-to-region (region-beginning)
15410 (save-excursion
15411 (goto-char (region-end))
15412 (unless (and (bolp) (org-at-heading-p))
15413 (outline-next-heading))
15414 (point)))
15415 (setq scope nil)))
15417 (if (not scope)
15418 (progn
15419 (org-agenda-prepare-buffers
15420 (and buffer-file-name (list buffer-file-name)))
15421 (setq res
15422 (org-scan-tags
15423 func matcher org--matcher-tags-todo-only start-level)))
15424 ;; Get the right scope
15425 (cond
15426 ((and scope (listp scope) (symbolp (car scope)))
15427 (setq scope (eval scope)))
15428 ((eq scope 'agenda)
15429 (setq scope (org-agenda-files t)))
15430 ((eq scope 'agenda-with-archives)
15431 (setq scope (org-agenda-files t))
15432 (setq scope (org-add-archive-files scope)))
15433 ((eq scope 'file)
15434 (setq scope (and buffer-file-name (list buffer-file-name))))
15435 ((eq scope 'file-with-archives)
15436 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15437 (org-agenda-prepare-buffers scope)
15438 (dolist (file scope)
15439 (with-current-buffer (org-find-base-buffer-visiting file)
15440 (org-with-wide-buffer
15441 (goto-char (point-min))
15442 (setq res
15443 (append
15445 (org-scan-tags
15446 func matcher org--matcher-tags-todo-only)))))))))
15447 res)))
15449 ;;; Properties API
15451 (defconst org-special-properties
15452 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15453 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15454 "The special properties valid in Org mode.
15455 These are properties that are not defined in the property drawer,
15456 but in some other way.")
15458 (defconst org-default-properties
15459 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15460 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15461 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15462 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15463 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15464 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15465 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15466 "Some properties that are used by Org mode for various purposes.
15467 Being in this list makes sure that they are offered for completion.")
15469 (defun org--valid-property-p (property)
15470 "Non nil when string PROPERTY is a valid property name."
15471 (not
15472 (or (equal property "")
15473 (string-match-p "\\s-" property))))
15475 (defun org--update-property-plist (key val props)
15476 "Associate KEY to VAL in alist PROPS.
15477 Modifications are made by side-effect. Return new alist."
15478 (let* ((appending (string= (substring key -1) "+"))
15479 (key (if appending (substring key 0 -1) key))
15480 (old (assoc-string key props t)))
15481 (if (not old) (cons (cons key val) props)
15482 (setcdr old (if appending (concat (cdr old) " " val) val))
15483 props)))
15485 (defun org-get-property-block (&optional beg force)
15486 "Return the (beg . end) range of the body of the property drawer.
15487 BEG is the beginning of the current subtree, or of the part
15488 before the first headline. If it is not given, it will be found.
15489 If the drawer does not exist, create it if FORCE is non-nil, or
15490 return nil."
15491 (org-with-wide-buffer
15492 (when beg (goto-char beg))
15493 (unless (org-before-first-heading-p)
15494 (let ((beg (cond (beg)
15495 ((or (not (featurep 'org-inlinetask))
15496 (org-inlinetask-in-task-p))
15497 (org-back-to-heading t))
15498 (t (org-with-limited-levels (org-back-to-heading t))))))
15499 (forward-line)
15500 (when (looking-at-p org-planning-line-re) (forward-line))
15501 (cond ((looking-at org-property-drawer-re)
15502 (forward-line)
15503 (cons (point) (progn (goto-char (match-end 0))
15504 (line-beginning-position))))
15505 (force
15506 (goto-char beg)
15507 (org-insert-property-drawer)
15508 (let ((pos (save-excursion (search-forward ":END:")
15509 (line-beginning-position))))
15510 (cons pos pos))))))))
15512 (defun org-at-property-p ()
15513 "Non-nil when point is inside a property drawer.
15514 See `org-property-re' for match data, if applicable."
15515 (save-excursion
15516 (beginning-of-line)
15517 (and (looking-at org-property-re)
15518 (let ((property-drawer (save-match-data (org-get-property-block))))
15519 (and property-drawer
15520 (>= (point) (car property-drawer))
15521 (< (point) (cdr property-drawer)))))))
15523 (defun org-property-action ()
15524 "Do an action on properties."
15525 (interactive)
15526 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15527 (let ((c (read-char-exclusive)))
15528 (cl-case c
15529 (?s (call-interactively #'org-set-property))
15530 (?d (call-interactively #'org-delete-property))
15531 (?D (call-interactively #'org-delete-property-globally))
15532 (?c (call-interactively #'org-compute-property-at-point))
15533 (otherwise (user-error "No such property action %c" c)))))
15535 (defun org-inc-effort ()
15536 "Increment the value of the effort property in the current entry."
15537 (interactive)
15538 (org-set-effort nil t))
15540 (defvar org-clock-effort) ; Defined in org-clock.el.
15541 (defvar org-clock-current-task) ; Defined in org-clock.el.
15542 (defun org-set-effort (&optional value increment)
15543 "Set the effort property of the current entry.
15544 With numerical prefix arg, use the nth allowed value, 0 stands for the
15545 10th allowed value.
15547 When INCREMENT is non-nil, set the property to the next allowed value."
15548 (interactive "P")
15549 (when (equal value 0) (setq value 10))
15550 (let* ((completion-ignore-case t)
15551 (prop org-effort-property)
15552 (cur (org-entry-get nil prop))
15553 (allowed (org-property-get-allowed-values nil prop 'table))
15554 (existing (mapcar 'list (org-property-values prop)))
15555 (heading (nth 4 (org-heading-components)))
15557 (val (cond
15558 ((stringp value) value)
15559 ((and allowed (integerp value))
15560 (or (car (nth (1- value) allowed))
15561 (car (org-last allowed))))
15562 ((and allowed increment)
15563 (or (cl-caadr (member (list cur) allowed))
15564 (user-error "Allowed effort values are not set")))
15565 (allowed
15566 (message "Select 1-9,0, [RET%s]: %s"
15567 (if cur (concat "=" cur) "")
15568 (mapconcat 'car allowed " "))
15569 (setq rpl (read-char-exclusive))
15570 (if (equal rpl ?\r)
15572 (setq rpl (- rpl ?0))
15573 (when (equal rpl 0) (setq rpl 10))
15574 (if (and (> rpl 0) (<= rpl (length allowed)))
15575 (car (nth (1- rpl) allowed))
15576 (org-completing-read "Effort: " allowed nil))))
15578 (org-completing-read
15579 (concat "Effort" (and cur (string-match "\\S-" cur)
15580 (concat " [" cur "]"))
15581 ": ")
15582 existing nil nil "" nil cur)))))
15583 (unless (equal (org-entry-get nil prop) val)
15584 (org-entry-put nil prop val))
15585 (org-refresh-property
15586 '((effort . identity)
15587 (effort-minutes . org-duration-to-minutes))
15588 val)
15589 (when (equal heading (bound-and-true-p org-clock-current-task))
15590 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15591 (org-clock-update-mode-line))
15592 (message "%s is now %s" prop val)))
15594 (defun org-entry-properties (&optional pom which)
15595 "Get all properties of the current entry.
15597 When POM is a buffer position, get all properties from the entry
15598 there instead.
15600 This includes the TODO keyword, the tags, time strings for
15601 deadline, scheduled, and clocking, and any additional properties
15602 defined in the entry.
15604 If WHICH is nil or `all', get all properties. If WHICH is
15605 `special' or `standard', only get that subclass. If WHICH is
15606 a string, only get that property.
15608 Return value is an alist. Keys are properties, as upcased
15609 strings."
15610 (org-with-point-at pom
15611 (when (and (derived-mode-p 'org-mode)
15612 (ignore-errors (org-back-to-heading t)))
15613 (catch 'exit
15614 (let* ((beg (point))
15615 (specific (and (stringp which) (upcase which)))
15616 (which (cond ((not specific) which)
15617 ((member specific org-special-properties) 'special)
15618 (t 'standard)))
15619 props)
15620 ;; Get the special properties, like TODO and TAGS.
15621 (when (memq which '(nil all special))
15622 (when (or (not specific) (string= specific "CLOCKSUM"))
15623 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15624 (when clocksum
15625 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15626 props)))
15627 (when specific (throw 'exit props)))
15628 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15629 (let ((clocksumt (get-text-property (point)
15630 :org-clock-minutes-today)))
15631 (when clocksumt
15632 (push (cons "CLOCKSUM_T"
15633 (org-duration-from-minutes clocksumt))
15634 props)))
15635 (when specific (throw 'exit props)))
15636 (when (or (not specific) (string= specific "ITEM"))
15637 (let ((case-fold-search nil))
15638 (when (looking-at org-complex-heading-regexp)
15639 (push (cons "ITEM"
15640 (let ((title (match-string-no-properties 4)))
15641 (if (org-string-nw-p title)
15642 (org-remove-tabs title)
15643 "")))
15644 props)))
15645 (when specific (throw 'exit props)))
15646 (when (or (not specific) (string= specific "TODO"))
15647 (let ((case-fold-search nil))
15648 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15649 (push (cons "TODO" (match-string-no-properties 2)) props)))
15650 (when specific (throw 'exit props)))
15651 (when (or (not specific) (string= specific "PRIORITY"))
15652 (push (cons "PRIORITY"
15653 (if (looking-at org-priority-regexp)
15654 (match-string-no-properties 2)
15655 (char-to-string org-default-priority)))
15656 props)
15657 (when specific (throw 'exit props)))
15658 (when (or (not specific) (string= specific "FILE"))
15659 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15660 props)
15661 (when specific (throw 'exit props)))
15662 (when (or (not specific) (string= specific "TAGS"))
15663 (let ((value (org-string-nw-p (org-get-tags-string))))
15664 (when value (push (cons "TAGS" value) props)))
15665 (when specific (throw 'exit props)))
15666 (when (or (not specific) (string= specific "ALLTAGS"))
15667 (let ((value (org-get-tags-at)))
15668 (when value
15669 (push (cons "ALLTAGS"
15670 (format ":%s:" (mapconcat #'identity value ":")))
15671 props)))
15672 (when specific (throw 'exit props)))
15673 (when (or (not specific) (string= specific "BLOCKED"))
15674 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15675 (when specific (throw 'exit props)))
15676 (when (or (not specific)
15677 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15678 (forward-line)
15679 (when (looking-at-p org-planning-line-re)
15680 (end-of-line)
15681 (let ((bol (line-beginning-position))
15682 ;; Backward compatibility: time keywords used to
15683 ;; be configurable (before 8.3). Make sure we
15684 ;; get the correct keyword.
15685 (key-assoc `(("CLOSED" . ,org-closed-string)
15686 ("DEADLINE" . ,org-deadline-string)
15687 ("SCHEDULED" . ,org-scheduled-string))))
15688 (dolist (pair (if specific (list (assoc specific key-assoc))
15689 key-assoc))
15690 (save-excursion
15691 (when (search-backward (cdr pair) bol t)
15692 (goto-char (match-end 0))
15693 (skip-chars-forward " \t")
15694 (and (looking-at org-ts-regexp-both)
15695 (push (cons (car pair)
15696 (match-string-no-properties 0))
15697 props)))))))
15698 (when specific (throw 'exit props)))
15699 (when (or (not specific)
15700 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15701 (let ((find-ts
15702 (lambda (end ts)
15703 ;; Fix next time-stamp before END. TS is the
15704 ;; list of time-stamps found so far.
15705 (let ((ts ts)
15706 (regexp (cond
15707 ((string= specific "TIMESTAMP")
15708 org-ts-regexp)
15709 ((string= specific "TIMESTAMP_IA")
15710 org-ts-regexp-inactive)
15711 ((assoc "TIMESTAMP_IA" ts)
15712 org-ts-regexp)
15713 ((assoc "TIMESTAMP" ts)
15714 org-ts-regexp-inactive)
15715 (t org-ts-regexp-both))))
15716 (catch 'next
15717 (while (re-search-forward regexp end t)
15718 (backward-char)
15719 (let ((object (org-element-context)))
15720 ;; Accept to match timestamps in node
15721 ;; properties, too.
15722 (when (memq (org-element-type object)
15723 '(node-property timestamp))
15724 (let ((type
15725 (org-element-property :type object)))
15726 (cond
15727 ((and (memq type '(active active-range))
15728 (not (equal specific "TIMESTAMP_IA")))
15729 (unless (assoc "TIMESTAMP" ts)
15730 (push (cons "TIMESTAMP"
15731 (org-element-property
15732 :raw-value object))
15734 (when specific (throw 'exit ts))))
15735 ((and (memq type '(inactive inactive-range))
15736 (not (string= specific "TIMESTAMP")))
15737 (unless (assoc "TIMESTAMP_IA" ts)
15738 (push (cons "TIMESTAMP_IA"
15739 (org-element-property
15740 :raw-value object))
15742 (when specific (throw 'exit ts))))))
15743 ;; Both timestamp types are found,
15744 ;; move to next part.
15745 (when (= (length ts) 2) (throw 'next ts)))))
15746 ts)))))
15747 (goto-char beg)
15748 ;; First look for timestamps within headline.
15749 (let ((ts (funcall find-ts (line-end-position) nil)))
15750 (if (= (length ts) 2) (setq props (nconc ts props))
15751 ;; Then find timestamps in the section, skipping
15752 ;; planning line.
15753 (let ((end (save-excursion (outline-next-heading))))
15754 (forward-line)
15755 (when (looking-at-p org-planning-line-re) (forward-line))
15756 (setq props (nconc (funcall find-ts end ts) props))))))))
15757 ;; Get the standard properties, like :PROP:.
15758 (when (memq which '(nil all standard))
15759 ;; If we are looking after a specific property, delegate
15760 ;; to `org-entry-get', which is faster. However, make an
15761 ;; exception for "CATEGORY", since it can be also set
15762 ;; through keywords (i.e. #+CATEGORY).
15763 (if (and specific (not (equal specific "CATEGORY")))
15764 (let ((value (org-entry-get beg specific nil t)))
15765 (throw 'exit (and value (list (cons specific value)))))
15766 (let ((range (org-get-property-block beg)))
15767 (when range
15768 (let ((end (cdr range)) seen-base)
15769 (goto-char (car range))
15770 ;; Unlike to `org--update-property-plist', we
15771 ;; handle the case where base values is found
15772 ;; after its extension. We also forbid standard
15773 ;; properties to be named as special properties.
15774 (while (re-search-forward org-property-re end t)
15775 (let* ((key (upcase (match-string-no-properties 2)))
15776 (extendp (string-match-p "\\+\\'" key))
15777 (key-base (if extendp (substring key 0 -1) key))
15778 (value (match-string-no-properties 3)))
15779 (cond
15780 ((member-ignore-case key-base org-special-properties))
15781 (extendp
15782 (setq props
15783 (org--update-property-plist key value props)))
15784 ((member key seen-base))
15785 (t (push key seen-base)
15786 (let ((p (assoc-string key props t)))
15787 (if p (setcdr p (concat value " " (cdr p)))
15788 (push (cons key value) props))))))))))))
15789 (unless (assoc "CATEGORY" props)
15790 (push (cons "CATEGORY" (org-get-category beg)) props)
15791 (when (string= specific "CATEGORY") (throw 'exit props)))
15792 ;; Return value.
15793 props)))))
15795 (defun org--property-local-values (property literal-nil)
15796 "Return value for PROPERTY in current entry.
15797 Value is a list whose car is the base value for PROPERTY and cdr
15798 a list of accumulated values. Return nil if neither is found in
15799 the entry. Also return nil when PROPERTY is set to \"nil\",
15800 unless LITERAL-NIL is non-nil."
15801 (let ((range (org-get-property-block)))
15802 (when range
15803 (goto-char (car range))
15804 (let* ((case-fold-search t)
15805 (end (cdr range))
15806 (value
15807 ;; Base value.
15808 (save-excursion
15809 (let ((v (and (re-search-forward
15810 (org-re-property property nil t) end t)
15811 (match-string-no-properties 3))))
15812 (list (if literal-nil v (org-not-nil v)))))))
15813 ;; Find additional values.
15814 (let* ((property+ (org-re-property (concat property "+") nil t)))
15815 (while (re-search-forward property+ end t)
15816 (push (match-string-no-properties 3) value)))
15817 ;; Return final values.
15818 (and (not (equal value '(nil))) (nreverse value))))))
15820 (defun org--property-global-value (property literal-nil)
15821 "Return value for PROPERTY in current buffer.
15822 Return value is a string. Return nil if property is not set
15823 globally. Also return nil when PROPERTY is set to \"nil\",
15824 unless LITERAL-NIL is non-nil."
15825 (let ((global
15826 (cdr (or (assoc-string property org-file-properties t)
15827 (assoc-string property org-global-properties t)
15828 (assoc-string property org-global-properties-fixed t)))))
15829 (if literal-nil global (org-not-nil global))))
15831 (defun org-entry-get (pom property &optional inherit literal-nil)
15832 "Get value of PROPERTY for entry or content at point-or-marker POM.
15834 If INHERIT is non-nil and the entry does not have the property,
15835 then also check higher levels of the hierarchy. If INHERIT is
15836 the symbol `selective', use inheritance only if the setting in
15837 `org-use-property-inheritance' selects PROPERTY for inheritance.
15839 If the property is present but empty, the return value is the
15840 empty string. If the property is not present at all, nil is
15841 returned. In any other case, return the value as a string.
15842 Search is case-insensitive.
15844 If LITERAL-NIL is set, return the string value \"nil\" as
15845 a string, do not interpret it as the list atom nil. This is used
15846 for inheritance when a \"nil\" value can supersede a non-nil
15847 value higher up the hierarchy."
15848 (org-with-point-at pom
15849 (cond
15850 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15851 ;; We need a special property. Use `org-entry-properties' to
15852 ;; retrieve it, but specify the wanted property.
15853 (cdr (assoc-string property (org-entry-properties nil property))))
15854 ((and inherit
15855 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15856 (org-entry-get-with-inheritance property literal-nil))
15858 (let* ((local (org--property-local-values property literal-nil))
15859 (value (and local (mapconcat #'identity (delq nil local) " "))))
15860 (if literal-nil value (org-not-nil value)))))))
15862 (defun org-property-or-variable-value (var &optional inherit)
15863 "Check if there is a property fixing the value of VAR.
15864 If yes, return this value. If not, return the current value of the variable."
15865 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15866 (if (and prop (stringp prop) (string-match "\\S-" prop))
15867 (read prop)
15868 (symbol-value var))))
15870 (defun org-entry-delete (pom property)
15871 "Delete PROPERTY from entry at point-or-marker POM.
15872 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15873 non-nil when a property was removed."
15874 (org-with-point-at pom
15875 (pcase (org-get-property-block)
15876 (`(,begin . ,origin)
15877 (let* ((end (copy-marker origin))
15878 (re (org-re-property
15879 (concat (regexp-quote property) "\\+?") t t)))
15880 (goto-char begin)
15881 (while (re-search-forward re end t)
15882 (delete-region (match-beginning 0) (line-beginning-position 2)))
15883 ;; If drawer is empty, remove it altogether.
15884 (when (= begin end)
15885 (delete-region (line-beginning-position 0)
15886 (line-beginning-position 2)))
15887 ;; Return non-nil if some property was removed.
15888 (prog1 (/= end origin) (set-marker end nil))))
15889 (_ nil))))
15891 ;; Multi-values properties are properties that contain multiple values
15892 ;; These values are assumed to be single words, separated by whitespace.
15893 (defun org-entry-add-to-multivalued-property (pom property value)
15894 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15895 (let* ((old (org-entry-get pom property))
15896 (values (and old (org-split-string old "[ \t]"))))
15897 (setq value (org-entry-protect-space value))
15898 (unless (member value values)
15899 (setq values (append values (list value)))
15900 (org-entry-put pom property
15901 (mapconcat 'identity values " ")))))
15903 (defun org-entry-remove-from-multivalued-property (pom property value)
15904 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15905 (let* ((old (org-entry-get pom property))
15906 (values (and old (org-split-string old "[ \t]"))))
15907 (setq value (org-entry-protect-space value))
15908 (when (member value values)
15909 (setq values (delete value values))
15910 (org-entry-put pom property
15911 (mapconcat 'identity values " ")))))
15913 (defun org-entry-member-in-multivalued-property (pom property value)
15914 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15915 (let* ((old (org-entry-get pom property))
15916 (values (and old (org-split-string old "[ \t]"))))
15917 (setq value (org-entry-protect-space value))
15918 (member value values)))
15920 (defun org-entry-get-multivalued-property (pom property)
15921 "Return a list of values in a multivalued property."
15922 (let* ((value (org-entry-get pom property))
15923 (values (and value (org-split-string value "[ \t]"))))
15924 (mapcar 'org-entry-restore-space values)))
15926 (defun org-entry-put-multivalued-property (pom property &rest values)
15927 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15928 VALUES should be a list of strings. Spaces will be protected."
15929 (org-entry-put pom property
15930 (mapconcat 'org-entry-protect-space values " "))
15931 (let* ((value (org-entry-get pom property))
15932 (values (and value (org-split-string value "[ \t]"))))
15933 (mapcar 'org-entry-restore-space values)))
15935 (defun org-entry-protect-space (s)
15936 "Protect spaces and newline in string S."
15937 (while (string-match " " s)
15938 (setq s (replace-match "%20" t t s)))
15939 (while (string-match "\n" s)
15940 (setq s (replace-match "%0A" t t s)))
15943 (defun org-entry-restore-space (s)
15944 "Restore spaces and newline in string S."
15945 (while (string-match "%20" s)
15946 (setq s (replace-match " " t t s)))
15947 (while (string-match "%0A" s)
15948 (setq s (replace-match "\n" t t s)))
15951 (defvar org-entry-property-inherited-from (make-marker)
15952 "Marker pointing to the entry from where a property was inherited.
15953 Each call to `org-entry-get-with-inheritance' will set this marker to the
15954 location of the entry where the inheritance search matched. If there was
15955 no match, the marker will point nowhere.
15956 Note that also `org-entry-get' calls this function, if the INHERIT flag
15957 is set.")
15959 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15960 "Get PROPERTY of entry or content at point, search higher levels if needed.
15961 The search will stop at the first ancestor which has the property defined.
15962 If the value found is \"nil\", return nil to show that the property
15963 should be considered as undefined (this is the meaning of nil here).
15964 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15965 (move-marker org-entry-property-inherited-from nil)
15966 (org-with-wide-buffer
15967 (let (value)
15968 (catch 'exit
15969 (while t
15970 (let ((v (org--property-local-values property literal-nil)))
15971 (when v
15972 (setq value
15973 (concat (mapconcat #'identity (delq nil v) " ")
15974 (and value " ")
15975 value)))
15976 (cond
15977 ((car v)
15978 (org-back-to-heading t)
15979 (move-marker org-entry-property-inherited-from (point))
15980 (throw 'exit nil))
15981 ((org-up-heading-safe))
15983 (let ((global (org--property-global-value property literal-nil)))
15984 (cond ((not global))
15985 (value (setq value (concat global " " value)))
15986 (t (setq value global))))
15987 (throw 'exit nil))))))
15988 (if literal-nil value (org-not-nil value)))))
15990 (defvar org-property-changed-functions nil
15991 "Hook called when the value of a property has changed.
15992 Each hook function should accept two arguments, the name of the property
15993 and the new value.")
15995 (defun org-entry-put (pom property value)
15996 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15998 If the value is nil, it is converted to the empty string. If it
15999 is not a string, an error is raised. Also raise an error on
16000 invalid property names.
16002 PROPERTY can be any regular property (see
16003 `org-special-properties'). It can also be \"TODO\",
16004 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16006 For the last two properties, VALUE may have any of the special
16007 values \"earlier\" and \"later\". The function then increases or
16008 decreases scheduled or deadline date by one day."
16009 (cond ((null value) (setq value ""))
16010 ((not (stringp value)) (error "Properties values should be strings"))
16011 ((not (org--valid-property-p property))
16012 (user-error "Invalid property name: \"%s\"" property)))
16013 (org-with-point-at pom
16014 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16015 (org-back-to-heading t)
16016 (org-with-limited-levels (org-back-to-heading t)))
16017 (let ((beg (point)))
16018 (cond
16019 ((equal property "TODO")
16020 (cond ((not (org-string-nw-p value)) (setq value 'none))
16021 ((not (member value org-todo-keywords-1))
16022 (user-error "\"%s\" is not a valid TODO state" value)))
16023 (org-todo value)
16024 (org-set-tags nil 'align))
16025 ((equal property "PRIORITY")
16026 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16027 (org-set-tags nil 'align))
16028 ((equal property "SCHEDULED")
16029 (forward-line)
16030 (if (and (looking-at-p org-planning-line-re)
16031 (re-search-forward
16032 org-scheduled-time-regexp (line-end-position) t))
16033 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16034 ((string= value "later") (org-timestamp-change 1 'day))
16035 ((string= value "") (org-schedule '(4)))
16036 (t (org-schedule nil value)))
16037 (if (member value '("earlier" "later" ""))
16038 (call-interactively #'org-schedule)
16039 (org-schedule nil value))))
16040 ((equal property "DEADLINE")
16041 (forward-line)
16042 (if (and (looking-at-p org-planning-line-re)
16043 (re-search-forward
16044 org-deadline-time-regexp (line-end-position) t))
16045 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16046 ((string= value "later") (org-timestamp-change 1 'day))
16047 ((string= value "") (org-deadline '(4)))
16048 (t (org-deadline nil value)))
16049 (if (member value '("earlier" "later" ""))
16050 (call-interactively #'org-deadline)
16051 (org-deadline nil value))))
16052 ((member property org-special-properties)
16053 (error "The %s property cannot be set with `org-entry-put'" property))
16055 (let* ((range (org-get-property-block beg 'force))
16056 (end (cdr range))
16057 (case-fold-search t))
16058 (goto-char (car range))
16059 (if (re-search-forward (org-re-property property nil t) end t)
16060 (progn (delete-region (match-beginning 0) (match-end 0))
16061 (goto-char (match-beginning 0)))
16062 (goto-char end)
16063 (insert "\n")
16064 (backward-char))
16065 (insert ":" property ":")
16066 (when value (insert " " value))
16067 (org-indent-line)))))
16068 (run-hook-with-args 'org-property-changed-functions property value)))
16070 (defun org-buffer-property-keys
16071 (&optional specials defaults columns ignore-malformed)
16072 "Get all property keys in the current buffer.
16074 When SPECIALS is non-nil, also list the special properties that
16075 reflect things like tags and TODO state.
16077 When DEFAULTS is non-nil, also include properties that has
16078 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16079 DESCRIPTION, LOCATION, and LOGGING and others.
16081 When COLUMNS in non-nil, also include property names given in
16082 COLUMN formats in the current buffer.
16084 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16085 automatically performed, such drawers will be silently ignored."
16086 (let ((case-fold-search t)
16087 (props (append
16088 (and specials org-special-properties)
16089 (and defaults (cons org-effort-property org-default-properties))
16090 nil)))
16091 (org-with-wide-buffer
16092 (goto-char (point-min))
16093 (while (re-search-forward org-property-start-re nil t)
16094 (let ((range (org-get-property-block)))
16095 (catch 'skip
16096 (unless range
16097 (when (and (not ignore-malformed)
16098 (not (org-before-first-heading-p))
16099 (y-or-n-p (format "Malformed drawer at %d, repair?"
16100 (line-beginning-position))))
16101 (org-get-property-block nil t))
16102 (throw 'skip nil))
16103 (goto-char (car range))
16104 (let ((begin (car range))
16105 (end (cdr range)))
16106 ;; Make sure that found property block is not located
16107 ;; before current point, as it would generate an infloop.
16108 ;; It can happen, for example, in the following
16109 ;; situation:
16111 ;; * Headline
16112 ;; :PROPERTIES:
16113 ;; ...
16114 ;; :END:
16115 ;; *************** Inlinetask
16116 ;; #+BEGIN_EXAMPLE
16117 ;; :PROPERTIES:
16118 ;; #+END_EXAMPLE
16120 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16121 (while (< (point) end)
16122 (let ((p (progn (looking-at org-property-re)
16123 (match-string-no-properties 2))))
16124 ;; Only add true property name, not extension symbol.
16125 (push (if (not (string-match-p "\\+\\'" p)) p
16126 (substring p 0 -1))
16127 props))
16128 (forward-line))))
16129 (outline-next-heading)))
16130 (when columns
16131 (goto-char (point-min))
16132 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16133 (let ((element (org-element-at-point)))
16134 (when (memq (org-element-type element) '(keyword node-property))
16135 (let ((value (org-element-property :value element))
16136 (start 0))
16137 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16138 (setq start (match-end 0))
16139 (let ((p (match-string-no-properties 1 value)))
16140 (unless (member-ignore-case p org-special-properties)
16141 (push p props))))))))))
16142 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16144 (defun org-property-values (key)
16145 "List all non-nil values of property KEY in current buffer."
16146 (org-with-wide-buffer
16147 (goto-char (point-min))
16148 (let ((case-fold-search t)
16149 (re (org-re-property key))
16150 values)
16151 (while (re-search-forward re nil t)
16152 (push (org-entry-get (point) key) values))
16153 (delete-dups values))))
16155 (defun org-insert-property-drawer ()
16156 "Insert a property drawer into the current entry."
16157 (org-with-wide-buffer
16158 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16159 (org-back-to-heading t)
16160 (org-with-limited-levels (org-back-to-heading t)))
16161 (forward-line)
16162 (when (looking-at-p org-planning-line-re) (forward-line))
16163 (unless (looking-at-p org-property-drawer-re)
16164 ;; Make sure we start editing a line from current entry, not from
16165 ;; next one. It prevents extending text properties or overlays
16166 ;; belonging to the latter.
16167 (when (bolp) (backward-char))
16168 (let ((begin (1+ (point)))
16169 (inhibit-read-only t))
16170 (insert "\n:PROPERTIES:\n:END:")
16171 (when (eobp) (insert "\n"))
16172 (org-indent-region begin (point))))))
16174 (defun org-insert-drawer (&optional arg drawer)
16175 "Insert a drawer at point.
16177 When optional argument ARG is non-nil, insert a property drawer.
16179 Optional argument DRAWER, when non-nil, is a string representing
16180 drawer's name. Otherwise, the user is prompted for a name.
16182 If a region is active, insert the drawer around that region
16183 instead.
16185 Point is left between drawer's boundaries."
16186 (interactive "P")
16187 (let* ((drawer (if arg "PROPERTIES"
16188 (or drawer (read-from-minibuffer "Drawer: ")))))
16189 (cond
16190 ;; With C-u, fall back on `org-insert-property-drawer'
16191 (arg (org-insert-property-drawer))
16192 ;; Check validity of suggested drawer's name.
16193 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16194 (user-error "Invalid drawer name"))
16195 ;; With an active region, insert a drawer at point.
16196 ((not (org-region-active-p))
16197 (progn
16198 (unless (bolp) (insert "\n"))
16199 (insert (format ":%s:\n\n:END:\n" drawer))
16200 (forward-line -2)))
16201 ;; Otherwise, insert the drawer at point
16203 (let ((rbeg (region-beginning))
16204 (rend (copy-marker (region-end))))
16205 (unwind-protect
16206 (progn
16207 (goto-char rbeg)
16208 (beginning-of-line)
16209 (when (save-excursion
16210 (re-search-forward org-outline-regexp-bol rend t))
16211 (user-error "Drawers cannot contain headlines"))
16212 ;; Position point at the beginning of the first
16213 ;; non-blank line in region. Insert drawer's opening
16214 ;; there, then indent it.
16215 (org-skip-whitespace)
16216 (beginning-of-line)
16217 (insert ":" drawer ":\n")
16218 (forward-line -1)
16219 (indent-for-tab-command)
16220 ;; Move point to the beginning of the first blank line
16221 ;; after the last non-blank line in region. Insert
16222 ;; drawer's closing, then indent it.
16223 (goto-char rend)
16224 (skip-chars-backward " \r\t\n")
16225 (insert "\n:END:")
16226 (deactivate-mark t)
16227 (indent-for-tab-command)
16228 (unless (eolp) (insert "\n")))
16229 ;; Clear marker, whatever the outcome of insertion is.
16230 (set-marker rend nil)))))))
16232 (defvar org-property-set-functions-alist nil
16233 "Property set function alist.
16234 Each entry should have the following format:
16236 (PROPERTY . READ-FUNCTION)
16238 The read function will be called with the same argument as
16239 `org-completing-read'.")
16241 (defun org-set-property-function (property)
16242 "Get the function that should be used to set PROPERTY.
16243 This is computed according to `org-property-set-functions-alist'."
16244 (or (cdr (assoc property org-property-set-functions-alist))
16245 'org-completing-read))
16247 (defun org-read-property-value (property)
16248 "Read PROPERTY value from user."
16249 (let* ((completion-ignore-case t)
16250 (allowed (org-property-get-allowed-values nil property 'table))
16251 (cur (org-entry-get nil property))
16252 (prompt (concat property " value"
16253 (if (and cur (string-match "\\S-" cur))
16254 (concat " [" cur "]") "") ": "))
16255 (set-function (org-set-property-function property))
16256 (val (if allowed
16257 (funcall set-function prompt allowed nil
16258 (not (get-text-property 0 'org-unrestricted
16259 (caar allowed))))
16260 (funcall set-function prompt
16261 (mapcar 'list (org-property-values property))
16262 nil nil "" nil cur))))
16263 (org-trim val)))
16265 (defvar org-last-set-property nil)
16266 (defvar org-last-set-property-value nil)
16267 (defun org-read-property-name ()
16268 "Read a property name."
16269 (let ((completion-ignore-case t)
16270 (default-prop (or (and (org-at-property-p)
16271 (match-string-no-properties 2))
16272 org-last-set-property)))
16273 (org-completing-read
16274 (concat "Property"
16275 (if default-prop (concat " [" default-prop "]") "")
16276 ": ")
16277 (mapcar #'list (org-buffer-property-keys nil t t))
16278 nil nil nil nil default-prop)))
16280 (defun org-set-property-and-value (use-last)
16281 "Allow to set [PROPERTY]: [value] direction from prompt.
16282 When use-default, don't even ask, just use the last
16283 \"[PROPERTY]: [value]\" string from the history."
16284 (interactive "P")
16285 (let* ((completion-ignore-case t)
16286 (pv (or (and use-last org-last-set-property-value)
16287 (org-completing-read
16288 "Enter a \"[Property]: [value]\" pair: "
16289 nil nil nil nil nil
16290 org-last-set-property-value)))
16291 prop val)
16292 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16293 (setq prop (match-string 1 pv)
16294 val (match-string 2 pv))
16295 (org-set-property prop val))))
16297 (defun org-set-property (property value)
16298 "In the current entry, set PROPERTY to VALUE.
16300 When called interactively, this will prompt for a property name, offering
16301 completion on existing and default properties. And then it will prompt
16302 for a value, offering completion either on allowed values (via an inherited
16303 xxx_ALL property) or on existing values in other instances of this property
16304 in the current file.
16306 Throw an error when trying to set a property with an invalid name."
16307 (interactive (list nil nil))
16308 (let ((property (or property (org-read-property-name))))
16309 ;; `org-entry-put' also makes the following check, but this one
16310 ;; avoids polluting `org-last-set-property' and
16311 ;; `org-last-set-property-value' needlessly.
16312 (unless (org--valid-property-p property)
16313 (user-error "Invalid property name: \"%s\"" property))
16314 (let ((value (or value (org-read-property-value property)))
16315 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16316 (setq org-last-set-property property)
16317 (setq org-last-set-property-value (concat property ": " value))
16318 ;; Possibly postprocess the inserted value:
16319 (when fn (setq value (funcall fn value)))
16320 (unless (equal (org-entry-get nil property) value)
16321 (org-entry-put nil property value)))))
16323 (defun org-find-property (property &optional value)
16324 "Find first entry in buffer that sets PROPERTY.
16326 When optional argument VALUE is non-nil, only consider an entry
16327 if it contains PROPERTY set to this value. If PROPERTY should be
16328 explicitly set to nil, use string \"nil\" for VALUE.
16330 Return position where the entry begins, or nil if there is no
16331 such entry. If narrowing is in effect, only search the visible
16332 part of the buffer."
16333 (save-excursion
16334 (goto-char (point-min))
16335 (let ((case-fold-search t)
16336 (re (org-re-property property nil (not value) value)))
16337 (catch 'exit
16338 (while (re-search-forward re nil t)
16339 (when (if value (org-at-property-p)
16340 (org-entry-get (point) property nil t))
16341 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16343 (defun org-delete-property (property)
16344 "In the current entry, delete PROPERTY."
16345 (interactive
16346 (let* ((completion-ignore-case t)
16347 (cat (org-entry-get (point) "CATEGORY"))
16348 (props0 (org-entry-properties nil 'standard))
16349 (props (if cat props0
16350 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16351 (prop (if (< 1 (length props))
16352 (completing-read "Property: " props nil t)
16353 (caar props))))
16354 (list prop)))
16355 (if (not property)
16356 (message "No property to delete in this entry")
16357 (org-entry-delete nil property)
16358 (message "Property \"%s\" deleted" property)))
16360 (defun org-delete-property-globally (property)
16361 "Remove PROPERTY globally, from all entries.
16362 This function ignores narrowing, if any."
16363 (interactive
16364 (let* ((completion-ignore-case t)
16365 (prop (completing-read
16366 "Globally remove property: "
16367 (mapcar #'list (org-buffer-property-keys)))))
16368 (list prop)))
16369 (org-with-wide-buffer
16370 (goto-char (point-min))
16371 (let ((count 0)
16372 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16373 (while (re-search-forward re nil t)
16374 (when (org-entry-delete (point) property) (cl-incf count)))
16375 (message "Property \"%s\" removed from %d entries" property count))))
16377 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16379 (defun org-compute-property-at-point ()
16380 "Compute the property at point.
16381 This looks for an enclosing column format, extracts the operator and
16382 then applies it to the property in the column format's scope."
16383 (interactive)
16384 (unless (org-at-property-p)
16385 (user-error "Not at a property"))
16386 (let ((prop (match-string-no-properties 2)))
16387 (org-columns-get-format-and-top-level)
16388 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16389 (user-error "No operator defined for property %s" prop))
16390 (org-columns-compute prop)))
16392 (defvar org-property-allowed-value-functions nil
16393 "Hook for functions supplying allowed values for a specific property.
16394 The functions must take a single argument, the name of the property, and
16395 return a flat list of allowed values. If \":ETC\" is one of
16396 the values, this means that these values are intended as defaults for
16397 completion, but that other values should be allowed too.
16398 The functions must return nil if they are not responsible for this
16399 property.")
16401 (defun org-property-get-allowed-values (pom property &optional table)
16402 "Get allowed values for the property PROPERTY.
16403 When TABLE is non-nil, return an alist that can directly be used for
16404 completion."
16405 (let (vals)
16406 (cond
16407 ((equal property "TODO")
16408 (setq vals (org-with-point-at pom
16409 (append org-todo-keywords-1 '("")))))
16410 ((equal property "PRIORITY")
16411 (let ((n org-lowest-priority))
16412 (while (>= n org-highest-priority)
16413 (push (char-to-string n) vals)
16414 (setq n (1- n)))))
16415 ((equal property "CATEGORY"))
16416 ((member property org-special-properties))
16417 ((setq vals (run-hook-with-args-until-success
16418 'org-property-allowed-value-functions property)))
16420 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16421 (when (and vals (string-match "\\S-" vals))
16422 (setq vals (car (read-from-string (concat "(" vals ")"))))
16423 (setq vals (mapcar (lambda (x)
16424 (cond ((stringp x) x)
16425 ((numberp x) (number-to-string x))
16426 ((symbolp x) (symbol-name x))
16427 (t "???")))
16428 vals)))))
16429 (when (member ":ETC" vals)
16430 (setq vals (remove ":ETC" vals))
16431 (org-add-props (car vals) '(org-unrestricted t)))
16432 (if table (mapcar 'list vals) vals)))
16434 (defun org-property-previous-allowed-value (&optional _previous)
16435 "Switch to the next allowed value for this property."
16436 (interactive)
16437 (org-property-next-allowed-value t))
16439 (defun org-property-next-allowed-value (&optional previous)
16440 "Switch to the next allowed value for this property."
16441 (interactive)
16442 (unless (org-at-property-p)
16443 (user-error "Not at a property"))
16444 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16445 (key (match-string 2))
16446 (value (match-string 3))
16447 (allowed (or (org-property-get-allowed-values (point) key)
16448 (and (member value '("[ ]" "[-]" "[X]"))
16449 '("[ ]" "[X]"))))
16450 (heading (save-match-data (nth 4 (org-heading-components))))
16451 nval)
16452 (unless allowed
16453 (user-error "Allowed values for this property have not been defined"))
16454 (when previous (setq allowed (reverse allowed)))
16455 (when (member value allowed)
16456 (setq nval (car (cdr (member value allowed)))))
16457 (setq nval (or nval (car allowed)))
16458 (when (equal nval value)
16459 (user-error "Only one allowed value for this property"))
16460 (org-at-property-p)
16461 (replace-match (concat " :" key ": " nval) t t)
16462 (org-indent-line)
16463 (beginning-of-line 1)
16464 (skip-chars-forward " \t")
16465 (when (equal prop org-effort-property)
16466 (org-refresh-property
16467 '((effort . identity)
16468 (effort-minutes . org-duration-to-minutes))
16469 nval)
16470 (when (string= org-clock-current-task heading)
16471 (setq org-clock-effort nval)
16472 (org-clock-update-mode-line)))
16473 (run-hook-with-args 'org-property-changed-functions key nval)))
16475 (defun org-find-olp (path &optional this-buffer)
16476 "Return a marker pointing to the entry at outline path OLP.
16477 If anything goes wrong, throw an error.
16478 You can wrap this call to catch the error like this:
16480 (condition-case msg
16481 (org-mobile-locate-entry (match-string 4))
16482 (error (nth 1 msg)))
16484 The return value will then be either a string with the error message,
16485 or a marker if everything is OK.
16487 If THIS-BUFFER is set, the outline path does not contain a file,
16488 only headings."
16489 (let* ((file (if this-buffer buffer-file-name (pop path)))
16490 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16491 (level 1)
16492 (lmin 1)
16493 (lmax 1)
16494 end found flevel)
16495 (unless buffer (error "File not found :%s" file))
16496 (with-current-buffer buffer
16497 (unless (derived-mode-p 'org-mode)
16498 (error "Buffer %s needs to be in Org mode" buffer))
16499 (org-with-wide-buffer
16500 (goto-char (point-min))
16501 (dolist (heading path)
16502 (let ((re (format org-complex-heading-regexp-format
16503 (regexp-quote heading)))
16504 (cnt 0))
16505 (while (re-search-forward re end t)
16506 (setq level (- (match-end 1) (match-beginning 1)))
16507 (when (and (>= level lmin) (<= level lmax))
16508 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16509 (when (= cnt 0)
16510 (error "Heading not found on level %d: %s" lmax heading))
16511 (when (> cnt 1)
16512 (error "Heading not unique on level %d: %s" lmax heading))
16513 (goto-char found)
16514 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16515 (setq end (save-excursion (org-end-of-subtree t t)))))
16516 (when (org-at-heading-p)
16517 (point-marker))))))
16519 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16520 "Find node HEADING in BUFFER.
16521 Return a marker to the heading if it was found, or nil if not.
16522 If POS-ONLY is set, return just the position instead of a marker.
16524 The heading text must match exact, but it may have a TODO keyword,
16525 a priority cookie and tags in the standard locations."
16526 (with-current-buffer (or buffer (current-buffer))
16527 (org-with-wide-buffer
16528 (goto-char (point-min))
16529 (let (case-fold-search)
16530 (when (re-search-forward
16531 (format org-complex-heading-regexp-format
16532 (regexp-quote heading)) nil t)
16533 (if pos-only
16534 (match-beginning 0)
16535 (move-marker (make-marker) (match-beginning 0))))))))
16537 (defun org-find-exact-heading-in-directory (heading &optional dir)
16538 "Find Org node headline HEADING in all .org files in directory DIR.
16539 When the target headline is found, return a marker to this location."
16540 (let ((files (directory-files (or dir default-directory)
16541 t "\\`[^.#].*\\.org\\'"))
16542 visiting m buffer)
16543 (catch 'found
16544 (dolist (file files)
16545 (message "trying %s" file)
16546 (setq visiting (org-find-base-buffer-visiting file))
16547 (setq buffer (or visiting (find-file-noselect file)))
16548 (setq m (org-find-exact-headline-in-buffer
16549 heading buffer))
16550 (when (and (not m) (not visiting)) (kill-buffer buffer))
16551 (and m (throw 'found m))))))
16553 (defun org-find-entry-with-id (ident)
16554 "Locate the entry that contains the ID property with exact value IDENT.
16555 IDENT can be a string, a symbol or a number, this function will search for
16556 the string representation of it.
16557 Return the position where this entry starts, or nil if there is no such entry."
16558 (interactive "sID: ")
16559 (let ((id (cond
16560 ((stringp ident) ident)
16561 ((symbolp ident) (symbol-name ident))
16562 ((numberp ident) (number-to-string ident))
16563 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16564 (org-with-wide-buffer (org-find-property "ID" id))))
16566 ;;;; Timestamps
16568 (defvar org-last-changed-timestamp nil)
16569 (defvar org-last-inserted-timestamp nil
16570 "The last time stamp inserted with `org-insert-time-stamp'.")
16572 (defun org-time-stamp (arg &optional inactive)
16573 "Prompt for a date/time and insert a time stamp.
16575 If the user specifies a time like HH:MM or if this command is
16576 called with at least one prefix argument, the time stamp contains
16577 the date and the time. Otherwise, only the date is included.
16579 All parts of a date not specified by the user are filled in from
16580 the timestamp at point, if any, or the current date/time
16581 otherwise.
16583 If there is already a timestamp at the cursor, it is replaced.
16585 With two universal prefix arguments, insert an active timestamp
16586 with the current time without prompting the user.
16588 When called from lisp, the timestamp is inactive if INACTIVE is
16589 non-nil."
16590 (interactive "P")
16591 (let* ((ts (cond
16592 ((org-at-date-range-p t)
16593 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16594 ((org-at-timestamp-p 'lax) (match-string 0))))
16595 ;; Default time is either the timestamp at point or today.
16596 ;; When entering a range, only the range start is considered.
16597 (default-time (if (not ts) (current-time)
16598 (apply #'encode-time (org-parse-time-string ts))))
16599 (default-input (and ts (org-get-compact-tod ts)))
16600 (repeater (and ts
16601 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16602 (match-string 0 ts)))
16603 org-time-was-given
16604 org-end-time-was-given
16605 (time
16606 (and (if (equal arg '(16)) (current-time)
16607 ;; Preserve `this-command' and `last-command'.
16608 (let ((this-command this-command)
16609 (last-command last-command))
16610 (org-read-date
16611 arg 'totime nil nil default-time default-input
16612 inactive))))))
16613 (cond
16614 ((and ts
16615 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16616 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16617 (insert "--")
16618 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16620 ;; Make sure we're on a timestamp. When in the middle of a date
16621 ;; range, move arbitrarily to range end.
16622 (unless (org-at-timestamp-p 'lax)
16623 (skip-chars-forward "-")
16624 (org-at-timestamp-p 'lax))
16625 (replace-match "")
16626 (setq org-last-changed-timestamp
16627 (org-insert-time-stamp
16628 time (or org-time-was-given arg)
16629 inactive nil nil (list org-end-time-was-given)))
16630 (when repeater
16631 (backward-char)
16632 (insert " " repeater)
16633 (setq org-last-changed-timestamp
16634 (concat (substring org-last-inserted-timestamp 0 -1)
16635 " " repeater ">")))
16636 (message "Timestamp updated"))
16637 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16638 (t (org-insert-time-stamp
16639 time (or org-time-was-given arg) inactive nil nil
16640 (list org-end-time-was-given))))))
16642 ;; FIXME: can we use this for something else, like computing time differences?
16643 (defun org-get-compact-tod (s)
16644 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16645 (let* ((t1 (match-string 1 s))
16646 (h1 (string-to-number (match-string 2 s)))
16647 (m1 (string-to-number (match-string 3 s)))
16648 (t2 (and (match-end 4) (match-string 5 s)))
16649 (h2 (and t2 (string-to-number (match-string 6 s))))
16650 (m2 (and t2 (string-to-number (match-string 7 s))))
16651 dh dm)
16652 (if (not t2)
16654 (setq dh (- h2 h1) dm (- m2 m1))
16655 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16656 (concat t1 "+" (number-to-string dh)
16657 (and (/= 0 dm) (format ":%02d" dm)))))))
16659 (defun org-time-stamp-inactive (&optional arg)
16660 "Insert an inactive time stamp.
16661 An inactive time stamp is enclosed in square brackets instead of angle
16662 brackets. It is inactive in the sense that it does not trigger agenda entries,
16663 does not link to the calendar and cannot be changed with the S-cursor keys.
16664 So these are more for recording a certain time/date."
16665 (interactive "P")
16666 (org-time-stamp arg 'inactive))
16668 (defvar org-date-ovl (make-overlay 1 1))
16669 (overlay-put org-date-ovl 'face 'org-date-selected)
16670 (delete-overlay org-date-ovl)
16672 (defvar org-ans1) ; dynamically scoped parameter
16673 (defvar org-ans2) ; dynamically scoped parameter
16675 (defvar org-plain-time-of-day-regexp) ; defined below
16677 (defvar org-overriding-default-time nil) ; dynamically scoped
16678 (defvar org-read-date-overlay nil)
16679 (defvar org-dcst nil) ; dynamically scoped
16680 (defvar org-read-date-history nil)
16681 (defvar org-read-date-final-answer nil)
16682 (defvar org-read-date-analyze-futurep nil)
16683 (defvar org-read-date-analyze-forced-year nil)
16684 (defvar org-read-date-inactive)
16686 (defvar org-read-date-minibuffer-local-map
16687 (let* ((map (make-sparse-keymap)))
16688 (set-keymap-parent map minibuffer-local-map)
16689 (org-defkey map (kbd ".")
16690 (lambda () (interactive)
16691 ;; Are we at the beginning of the prompt?
16692 (if (looking-back "^[^:]+: "
16693 (let ((inhibit-field-text-motion t))
16694 (line-beginning-position)))
16695 (org-eval-in-calendar '(calendar-goto-today))
16696 (insert "."))))
16697 (org-defkey map (kbd "C-.")
16698 (lambda () (interactive)
16699 (org-eval-in-calendar '(calendar-goto-today))))
16700 (org-defkey map [(meta shift left)]
16701 (lambda () (interactive)
16702 (org-eval-in-calendar '(calendar-backward-month 1))))
16703 (org-defkey map [(meta shift right)]
16704 (lambda () (interactive)
16705 (org-eval-in-calendar '(calendar-forward-month 1))))
16706 (org-defkey map [(meta shift up)]
16707 (lambda () (interactive)
16708 (org-eval-in-calendar '(calendar-backward-year 1))))
16709 (org-defkey map [(meta shift down)]
16710 (lambda () (interactive)
16711 (org-eval-in-calendar '(calendar-forward-year 1))))
16712 (org-defkey map [?\e (shift left)]
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-backward-month 1))))
16715 (org-defkey map [?\e (shift right)]
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-forward-month 1))))
16718 (org-defkey map [?\e (shift up)]
16719 (lambda () (interactive)
16720 (org-eval-in-calendar '(calendar-backward-year 1))))
16721 (org-defkey map [?\e (shift down)]
16722 (lambda () (interactive)
16723 (org-eval-in-calendar '(calendar-forward-year 1))))
16724 (org-defkey map [(shift up)]
16725 (lambda () (interactive)
16726 (org-eval-in-calendar '(calendar-backward-week 1))))
16727 (org-defkey map [(shift down)]
16728 (lambda () (interactive)
16729 (org-eval-in-calendar '(calendar-forward-week 1))))
16730 (org-defkey map [(shift left)]
16731 (lambda () (interactive)
16732 (org-eval-in-calendar '(calendar-backward-day 1))))
16733 (org-defkey map [(shift right)]
16734 (lambda () (interactive)
16735 (org-eval-in-calendar '(calendar-forward-day 1))))
16736 (org-defkey map "!"
16737 (lambda () (interactive)
16738 (org-eval-in-calendar '(diary-view-entries))
16739 (message "")))
16740 (org-defkey map ">"
16741 (lambda () (interactive)
16742 (org-eval-in-calendar '(calendar-scroll-left 1))))
16743 (org-defkey map "<"
16744 (lambda () (interactive)
16745 (org-eval-in-calendar '(calendar-scroll-right 1))))
16746 (org-defkey map "\C-v"
16747 (lambda () (interactive)
16748 (org-eval-in-calendar
16749 '(calendar-scroll-left-three-months 1))))
16750 (org-defkey map "\M-v"
16751 (lambda () (interactive)
16752 (org-eval-in-calendar
16753 '(calendar-scroll-right-three-months 1))))
16754 map)
16755 "Keymap for minibuffer commands when using `org-read-date'.")
16757 (defvar org-def)
16758 (defvar org-defdecode)
16759 (defvar org-with-time)
16761 (defvar calendar-setup) ; Dynamically scoped.
16762 (defun org-read-date (&optional with-time to-time from-string prompt
16763 default-time default-input inactive)
16764 "Read a date, possibly a time, and make things smooth for the user.
16765 The prompt will suggest to enter an ISO date, but you can also enter anything
16766 which will at least partially be understood by `parse-time-string'.
16767 Unrecognized parts of the date will default to the current day, month, year,
16768 hour and minute. If this command is called to replace a timestamp at point,
16769 or to enter the second timestamp of a range, the default time is taken
16770 from the existing stamp. Furthermore, the command prefers the future,
16771 so if you are giving a date where the year is not given, and the day-month
16772 combination is already past in the current year, it will assume you
16773 mean next year. For details, see the manual. A few examples:
16775 3-2-5 --> 2003-02-05
16776 feb 15 --> currentyear-02-15
16777 2/15 --> currentyear-02-15
16778 sep 12 9 --> 2009-09-12
16779 12:45 --> today 12:45
16780 22 sept 0:34 --> currentyear-09-22 0:34
16781 12 --> currentyear-currentmonth-12
16782 Fri --> nearest Friday after today
16783 -Tue --> last Tuesday
16784 etc.
16786 Furthermore you can specify a relative date by giving, as the *first* thing
16787 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16788 change in days weeks, months, years.
16789 With a single plus or minus, the date is relative to today. With a double
16790 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16791 +4d --> four days from today
16792 +4 --> same as above
16793 +2w --> two weeks from today
16794 ++5 --> five days from default date
16796 The function understands only English month and weekday abbreviations.
16798 While prompting, a calendar is popped up - you can also select the
16799 date with the mouse (button 1). The calendar shows a period of three
16800 months. To scroll it to other months, use the keys `>' and `<'.
16801 If you don't like the calendar, turn it off with
16802 (setq org-read-date-popup-calendar nil)
16804 With optional argument TO-TIME, the date will immediately be converted
16805 to an internal time.
16806 With an optional argument WITH-TIME, the prompt will suggest to
16807 also insert a time. Note that when WITH-TIME is not set, you can
16808 still enter a time, and this function will inform the calling routine
16809 about this change. The calling routine may then choose to change the
16810 format used to insert the time stamp into the buffer to include the time.
16811 With optional argument FROM-STRING, read from this string instead from
16812 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16813 the time/date that is used for everything that is not specified by the
16814 user."
16815 (require 'parse-time)
16816 (let* ((org-with-time with-time)
16817 (org-time-stamp-rounding-minutes
16818 (if (equal org-with-time '(16))
16819 '(0 0)
16820 org-time-stamp-rounding-minutes))
16821 (org-dcst org-display-custom-times)
16822 (ct (org-current-time))
16823 (org-def (or org-overriding-default-time default-time ct))
16824 (org-defdecode (decode-time org-def))
16825 (cur-frame (selected-frame))
16826 (mouse-autoselect-window nil) ; Don't let the mouse jump
16827 (calendar-setup
16828 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16829 (calendar-move-hook nil)
16830 (calendar-view-diary-initially-flag nil)
16831 (calendar-view-holidays-initially-flag nil)
16832 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16833 ;; Rationalize `org-def' and `org-defdecode', if required.
16834 (when (< (nth 2 org-defdecode) org-extend-today-until)
16835 (setf (nth 2 org-defdecode) -1)
16836 (setf (nth 1 org-defdecode) 59)
16837 (setq org-def (apply #'encode-time org-defdecode))
16838 (setq org-defdecode (decode-time org-def)))
16839 (let* ((timestr (format-time-string
16840 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16841 org-def))
16842 (prompt (concat (if prompt (concat prompt " ") "")
16843 (format "Date+time [%s]: " timestr))))
16844 (cond
16845 (from-string (setq ans from-string))
16846 (org-read-date-popup-calendar
16847 (save-excursion
16848 (save-window-excursion
16849 (calendar)
16850 (when (eq calendar-setup 'calendar-only)
16851 (setq cal-frame
16852 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16853 (select-frame cal-frame))
16854 (org-eval-in-calendar '(setq cursor-type nil) t)
16855 (unwind-protect
16856 (progn
16857 (calendar-forward-day (- (time-to-days org-def)
16858 (calendar-absolute-from-gregorian
16859 (calendar-current-date))))
16860 (org-eval-in-calendar nil t)
16861 (let* ((old-map (current-local-map))
16862 (map (copy-keymap calendar-mode-map))
16863 (minibuffer-local-map
16864 (copy-keymap org-read-date-minibuffer-local-map)))
16865 (org-defkey map (kbd "RET") 'org-calendar-select)
16866 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16867 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16868 (unwind-protect
16869 (progn
16870 (use-local-map map)
16871 (setq org-read-date-inactive inactive)
16872 (add-hook 'post-command-hook 'org-read-date-display)
16873 (setq org-ans0
16874 (read-string prompt
16875 default-input
16876 'org-read-date-history
16877 nil))
16878 ;; org-ans0: from prompt
16879 ;; org-ans1: from mouse click
16880 ;; org-ans2: from calendar motion
16881 (setq ans
16882 (concat org-ans0 " " (or org-ans1 org-ans2))))
16883 (remove-hook 'post-command-hook 'org-read-date-display)
16884 (use-local-map old-map)
16885 (when org-read-date-overlay
16886 (delete-overlay org-read-date-overlay)
16887 (setq org-read-date-overlay nil)))))
16888 (bury-buffer "*Calendar*")
16889 (when cal-frame
16890 (delete-frame cal-frame)
16891 (select-frame-set-input-focus cur-frame))))))
16893 (t ; Naked prompt only
16894 (unwind-protect
16895 (setq ans (read-string prompt default-input
16896 'org-read-date-history timestr))
16897 (when org-read-date-overlay
16898 (delete-overlay org-read-date-overlay)
16899 (setq org-read-date-overlay nil))))))
16901 (setq final (org-read-date-analyze ans org-def org-defdecode))
16903 (when org-read-date-analyze-forced-year
16904 (message "Year was forced into %s"
16905 (if org-read-date-force-compatible-dates
16906 "compatible range (1970-2037)"
16907 "range representable on this machine"))
16908 (ding))
16910 ;; One round trip to get rid of 34th of August and stuff like that....
16911 (setq final (decode-time (apply 'encode-time final)))
16913 (setq org-read-date-final-answer ans)
16915 (if to-time
16916 (apply 'encode-time final)
16917 (if (and (boundp 'org-time-was-given) org-time-was-given)
16918 (format "%04d-%02d-%02d %02d:%02d"
16919 (nth 5 final) (nth 4 final) (nth 3 final)
16920 (nth 2 final) (nth 1 final))
16921 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16923 (defun org-read-date-display ()
16924 "Display the current date prompt interpretation in the minibuffer."
16925 (when org-read-date-display-live
16926 (when org-read-date-overlay
16927 (delete-overlay org-read-date-overlay))
16928 (when (minibufferp (current-buffer))
16929 (save-excursion
16930 (end-of-line 1)
16931 (while (not (equal (buffer-substring
16932 (max (point-min) (- (point) 4)) (point))
16933 " "))
16934 (insert " ")))
16935 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16936 " " (or org-ans1 org-ans2)))
16937 (org-end-time-was-given nil)
16938 (f (org-read-date-analyze ans org-def org-defdecode))
16939 (fmts (if org-dcst
16940 org-time-stamp-custom-formats
16941 org-time-stamp-formats))
16942 (fmt (if (or org-with-time
16943 (and (boundp 'org-time-was-given) org-time-was-given))
16944 (cdr fmts)
16945 (car fmts)))
16946 (txt (format-time-string fmt (apply 'encode-time f)))
16947 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16948 (txt (concat "=> " txt)))
16949 (when (and org-end-time-was-given
16950 (string-match org-plain-time-of-day-regexp txt))
16951 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16952 org-end-time-was-given
16953 (substring txt (match-end 0)))))
16954 (when org-read-date-analyze-futurep
16955 (setq txt (concat txt " (=>F)")))
16956 (setq org-read-date-overlay
16957 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16958 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16960 (defun org-read-date-analyze (ans def defdecode)
16961 "Analyze the combined answer of the date prompt."
16962 ;; FIXME: cleanup and comment
16963 ;; Pass `current-time' result to `decode-time' (instead of calling
16964 ;; without arguments) so that only `current-time' has to be
16965 ;; overriden in tests.
16966 (let ((org-def def)
16967 (org-defdecode defdecode)
16968 (nowdecode (decode-time (current-time)))
16969 delta deltan deltaw deltadef year month day
16970 hour minute second wday pm h2 m2 tl wday1
16971 iso-year iso-weekday iso-week iso-date futurep kill-year)
16972 (setq org-read-date-analyze-futurep nil
16973 org-read-date-analyze-forced-year nil)
16974 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16975 (setq ans "+0"))
16977 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16978 (setq ans (replace-match "" t t ans)
16979 deltan (car delta)
16980 deltaw (nth 1 delta)
16981 deltadef (nth 2 delta)))
16983 ;; Check if there is an iso week date in there. If yes, store the
16984 ;; info and postpone interpreting it until the rest of the parsing
16985 ;; is done.
16986 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16987 (setq iso-year (when (match-end 1)
16988 (org-small-year-to-year
16989 (string-to-number (match-string 1 ans))))
16990 iso-weekday (when (match-end 3)
16991 (string-to-number (match-string 3 ans)))
16992 iso-week (string-to-number (match-string 2 ans)))
16993 (setq ans (replace-match "" t t ans)))
16995 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16996 (when (string-match
16997 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16998 (setq year (if (match-end 2)
16999 (string-to-number (match-string 2 ans))
17000 (progn (setq kill-year t)
17001 (string-to-number (format-time-string "%Y"))))
17002 month (string-to-number (match-string 3 ans))
17003 day (string-to-number (match-string 4 ans)))
17004 (setq year (org-small-year-to-year year))
17005 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17006 t nil ans)))
17008 ;; Help matching dotted european dates
17009 (when (string-match
17010 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17011 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17012 (setq kill-year t)
17013 (string-to-number (format-time-string "%Y")))
17014 day (string-to-number (match-string 1 ans))
17015 month (string-to-number (match-string 2 ans))
17016 ans (replace-match (format "%04d-%02d-%02d" year month day)
17017 t nil ans)))
17019 ;; Help matching american dates, like 5/30 or 5/30/7
17020 (when (string-match
17021 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17022 (setq year (if (match-end 4)
17023 (string-to-number (match-string 4 ans))
17024 (progn (setq kill-year t)
17025 (string-to-number (format-time-string "%Y"))))
17026 month (string-to-number (match-string 1 ans))
17027 day (string-to-number (match-string 2 ans)))
17028 (setq year (org-small-year-to-year year))
17029 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17030 t nil ans)))
17031 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17032 ;; If there is a time with am/pm, and *no* time without it, we convert
17033 ;; so that matching will be successful.
17034 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17035 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17036 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17037 (setq hour (string-to-number (match-string 1 ans))
17038 minute (if (match-end 3)
17039 (string-to-number (match-string 3 ans))
17041 pm (equal ?p
17042 (string-to-char (downcase (match-string 4 ans)))))
17043 (if (and (= hour 12) (not pm))
17044 (setq hour 0)
17045 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17046 (setq ans (replace-match (format "%02d:%02d" hour minute)
17047 t t ans))))
17049 ;; Check if a time range is given as a duration
17050 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17051 (setq hour (string-to-number (match-string 1 ans))
17052 h2 (+ hour (string-to-number (match-string 3 ans)))
17053 minute (string-to-number (match-string 2 ans))
17054 m2 (+ minute (if (match-end 5) (string-to-number
17055 (match-string 5 ans))0)))
17056 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17057 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17058 t t ans)))
17060 ;; Check if there is a time range
17061 (when (boundp 'org-end-time-was-given)
17062 (setq org-time-was-given nil)
17063 (when (and (string-match org-plain-time-of-day-regexp ans)
17064 (match-end 8))
17065 (setq org-end-time-was-given (match-string 8 ans))
17066 (setq ans (concat (substring ans 0 (match-beginning 7))
17067 (substring ans (match-end 7))))))
17069 (setq tl (parse-time-string ans)
17070 day (or (nth 3 tl) (nth 3 org-defdecode))
17071 month
17072 (cond ((nth 4 tl))
17073 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17074 ;; Day was specified. Make sure DAY+MONTH
17075 ;; combination happens in the future.
17076 ((nth 3 tl)
17077 (setq futurep t)
17078 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17079 (nth 4 nowdecode)))
17080 (t (nth 4 org-defdecode)))
17081 year
17082 (cond ((and (not kill-year) (nth 5 tl)))
17083 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17084 ;; Month was guessed in the future and is at least
17085 ;; equal to NOWDECODE's. Fix year accordingly.
17086 (futurep
17087 (if (or (> month (nth 4 nowdecode))
17088 (>= day (nth 3 nowdecode)))
17089 (nth 5 nowdecode)
17090 (1+ (nth 5 nowdecode))))
17091 ;; Month was specified. Make sure MONTH+YEAR
17092 ;; combination happens in the future.
17093 ((nth 4 tl)
17094 (setq futurep t)
17095 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17096 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17097 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17098 (t (nth 5 nowdecode))))
17099 (t (nth 5 org-defdecode)))
17100 hour (or (nth 2 tl) (nth 2 org-defdecode))
17101 minute (or (nth 1 tl) (nth 1 org-defdecode))
17102 second (or (nth 0 tl) 0)
17103 wday (nth 6 tl))
17105 (when (and (eq org-read-date-prefer-future 'time)
17106 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17107 (equal day (nth 3 nowdecode))
17108 (equal month (nth 4 nowdecode))
17109 (equal year (nth 5 nowdecode))
17110 (nth 2 tl)
17111 (or (< (nth 2 tl) (nth 2 nowdecode))
17112 (and (= (nth 2 tl) (nth 2 nowdecode))
17113 (nth 1 tl)
17114 (< (nth 1 tl) (nth 1 nowdecode)))))
17115 (setq day (1+ day)
17116 futurep t))
17118 ;; Special date definitions below
17119 (cond
17120 (iso-week
17121 ;; There was an iso week
17122 (require 'cal-iso)
17123 (setq futurep nil)
17124 (setq year (or iso-year year)
17125 day (or iso-weekday wday 1)
17126 wday nil ; to make sure that the trigger below does not match
17127 iso-date (calendar-gregorian-from-absolute
17128 (calendar-iso-to-absolute
17129 (list iso-week day year))))
17130 ; FIXME: Should we also push ISO weeks into the future?
17131 ; (when (and org-read-date-prefer-future
17132 ; (not iso-year)
17133 ; (< (calendar-absolute-from-gregorian iso-date)
17134 ; (time-to-days (current-time))))
17135 ; (setq year (1+ year)
17136 ; iso-date (calendar-gregorian-from-absolute
17137 ; (calendar-iso-to-absolute
17138 ; (list iso-week day year)))))
17139 (setq month (car iso-date)
17140 year (nth 2 iso-date)
17141 day (nth 1 iso-date)))
17142 (deltan
17143 (setq futurep nil)
17144 (unless deltadef
17145 ;; Pass `current-time' result to `decode-time' (instead of
17146 ;; calling without arguments) so that only `current-time' has
17147 ;; to be overriden in tests.
17148 (let ((now (decode-time (current-time))))
17149 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17150 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17151 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17152 ((equal deltaw "m") (setq month (+ month deltan)))
17153 ((equal deltaw "y") (setq year (+ year deltan)))))
17154 ((and wday (not (nth 3 tl)))
17155 ;; Weekday was given, but no day, so pick that day in the week
17156 ;; on or after the derived date.
17157 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17158 (unless (equal wday wday1)
17159 (setq day (+ day (% (- wday wday1 -7) 7))))))
17160 (when (and (boundp 'org-time-was-given)
17161 (nth 2 tl))
17162 (setq org-time-was-given t))
17163 (when (< year 100) (setq year (+ 2000 year)))
17164 ;; Check of the date is representable
17165 (if org-read-date-force-compatible-dates
17166 (progn
17167 (when (< year 1970)
17168 (setq year 1970 org-read-date-analyze-forced-year t))
17169 (when (> year 2037)
17170 (setq year 2037 org-read-date-analyze-forced-year t)))
17171 (condition-case nil
17172 (ignore (encode-time second minute hour day month year))
17173 (error
17174 (setq year (nth 5 org-defdecode))
17175 (setq org-read-date-analyze-forced-year t))))
17176 (setq org-read-date-analyze-futurep futurep)
17177 (list second minute hour day month year)))
17179 (defvar parse-time-weekdays)
17180 (defun org-read-date-get-relative (s today default)
17181 "Check string S for special relative date string.
17182 TODAY and DEFAULT are internal times, for today and for a default.
17183 Return shift list (N what def-flag)
17184 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17185 N is the number of WHATs to shift.
17186 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17187 the DEFAULT date rather than TODAY."
17188 (require 'parse-time)
17189 (when (and
17190 (string-match
17191 (concat
17192 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17193 "\\([0-9]+\\)?"
17194 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17195 "\\([ \t]\\|$\\)") s)
17196 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17197 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17198 (string-to-char (substring (match-string 1 s) -1))
17199 ?+))
17200 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17201 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17202 (what (if (match-end 3) (match-string 3 s) "d"))
17203 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17204 (date (if rel default today))
17205 (wday (nth 6 (decode-time date)))
17206 delta)
17207 (if wday1
17208 (progn
17209 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17210 (when (= delta 0) (setq delta 7))
17211 (when (= dir ?-)
17212 (setq delta (- delta 7))
17213 (when (= delta 0) (setq delta -7)))
17214 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17215 (list delta "d" rel))
17216 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17218 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17219 "Turn a user-specified date into the internal representation.
17220 The internal representation needed by the calendar is (month day year).
17221 This is a wrapper to handle the brain-dead convention in calendar that
17222 user function argument order change dependent on argument order."
17223 (pcase calendar-date-style
17224 (`american (list arg1 arg2 arg3))
17225 (`european (list arg2 arg1 arg3))
17226 (`iso (list arg2 arg3 arg1))))
17228 (defun org-eval-in-calendar (form &optional keepdate)
17229 "Eval FORM in the calendar window and return to current window.
17230 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17231 (let ((sf (selected-frame))
17232 (sw (selected-window)))
17233 (select-window (get-buffer-window "*Calendar*" t))
17234 (eval form)
17235 (when (and (not keepdate) (calendar-cursor-to-date))
17236 (let* ((date (calendar-cursor-to-date))
17237 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17238 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17239 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17240 (select-window sw)
17241 (select-frame-set-input-focus sf)))
17243 (defun org-calendar-select ()
17244 "Return to `org-read-date' with the date currently selected.
17245 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17246 (interactive)
17247 (when (calendar-cursor-to-date)
17248 (let* ((date (calendar-cursor-to-date))
17249 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17250 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17251 (when (active-minibuffer-window) (exit-minibuffer))))
17253 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17254 "Insert a date stamp for the date given by the internal TIME.
17255 See `format-time-string' for the format of TIME.
17256 WITH-HM means use the stamp format that includes the time of the day.
17257 INACTIVE means use square brackets instead of angular ones, so that the
17258 stamp will not contribute to the agenda.
17259 PRE and POST are optional strings to be inserted before and after the
17260 stamp.
17261 The command returns the inserted time stamp."
17262 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17263 stamp)
17264 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17265 (insert-before-markers (or pre ""))
17266 (when (listp extra)
17267 (setq extra (car extra))
17268 (if (and (stringp extra)
17269 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17270 (setq extra (format "-%02d:%02d"
17271 (string-to-number (match-string 1 extra))
17272 (string-to-number (match-string 2 extra))))
17273 (setq extra nil)))
17274 (when extra
17275 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17276 (insert-before-markers (setq stamp (format-time-string fmt time)))
17277 (insert-before-markers (or post ""))
17278 (setq org-last-inserted-timestamp stamp)))
17280 (defun org-toggle-time-stamp-overlays ()
17281 "Toggle the use of custom time stamp formats."
17282 (interactive)
17283 (setq org-display-custom-times (not org-display-custom-times))
17284 (unless org-display-custom-times
17285 (let ((p (point-min)) (bmp (buffer-modified-p)))
17286 (while (setq p (next-single-property-change p 'display))
17287 (when (and (get-text-property p 'display)
17288 (eq (get-text-property p 'face) 'org-date))
17289 (remove-text-properties
17290 p (setq p (next-single-property-change p 'display))
17291 '(display t))))
17292 (set-buffer-modified-p bmp)))
17293 (org-restart-font-lock)
17294 (setq org-table-may-need-update t)
17295 (if org-display-custom-times
17296 (message "Time stamps are overlaid with custom format")
17297 (message "Time stamp overlays removed")))
17299 (defun org-display-custom-time (beg end)
17300 "Overlay modified time stamp format over timestamp between BEG and END."
17301 (let* ((ts (buffer-substring beg end))
17302 t1 w1 with-hm tf time str w2 (off 0))
17303 (save-match-data
17304 (setq t1 (org-parse-time-string ts t))
17305 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17306 (setq off (- (match-end 0) (match-beginning 0)))))
17307 (setq end (- end off))
17308 (setq w1 (- end beg)
17309 with-hm (and (nth 1 t1) (nth 2 t1))
17310 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17311 time (org-fix-decoded-time t1)
17312 str (org-add-props
17313 (format-time-string
17314 (substring tf 1 -1) (apply 'encode-time time))
17315 nil 'mouse-face 'highlight)
17316 w2 (length str))
17317 (unless (= w2 w1)
17318 (add-text-properties (1+ beg) (+ 2 beg)
17319 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17320 (put-text-property beg end 'display str)))
17322 (defun org-fix-decoded-time (time)
17323 "Set 0 instead of nil for the first 6 elements of time.
17324 Don't touch the rest."
17325 (let ((n 0))
17326 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17328 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17329 "Difference between TIMESTAMP-STRING and now in days.
17330 If SECONDS is non-nil, return the difference in seconds."
17331 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17332 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17333 (funcall fdiff (current-time)))))
17335 (defun org-deadline-close-p (timestamp-string &optional ndays)
17336 "Is the time in TIMESTAMP-STRING close to the current date?"
17337 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17338 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17339 (not (org-entry-is-done-p))))
17341 (defun org-get-wdays (ts &optional delay zero-delay)
17342 "Get the deadline lead time appropriate for timestring TS.
17343 When DELAY is non-nil, get the delay time for scheduled items
17344 instead of the deadline lead time. When ZERO-DELAY is non-nil
17345 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17346 don't try to find the delay cookie in the scheduled timestamp."
17347 (let ((tv (if delay org-scheduled-delay-days
17348 org-deadline-warning-days)))
17349 (cond
17350 ((or (and delay (< tv 0))
17351 (and delay zero-delay (<= tv 0))
17352 (and (not delay) (<= tv 0)))
17353 ;; Enforce this value no matter what
17354 (- tv))
17355 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17356 ;; lead time is specified.
17357 (floor (* (string-to-number (match-string 1 ts))
17358 (cdr (assoc (match-string 2 ts)
17359 '(("d" . 1) ("w" . 7)
17360 ("m" . 30.4) ("y" . 365.25)
17361 ("h" . 0.041667)))))))
17362 ;; go for the default.
17363 (t tv))))
17365 (defun org-calendar-select-mouse (ev)
17366 "Return to `org-read-date' with the date currently selected.
17367 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17368 (interactive "e")
17369 (mouse-set-point ev)
17370 (when (calendar-cursor-to-date)
17371 (let* ((date (calendar-cursor-to-date))
17372 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17373 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17374 (when (active-minibuffer-window) (exit-minibuffer))))
17376 (defun org-check-deadlines (ndays)
17377 "Check if there are any deadlines due or past due.
17378 A deadline is considered due if it happens within `org-deadline-warning-days'
17379 days from today's date. If the deadline appears in an entry marked DONE,
17380 it is not shown. A numeric prefix argument NDAYS can be used to test that
17381 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17382 are shown."
17383 (interactive "P")
17384 (let* ((org-warn-days
17385 (cond
17386 ((equal ndays '(4)) 100000)
17387 (ndays (prefix-numeric-value ndays))
17388 (t (abs org-deadline-warning-days))))
17389 (case-fold-search nil)
17390 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17391 (callback
17392 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17393 (message "%d deadlines past-due or due within %d days"
17394 (org-occur regexp nil callback)
17395 org-warn-days)))
17397 (defsubst org-re-timestamp (type)
17398 "Return a regexp for timestamp TYPE.
17399 Allowed values for TYPE are:
17401 all: all timestamps
17402 active: only active timestamps (<...>)
17403 inactive: only inactive timestamps ([...])
17404 scheduled: only scheduled timestamps
17405 deadline: only deadline timestamps
17406 closed: only closed time-stamps
17408 When TYPE is nil, fall back on returning a regexp that matches
17409 both scheduled and deadline timestamps."
17410 (cl-case type
17411 (all org-ts-regexp-both)
17412 (active org-ts-regexp)
17413 (inactive org-ts-regexp-inactive)
17414 (scheduled org-scheduled-time-regexp)
17415 (deadline org-deadline-time-regexp)
17416 (closed org-closed-time-regexp)
17417 (otherwise
17418 (concat "\\<"
17419 (regexp-opt (list org-deadline-string org-scheduled-string))
17420 " *<\\([^>]+\\)>"))))
17422 (defun org-check-before-date (d)
17423 "Check if there are deadlines or scheduled entries before date D."
17424 (interactive (list (org-read-date)))
17425 (let* ((case-fold-search nil)
17426 (regexp (org-re-timestamp org-ts-type))
17427 (ts-type org-ts-type)
17428 (callback
17429 (lambda ()
17430 (let ((match (match-string 1)))
17431 (and (if (memq ts-type '(active inactive all))
17432 (eq (org-element-type (save-excursion
17433 (backward-char)
17434 (org-element-context)))
17435 'timestamp)
17436 (org-at-planning-p))
17437 (time-less-p
17438 (org-time-string-to-time match)
17439 (org-time-string-to-time d)))))))
17440 (message "%d entries before %s"
17441 (org-occur regexp nil callback)
17442 d)))
17444 (defun org-check-after-date (d)
17445 "Check if there are deadlines or scheduled entries after date D."
17446 (interactive (list (org-read-date)))
17447 (let* ((case-fold-search nil)
17448 (regexp (org-re-timestamp org-ts-type))
17449 (ts-type org-ts-type)
17450 (callback
17451 (lambda ()
17452 (let ((match (match-string 1)))
17453 (and (if (memq ts-type '(active inactive all))
17454 (eq (org-element-type (save-excursion
17455 (backward-char)
17456 (org-element-context)))
17457 'timestamp)
17458 (org-at-planning-p))
17459 (not (time-less-p
17460 (org-time-string-to-time match)
17461 (org-time-string-to-time d))))))))
17462 (message "%d entries after %s"
17463 (org-occur regexp nil callback)
17464 d)))
17466 (defun org-check-dates-range (start-date end-date)
17467 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17468 (interactive (list (org-read-date nil nil nil "Range starts")
17469 (org-read-date nil nil nil "Range end")))
17470 (let ((case-fold-search nil)
17471 (regexp (org-re-timestamp org-ts-type))
17472 (callback
17473 (let ((type org-ts-type))
17474 (lambda ()
17475 (let ((match (match-string 1)))
17476 (and
17477 (if (memq type '(active inactive all))
17478 (eq (org-element-type (save-excursion
17479 (backward-char)
17480 (org-element-context)))
17481 'timestamp)
17482 (org-at-planning-p))
17483 (not (time-less-p
17484 (org-time-string-to-time match)
17485 (org-time-string-to-time start-date)))
17486 (time-less-p
17487 (org-time-string-to-time match)
17488 (org-time-string-to-time end-date))))))))
17489 (message "%d entries between %s and %s"
17490 (org-occur regexp nil callback) start-date end-date)))
17492 (defun org-evaluate-time-range (&optional to-buffer)
17493 "Evaluate a time range by computing the difference between start and end.
17494 Normally the result is just printed in the echo area, but with prefix arg
17495 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17496 If the time range is actually in a table, the result is inserted into the
17497 next column.
17498 For time difference computation, a year is assumed to be exactly 365
17499 days in order to avoid rounding problems."
17500 (interactive "P")
17502 (org-clock-update-time-maybe)
17503 (save-excursion
17504 (unless (org-at-date-range-p t)
17505 (goto-char (point-at-bol))
17506 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17507 (unless (org-at-date-range-p t)
17508 (user-error "Not at a time-stamp range, and none found in current line")))
17509 (let* ((ts1 (match-string 1))
17510 (ts2 (match-string 2))
17511 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17512 (match-end (match-end 0))
17513 (time1 (org-time-string-to-time ts1))
17514 (time2 (org-time-string-to-time ts2))
17515 (t1 (float-time time1))
17516 (t2 (float-time time2))
17517 (diff (abs (- t2 t1)))
17518 (negative (< (- t2 t1) 0))
17519 ;; (ys (floor (* 365 24 60 60)))
17520 (ds (* 24 60 60))
17521 (hs (* 60 60))
17522 (fy "%dy %dd %02d:%02d")
17523 (fy1 "%dy %dd")
17524 (fd "%dd %02d:%02d")
17525 (fd1 "%dd")
17526 (fh "%02d:%02d")
17527 y d h m align)
17528 (if havetime
17529 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17531 d (floor (/ diff ds)) diff (mod diff ds)
17532 h (floor (/ diff hs)) diff (mod diff hs)
17533 m (floor (/ diff 60)))
17534 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17536 d (floor (+ (/ diff ds) 0.5))
17537 h 0 m 0))
17538 (if (not to-buffer)
17539 (message "%s" (org-make-tdiff-string y d h m))
17540 (if (org-at-table-p)
17541 (progn
17542 (goto-char match-end)
17543 (setq align t)
17544 (and (looking-at " *|") (goto-char (match-end 0))))
17545 (goto-char match-end))
17546 (when (looking-at
17547 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17548 (replace-match ""))
17549 (when negative (insert " -"))
17550 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17551 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17552 (insert " " (format fh h m))))
17553 (when align (org-table-align))
17554 (message "Time difference inserted")))))
17556 (defun org-make-tdiff-string (y d h m)
17557 (let ((fmt "")
17558 (l nil))
17559 (when (> y 0)
17560 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17561 (push y l))
17562 (when (> d 0)
17563 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17564 (push d l))
17565 (when (> h 0)
17566 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17567 (push h l))
17568 (when (> m 0)
17569 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17570 (push m l))
17571 (apply 'format fmt (nreverse l))))
17573 (defun org-time-string-to-time (s &optional buffer pos)
17574 "Convert a timestamp string into internal time."
17575 (condition-case errdata
17576 (apply 'encode-time (org-parse-time-string s))
17577 (error (error "Bad timestamp `%s'%s\nError was: %s"
17578 s (if (not (and buffer pos))
17580 (format-message " at %d in buffer `%s'" pos buffer))
17581 (cdr errdata)))))
17583 (defun org-time-string-to-seconds (s)
17584 "Convert a timestamp string to a number of seconds."
17585 (float-time (org-time-string-to-time s)))
17587 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17589 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17590 "Convert time stamp S to an absolute day number.
17592 If DAYNR in non-nil, and there is a specifier for a cyclic time
17593 stamp, get the closest date to DAYNR. If PREFER is
17594 `past' (respectively `future') return a date past (respectively
17595 after) or equal to DAYNR.
17597 POS is the location of time stamp S, as a buffer position in
17598 BUFFER.
17600 Diary sexp timestamps are matched against DAYNR, when non-nil.
17601 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17602 signalled."
17603 (cond
17604 ((string-match "\\`%%\\((.*)\\)" s)
17605 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17606 ;; only able to match individual dates. If it fails, raise an
17607 ;; error.
17608 (if (and daynr
17609 (org-diary-sexp-entry
17610 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17611 daynr
17612 (signal 'org-diary-sexp-no-match (list s))))
17613 (daynr (org-closest-date s daynr prefer))
17614 (t (time-to-days
17615 (condition-case errdata
17616 (apply #'encode-time (org-parse-time-string s))
17617 (error (error "Bad timestamp `%s'%s\nError was: %s"
17619 (if (not (and buffer pos)) ""
17620 (format-message " at %d in buffer `%s'" pos buffer))
17621 (cdr errdata))))))))
17623 (defun org-days-to-iso-week (days)
17624 "Return the iso week number."
17625 (require 'cal-iso)
17626 (car (calendar-iso-from-absolute days)))
17628 (defun org-small-year-to-year (year)
17629 "Convert 2-digit years into 4-digit years.
17630 YEAR is expanded into one of the 30 next years, if possible, or
17631 into a past one. Any year larger than 99 is returned unchanged."
17632 (if (>= year 100) year
17633 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17634 (century (/ current 100))
17635 (offset (- year (% current 100))))
17636 (cond ((> offset 30) (+ (* (1- century) 100) year))
17637 ((> offset -70) (+ (* century 100) year))
17638 (t (+ (* (1+ century) 100) year))))))
17640 (defun org-time-from-absolute (d)
17641 "Return the time corresponding to date D.
17642 D may be an absolute day number, or a calendar-type list (month day year)."
17643 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17644 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17646 (defvar org-agenda-current-date)
17647 (defun org-calendar-holiday ()
17648 "List of holidays, for Diary display in Org mode."
17649 (require 'holidays)
17650 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17651 (and hl (mapconcat #'identity hl "; "))))
17653 (defun org-diary-sexp-entry (sexp entry d)
17654 "Process a SEXP diary ENTRY for date D."
17655 (require 'diary-lib)
17656 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17657 ;; dynamically.
17658 (let* ((sexp `(let ((entry ,entry)
17659 (date ',d))
17660 ,(car (read-from-string sexp))))
17661 (result (if calendar-debug-sexp (eval sexp)
17662 (condition-case nil
17663 (eval sexp)
17664 (error
17665 (beep)
17666 (message "Bad sexp at line %d in %s: %s"
17667 (org-current-line)
17668 (buffer-file-name) sexp)
17669 (sleep-for 2))))))
17670 (cond ((stringp result) (split-string result "; "))
17671 ((and (consp result)
17672 (not (consp (cdr result)))
17673 (stringp (cdr result))) (cdr result))
17674 ((and (consp result)
17675 (stringp (car result))) result)
17676 (result entry))))
17678 (defun org-diary-to-ical-string (frombuf)
17679 "Get iCalendar entries from diary entries in buffer FROMBUF.
17680 This uses the icalendar.el library."
17681 (let* ((tmpdir temporary-file-directory)
17682 (tmpfile (make-temp-name
17683 (expand-file-name "orgics" tmpdir)))
17684 buf rtn b e)
17685 (with-current-buffer frombuf
17686 (icalendar-export-region (point-min) (point-max) tmpfile)
17687 (setq buf (find-buffer-visiting tmpfile))
17688 (set-buffer buf)
17689 (goto-char (point-min))
17690 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17691 (setq b (match-beginning 0)))
17692 (goto-char (point-max))
17693 (when (re-search-backward "^END:VEVENT" nil t)
17694 (setq e (match-end 0)))
17695 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17696 (kill-buffer buf)
17697 (delete-file tmpfile)
17698 rtn))
17700 (defun org-closest-date (start current prefer)
17701 "Return closest date to CURRENT starting from START.
17703 CURRENT and START are both time stamps.
17705 When PREFER is `past', return a date that is either CURRENT or
17706 past. When PREFER is `future', return a date that is either
17707 CURRENT or future.
17709 Only time stamps with a repeater are modified. Any other time
17710 stamp stay unchanged. In any case, return value is an absolute
17711 day number."
17712 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17713 ;; No repeater. Do not shift time stamp.
17714 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17715 (let ((value (string-to-number (match-string 1 start)))
17716 (type (match-string 2 start)))
17717 (if (= 0 value)
17718 ;; Repeater with a 0-value is considered as void.
17719 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17720 (let* ((base (org-date-to-gregorian start))
17721 (target (org-date-to-gregorian current))
17722 (sday (calendar-absolute-from-gregorian base))
17723 (cday (calendar-absolute-from-gregorian target))
17724 n1 n2)
17725 ;; If START is already past CURRENT, just return START.
17726 (if (<= cday sday) sday
17727 ;; Compute closest date before (N1) and closest date past
17728 ;; (N2) CURRENT.
17729 (pcase type
17730 ("h"
17731 (let ((missing-hours
17732 (mod (+ (- (* 24 (- cday sday))
17733 (nth 2 (org-parse-time-string start)))
17734 org-extend-today-until)
17735 value)))
17736 (setf n1 (if (= missing-hours 0) cday
17737 (- cday (1+ (/ missing-hours 24)))))
17738 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17739 ((or "d" "w")
17740 (let ((value (if (equal type "w") (* 7 value) value)))
17741 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17742 (setf n2 (+ n1 value))))
17743 ("m"
17744 (let* ((add-months
17745 (lambda (d n)
17746 ;; Add N months to gregorian date D, i.e.,
17747 ;; a list (MONTH DAY YEAR). Return a valid
17748 ;; gregorian date.
17749 (let ((m (+ (nth 0 d) n)))
17750 (list (mod m 12)
17751 (nth 1 d)
17752 (+ (/ m 12) (nth 2 d))))))
17753 (months ; Complete months to TARGET.
17754 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17755 (- (nth 0 target) (nth 0 base))
17756 ;; If START's day is greater than
17757 ;; TARGET's, remove incomplete month.
17758 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17759 value)
17760 value))
17761 (before (funcall add-months base months)))
17762 (setf n1 (calendar-absolute-from-gregorian before))
17763 (setf n2
17764 (calendar-absolute-from-gregorian
17765 (funcall add-months before value)))))
17767 (let* ((d (nth 1 base))
17768 (m (nth 0 base))
17769 (y (nth 2 base))
17770 (years ; Complete years to TARGET.
17771 (* (/ (- (nth 2 target)
17773 ;; If START's month and day are
17774 ;; greater than TARGET's, remove
17775 ;; incomplete year.
17776 (if (or (> (nth 0 target) m)
17777 (and (= (nth 0 target) m)
17778 (> (nth 1 target) d)))
17781 value)
17782 value))
17783 (before (list m d (+ y years))))
17784 (setf n1 (calendar-absolute-from-gregorian before))
17785 (setf n2 (calendar-absolute-from-gregorian
17786 (list m d (+ (nth 2 before) value)))))))
17787 ;; Handle PREFER parameter, if any.
17788 (cond
17789 ((eq prefer 'past) (if (= cday n2) n2 n1))
17790 ((eq prefer 'future) (if (= cday n1) n1 n2))
17791 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17793 (defun org-date-to-gregorian (d)
17794 "Turn any specification of date D into a Gregorian date for the calendar."
17795 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17796 ((and (listp d) (= (length d) 3)) d)
17797 ((stringp d)
17798 (let ((d (org-parse-time-string d)))
17799 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17800 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17802 (defun org-parse-time-string (s &optional nodefault)
17803 "Parse the standard Org time string.
17804 This should be a lot faster than the normal `parse-time-string'.
17805 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17806 hour and minute fields will be nil if not given."
17807 (cond ((string-match org-ts-regexp0 s)
17808 (list 0
17809 (when (or (match-beginning 8) (not nodefault))
17810 (string-to-number (or (match-string 8 s) "0")))
17811 (when (or (match-beginning 7) (not nodefault))
17812 (string-to-number (or (match-string 7 s) "0")))
17813 (string-to-number (match-string 4 s))
17814 (string-to-number (match-string 3 s))
17815 (string-to-number (match-string 2 s))
17816 nil nil nil))
17817 ((string-match "^<[^>]+>$" s)
17818 (decode-time (seconds-to-time (org-matcher-time s))))
17819 (t (error "Not a standard Org time string: %s" s))))
17821 (defun org-timestamp-up (&optional arg)
17822 "Increase the date item at the cursor by one.
17823 If the cursor is on the year, change the year. If it is on the month,
17824 the day or the time, change that.
17825 With prefix ARG, change by that many units."
17826 (interactive "p")
17827 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17829 (defun org-timestamp-down (&optional arg)
17830 "Decrease the date item at the cursor by one.
17831 If the cursor is on the year, change the year. If it is on the month,
17832 the day or the time, change that.
17833 With prefix ARG, change by that many units."
17834 (interactive "p")
17835 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17837 (defun org-timestamp-up-day (&optional arg)
17838 "Increase the date in the time stamp by one day.
17839 With prefix ARG, change that many days."
17840 (interactive "p")
17841 (if (and (not (org-at-timestamp-p 'lax))
17842 (org-at-heading-p))
17843 (org-todo 'up)
17844 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17846 (defun org-timestamp-down-day (&optional arg)
17847 "Decrease the date in the time stamp by one day.
17848 With prefix ARG, change that many days."
17849 (interactive "p")
17850 (if (and (not (org-at-timestamp-p 'lax))
17851 (org-at-heading-p))
17852 (org-todo 'down)
17853 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17855 (defun org-at-timestamp-p (&optional extended)
17856 "Non-nil if point is inside a timestamp.
17858 By default, the function only consider syntactically valid active
17859 timestamps. However, the caller may have a broader definition
17860 for timestamps. As a consequence, optional argument EXTENDED can
17861 be set to the following values
17863 `inactive'
17865 Include also syntactically valid inactive timestamps.
17867 `agenda'
17869 Include timestamps allowed in Agenda, i.e., those in
17870 properties drawers, planning lines and clock lines.
17872 `lax'
17874 Ignore context. The function matches any part of the
17875 document looking like a timestamp. This includes comments,
17876 example blocks...
17878 For backward-compatibility with Org 9.0, every other non-nil
17879 value is equivalent to `inactive'.
17881 When at a timestamp, return the position of the point as a symbol
17882 among `bracket', `after', `year', `month', `hour', `minute',
17883 `day' or a number of character from the last know part of the
17884 time stamp.
17886 When matching, the match groups are the following:
17887 group 1: year
17888 group 2: month
17889 group 3: day number
17890 group 4: day name
17891 group 5: hours, if any
17892 group 6: minutes, if any"
17893 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17894 (pos (point))
17895 (match?
17896 (let ((boundaries (org-in-regexp regexp)))
17897 (save-match-data
17898 (cond ((null boundaries) nil)
17899 ((eq extended 'lax) t)
17901 (or (and (eq extended 'agenda)
17902 (or (org-at-planning-p)
17903 (org-at-property-p)
17904 (and (bound-and-true-p
17905 org-agenda-include-inactive-timestamps)
17906 (org-at-clock-log-p))))
17907 (eq 'timestamp
17908 (save-excursion
17909 (when (= pos (cdr boundaries)) (forward-char -1))
17910 (org-element-type (org-element-context)))))))))))
17911 (cond
17912 ((not match?) nil)
17913 ((= pos (match-beginning 0)) 'bracket)
17914 ;; Distinguish location right before the closing bracket from
17915 ;; right after it.
17916 ((= pos (1- (match-end 0))) 'bracket)
17917 ((= pos (match-end 0)) 'after)
17918 ((org-pos-in-match-range pos 2) 'year)
17919 ((org-pos-in-match-range pos 3) 'month)
17920 ((org-pos-in-match-range pos 7) 'hour)
17921 ((org-pos-in-match-range pos 8) 'minute)
17922 ((or (org-pos-in-match-range pos 4)
17923 (org-pos-in-match-range pos 5)) 'day)
17924 ((and (> pos (or (match-end 8) (match-end 5)))
17925 (< pos (match-end 0)))
17926 (- pos (or (match-end 8) (match-end 5))))
17927 (t 'day))))
17929 (defun org-toggle-timestamp-type ()
17930 "Toggle the type (<active> or [inactive]) of a time stamp."
17931 (interactive)
17932 (when (org-at-timestamp-p 'lax)
17933 (let ((beg (match-beginning 0)) (end (match-end 0))
17934 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17935 (save-excursion
17936 (goto-char beg)
17937 (while (re-search-forward "[][<>]" end t)
17938 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17939 t t)))
17940 (message "Timestamp is now %sactive"
17941 (if (equal (char-after beg) ?<) "" "in")))))
17943 (defun org-at-clock-log-p ()
17944 "Non-nil if point is on a clock log line."
17945 (and (org-match-line org-clock-line-re)
17946 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17948 (defvar org-clock-history) ; defined in org-clock.el
17949 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17950 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17951 "Change the date in the time stamp at point.
17952 The date will be changed by N times WHAT. WHAT can be `day', `month',
17953 `year', `minute', `second'. If WHAT is not given, the cursor position
17954 in the timestamp determines what will be changed.
17955 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17956 (let ((origin (point))
17957 (timestamp? (org-at-timestamp-p 'lax))
17958 origin-cat
17959 with-hm inactive
17960 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17961 extra rem
17962 ts time time0 fixnext clrgx)
17963 (unless timestamp? (user-error "Not at a timestamp"))
17964 (if (and (not what) (eq timestamp? 'bracket))
17965 (org-toggle-timestamp-type)
17966 ;; Point isn't on brackets. Remember the part of the time-stamp
17967 ;; the point was in. Indeed, size of time-stamps may change,
17968 ;; but point must be kept in the same category nonetheless.
17969 (setq origin-cat timestamp?)
17970 (when (and (not what) (not (eq timestamp? 'day))
17971 org-display-custom-times
17972 (get-text-property (point) 'display)
17973 (not (get-text-property (1- (point)) 'display)))
17974 (setq timestamp? 'day))
17975 (setq timestamp? (or what timestamp?)
17976 inactive (= (char-after (match-beginning 0)) ?\[)
17977 ts (match-string 0))
17978 (replace-match "")
17979 (when (string-match
17980 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17982 (setq extra (match-string 1 ts))
17983 (when suppress-tmp-delay
17984 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17985 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17986 (setq with-hm t))
17987 (setq time0 (org-parse-time-string ts))
17988 (when (and updown
17989 (eq timestamp? 'minute)
17990 (not current-prefix-arg))
17991 ;; This looks like s-up and s-down. Change by one rounding step.
17992 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17993 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17994 (setcar (cdr time0) (+ (nth 1 time0)
17995 (if (> n 0) (- rem) (- dm rem))))))
17996 (setq time
17997 (apply #'encode-time
17998 (or (car time0) 0)
17999 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
18000 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
18001 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
18002 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
18003 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
18004 (nthcdr 6 time0)))
18005 (when (and (memq timestamp? '(hour minute))
18006 extra
18007 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18008 (setq extra (org-modify-ts-extra
18009 extra
18010 (if (eq timestamp? 'hour) 2 5)
18011 n dm)))
18012 (when (integerp timestamp?)
18013 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18014 (when (eq what 'calendar)
18015 (let ((cal-date (org-get-date-from-calendar)))
18016 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18017 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18018 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18019 (setcar time0 (or (car time0) 0))
18020 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18021 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18022 (setq time (apply 'encode-time time0))))
18023 ;; Insert the new time-stamp, and ensure point stays in the same
18024 ;; category as before (i.e. not after the last position in that
18025 ;; category).
18026 (let ((pos (point)))
18027 ;; Stay before inserted string. `save-excursion' is of no use.
18028 (setq org-last-changed-timestamp
18029 (org-insert-time-stamp time with-hm inactive nil nil extra))
18030 (goto-char pos))
18031 (save-match-data
18032 (looking-at org-ts-regexp3)
18033 (goto-char
18034 (pcase origin-cat
18035 ;; `day' category ends before `hour' if any, or at the end
18036 ;; of the day name.
18037 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18038 (`hour (min (match-end 7) origin))
18039 (`minute (min (1- (match-end 8)) origin))
18040 ((pred integerp) (min (1- (match-end 0)) origin))
18041 ;; Point was right after the time-stamp. However, the
18042 ;; time-stamp length might have changed, so refer to
18043 ;; (match-end 0) instead.
18044 (`after (match-end 0))
18045 ;; `year' and `month' have both fixed size: point couldn't
18046 ;; have moved into another part.
18047 (_ origin))))
18048 ;; Update clock if on a CLOCK line.
18049 (org-clock-update-time-maybe)
18050 ;; Maybe adjust the closest clock in `org-clock-history'
18051 (when org-clock-adjust-closest
18052 (if (not (and (org-at-clock-log-p)
18053 (< 1 (length (delq nil (mapcar 'marker-position
18054 org-clock-history))))))
18055 (message "No clock to adjust")
18056 (cond ((save-excursion ; fix previous clock?
18057 (re-search-backward org-ts-regexp0 nil t)
18058 (looking-back (concat org-clock-string " \\[")
18059 (line-beginning-position)))
18060 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18061 ((save-excursion ; fix next clock?
18062 (re-search-backward org-ts-regexp0 nil t)
18063 (looking-at (concat org-ts-regexp0 "\\] =>")))
18064 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18065 (save-window-excursion
18066 ;; Find closest clock to point, adjust the previous/next one in history
18067 (let* ((p (save-excursion (org-back-to-heading t)))
18068 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18069 (clfixnth
18070 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18071 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18072 (if (not clfixpos)
18073 (message "No clock to adjust")
18074 (save-excursion
18075 (org-goto-marker-or-bmk clfixpos)
18076 (org-show-subtree)
18077 (when (re-search-forward clrgx nil t)
18078 (goto-char (match-beginning 1))
18079 (let (org-clock-adjust-closest)
18080 (org-timestamp-change n timestamp? updown))
18081 (message "Clock adjusted in %s for heading: %s"
18082 (file-name-nondirectory (buffer-file-name))
18083 (org-get-heading t t)))))))))
18084 ;; Try to recenter the calendar window, if any.
18085 (when (and org-calendar-follow-timestamp-change
18086 (get-buffer-window "*Calendar*" t)
18087 (memq timestamp? '(day month year)))
18088 (org-recenter-calendar (time-to-days time))))))
18090 (defun org-modify-ts-extra (s pos n dm)
18091 "Change the different parts of the lead-time and repeat fields in timestamp."
18092 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18093 ng h m new rem)
18094 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18095 (cond
18096 ((or (org-pos-in-match-range pos 2)
18097 (org-pos-in-match-range pos 3))
18098 (setq m (string-to-number (match-string 3 s))
18099 h (string-to-number (match-string 2 s)))
18100 (if (org-pos-in-match-range pos 2)
18101 (setq h (+ h n))
18102 (setq n (* dm (with-no-warnings (signum n))))
18103 (unless (= 0 (setq rem (% m dm)))
18104 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18105 (setq m (+ m n)))
18106 (when (< m 0) (setq m (+ m 60) h (1- h)))
18107 (when (> m 59) (setq m (- m 60) h (1+ h)))
18108 (setq h (mod h 24))
18109 (setq ng 1 new (format "-%02d:%02d" h m)))
18110 ((org-pos-in-match-range pos 6)
18111 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18112 ((org-pos-in-match-range pos 5)
18113 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18115 ((org-pos-in-match-range pos 9)
18116 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18117 ((org-pos-in-match-range pos 8)
18118 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18120 (when ng
18121 (setq s (concat
18122 (substring s 0 (match-beginning ng))
18124 (substring s (match-end ng))))))
18127 (defun org-recenter-calendar (d)
18128 "If the calendar is visible, recenter it to date D."
18129 (let ((cwin (get-buffer-window "*Calendar*" t)))
18130 (when cwin
18131 (let ((calendar-move-hook nil))
18132 (with-selected-window cwin
18133 (calendar-goto-date
18134 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18136 (defun org-goto-calendar (&optional arg)
18137 "Go to the Emacs calendar at the current date.
18138 If there is a time stamp in the current line, go to that date.
18139 A prefix ARG can be used to force the current date."
18140 (interactive "P")
18141 (let ((calendar-move-hook nil)
18142 (calendar-view-holidays-initially-flag nil)
18143 (calendar-view-diary-initially-flag nil)
18144 diff)
18145 (when (or (org-at-timestamp-p 'lax)
18146 (org-match-line (concat ".*" org-ts-regexp)))
18147 (let ((d1 (time-to-days (current-time)))
18148 (d2 (time-to-days
18149 (org-time-string-to-time (match-string 1)))))
18150 (setq diff (- d2 d1))))
18151 (calendar)
18152 (calendar-goto-today)
18153 (when (and diff (not arg)) (calendar-forward-day diff))))
18155 (defun org-get-date-from-calendar ()
18156 "Return a list (month day year) of date at point in calendar."
18157 (with-current-buffer "*Calendar*"
18158 (save-match-data
18159 (calendar-cursor-to-date))))
18161 (defun org-date-from-calendar ()
18162 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18163 If there is already a time stamp at the cursor position, update it."
18164 (interactive)
18165 (if (org-at-timestamp-p 'lax)
18166 (org-timestamp-change 0 'calendar)
18167 (let ((cal-date (org-get-date-from-calendar)))
18168 (org-insert-time-stamp
18169 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18171 (defcustom org-effort-durations
18172 `(("min" . 1)
18173 ("h" . 60)
18174 ("d" . ,(* 60 8))
18175 ("w" . ,(* 60 8 5))
18176 ("m" . ,(* 60 8 5 4))
18177 ("y" . ,(* 60 8 5 40)))
18178 "Conversion factor to minutes for an effort modifier.
18180 Each entry has the form (MODIFIER . MINUTES).
18182 In an effort string, a number followed by MODIFIER is multiplied
18183 by the specified number of MINUTES to obtain an effort in
18184 minutes.
18186 For example, if the value of this variable is ((\"hours\" . 60)), then an
18187 effort string \"2hours\" is equivalent to 120 minutes."
18188 :group 'org-agenda
18189 :version "26.1"
18190 :package-version '(Org . "8.3")
18191 :type '(alist :key-type (string :tag "Modifier")
18192 :value-type (number :tag "Minutes")))
18194 (defcustom org-image-actual-width t
18195 "Should we use the actual width of images when inlining them?
18197 When set to t, always use the image width.
18199 When set to a number, use imagemagick (when available) to set
18200 the image's width to this value.
18202 When set to a number in a list, try to get the width from any
18203 #+ATTR.* keyword if it matches a width specification like
18205 #+ATTR_HTML: :width 300px
18207 and fall back on that number if none is found.
18209 When set to nil, try to get the width from an #+ATTR.* keyword
18210 and fall back on the original width if none is found.
18212 This requires Emacs >= 24.1, build with imagemagick support."
18213 :group 'org-appearance
18214 :version "24.4"
18215 :package-version '(Org . "8.0")
18216 :type '(choice
18217 (const :tag "Use the image width" t)
18218 (integer :tag "Use a number of pixels")
18219 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18220 (const :tag "Use #+ATTR* or don't resize" nil)))
18222 (defcustom org-agenda-inhibit-startup nil
18223 "Inhibit startup when preparing agenda buffers.
18224 When this variable is t, the initialization of the Org agenda
18225 buffers is inhibited: e.g. the visibility state is not set, the
18226 tables are not re-aligned, etc."
18227 :type 'boolean
18228 :version "24.3"
18229 :group 'org-agenda)
18231 (defcustom org-agenda-ignore-properties nil
18232 "Avoid updating text properties when building the agenda.
18233 Properties are used to prepare buffers for effort estimates,
18234 appointments, statistics and subtree-local categories.
18235 If you don't use these in the agenda, you can add them to this
18236 list and agenda building will be a bit faster.
18237 The value is a list, with zero or more of the symbols `effort', `appt',
18238 `stats' or `category'."
18239 :type '(set :greedy t
18240 (const effort)
18241 (const appt)
18242 (const stats)
18243 (const category))
18244 :version "26.1"
18245 :package-version '(Org . "8.3")
18246 :group 'org-agenda)
18248 ;;;; Files
18250 (defun org-save-all-org-buffers ()
18251 "Save all Org buffers without user confirmation."
18252 (interactive)
18253 (message "Saving all Org buffers...")
18254 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18255 (when (featurep 'org-id) (org-id-locations-save))
18256 (message "Saving all Org buffers... done"))
18258 (defun org-revert-all-org-buffers ()
18259 "Revert all Org buffers.
18260 Prompt for confirmation when there are unsaved changes.
18261 Be sure you know what you are doing before letting this function
18262 overwrite your changes.
18264 This function is useful in a setup where one tracks org files
18265 with a version control system, to revert on one machine after pulling
18266 changes from another. I believe the procedure must be like this:
18268 1. M-x org-save-all-org-buffers
18269 2. Pull changes from the other machine, resolve conflicts
18270 3. M-x org-revert-all-org-buffers"
18271 (interactive)
18272 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18273 (user-error "Abort"))
18274 (save-excursion
18275 (save-window-excursion
18276 (dolist (b (buffer-list))
18277 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18278 (with-current-buffer b buffer-file-name))
18279 (pop-to-buffer-same-window b)
18280 (revert-buffer t 'no-confirm)))
18281 (when (and (featurep 'org-id) org-id-track-globally)
18282 (org-id-locations-load)))))
18284 ;;;; Agenda files
18286 ;;;###autoload
18287 (defun org-switchb (&optional arg)
18288 "Switch between Org buffers.
18290 With `\\[universal-argument]' prefix, restrict available buffers to files.
18292 With `\\[universal-argument] \\[universal-argument]' \
18293 prefix, restrict available buffers to agenda files."
18294 (interactive "P")
18295 (let ((blist (org-buffer-list
18296 (cond ((equal arg '(4)) 'files)
18297 ((equal arg '(16)) 'agenda)))))
18298 (pop-to-buffer-same-window
18299 (completing-read "Org buffer: "
18300 (mapcar #'list (mapcar #'buffer-name blist))
18301 nil t))))
18303 (defun org-buffer-list (&optional predicate exclude-tmp)
18304 "Return a list of Org buffers.
18305 PREDICATE can be `export', `files' or `agenda'.
18307 export restrict the list to Export buffers.
18308 files restrict the list to buffers visiting Org files.
18309 agenda restrict the list to buffers visiting agenda files.
18311 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18312 (let* ((bfn nil)
18313 (agenda-files (and (eq predicate 'agenda)
18314 (mapcar 'file-truename (org-agenda-files t))))
18315 (filter
18316 (cond
18317 ((eq predicate 'files)
18318 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18319 ((eq predicate 'export)
18320 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18321 ((eq predicate 'agenda)
18322 (lambda (b)
18323 (with-current-buffer b
18324 (and (derived-mode-p 'org-mode)
18325 (setq bfn (buffer-file-name b))
18326 (member (file-truename bfn) agenda-files)))))
18327 (t (lambda (b) (with-current-buffer b
18328 (or (derived-mode-p 'org-mode)
18329 (string-match "\\*Org .*Export"
18330 (buffer-name b)))))))))
18331 (delq nil
18332 (mapcar
18333 (lambda(b)
18334 (if (and (funcall filter b)
18335 (or (not exclude-tmp)
18336 (not (string-match "tmp" (buffer-name b)))))
18338 nil))
18339 (buffer-list)))))
18341 (defun org-agenda-files (&optional unrestricted archives)
18342 "Get the list of agenda files.
18343 Optional UNRESTRICTED means return the full list even if a restriction
18344 is currently in place.
18345 When ARCHIVES is t, include all archive files that are really being
18346 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18347 `org-agenda-archives-mode' is t."
18348 (let ((files
18349 (cond
18350 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18351 ((stringp org-agenda-files) (org-read-agenda-file-list))
18352 ((listp org-agenda-files) org-agenda-files)
18353 (t (error "Invalid value of `org-agenda-files'")))))
18354 (setq files (apply 'append
18355 (mapcar (lambda (f)
18356 (if (file-directory-p f)
18357 (directory-files
18358 f t org-agenda-file-regexp)
18359 (list f)))
18360 files)))
18361 (when org-agenda-skip-unavailable-files
18362 (setq files (delq nil
18363 (mapcar (function
18364 (lambda (file)
18365 (and (file-readable-p file) file)))
18366 files))))
18367 (when (or (eq archives t)
18368 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18369 (setq files (org-add-archive-files files)))
18370 files))
18372 (defun org-agenda-file-p (&optional file)
18373 "Return non-nil, if FILE is an agenda file.
18374 If FILE is omitted, use the file associated with the current
18375 buffer."
18376 (let ((fname (or file (buffer-file-name))))
18377 (and fname
18378 (member (file-truename fname)
18379 (mapcar #'file-truename (org-agenda-files t))))))
18381 (defun org-edit-agenda-file-list ()
18382 "Edit the list of agenda files.
18383 Depending on setup, this either uses customize to edit the variable
18384 `org-agenda-files', or it visits the file that is holding the list. In the
18385 latter case, the buffer is set up in a way that saving it automatically kills
18386 the buffer and restores the previous window configuration."
18387 (interactive)
18388 (if (stringp org-agenda-files)
18389 (let ((cw (current-window-configuration)))
18390 (find-file org-agenda-files)
18391 (setq-local org-window-configuration cw)
18392 (add-hook 'after-save-hook
18393 (lambda ()
18394 (set-window-configuration
18395 (prog1 org-window-configuration
18396 (kill-buffer (current-buffer))))
18397 (org-install-agenda-files-menu)
18398 (message "New agenda file list installed"))
18399 nil 'local)
18400 (message "%s" (substitute-command-keys
18401 "Edit list and finish with \\[save-buffer]")))
18402 (customize-variable 'org-agenda-files)))
18404 (defun org-store-new-agenda-file-list (list)
18405 "Set new value for the agenda file list and save it correctly."
18406 (if (stringp org-agenda-files)
18407 (let ((fe (org-read-agenda-file-list t)) b u)
18408 (while (setq b (find-buffer-visiting org-agenda-files))
18409 (kill-buffer b))
18410 (with-temp-file org-agenda-files
18411 (insert
18412 (mapconcat
18413 (lambda (f) ;; Keep un-expanded entries.
18414 (if (setq u (assoc f fe))
18415 (cdr u)
18417 list "\n")
18418 "\n")))
18419 (let ((org-mode-hook nil) (org-inhibit-startup t)
18420 (org-insert-mode-line-in-empty-file nil))
18421 (setq org-agenda-files list)
18422 (customize-save-variable 'org-agenda-files org-agenda-files))))
18424 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18425 "Read the list of agenda files from a file.
18426 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18427 filenames, used by `org-store-new-agenda-file-list' to write back
18428 un-expanded file names."
18429 (when (file-directory-p org-agenda-files)
18430 (error "`org-agenda-files' cannot be a single directory"))
18431 (when (stringp org-agenda-files)
18432 (with-temp-buffer
18433 (insert-file-contents org-agenda-files)
18434 (mapcar
18435 (lambda (f)
18436 (let ((e (expand-file-name (substitute-in-file-name f)
18437 org-directory)))
18438 (if pair-with-expansion
18439 (cons e f)
18440 e)))
18441 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18443 ;;;###autoload
18444 (defun org-cycle-agenda-files ()
18445 "Cycle through the files in `org-agenda-files'.
18446 If the current buffer visits an agenda file, find the next one in the list.
18447 If the current buffer does not, find the first agenda file."
18448 (interactive)
18449 (let* ((fs (or (org-agenda-files t)
18450 (user-error "No agenda files")))
18451 (files (copy-sequence fs))
18452 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18453 file)
18454 (when tcf
18455 (while (and (setq file (pop files))
18456 (not (equal (file-truename file) tcf)))))
18457 (find-file (car (or files fs)))
18458 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18460 (defun org-agenda-file-to-front (&optional to-end)
18461 "Move/add the current file to the top of the agenda file list.
18462 If the file is not present in the list, it is added to the front. If it is
18463 present, it is moved there. With optional argument TO-END, add/move to the
18464 end of the list."
18465 (interactive "P")
18466 (let ((org-agenda-skip-unavailable-files nil)
18467 (file-alist (mapcar (lambda (x)
18468 (cons (file-truename x) x))
18469 (org-agenda-files t)))
18470 (ctf (file-truename
18471 (or buffer-file-name
18472 (user-error "Please save the current buffer to a file"))))
18473 x had)
18474 (setq x (assoc ctf file-alist) had x)
18476 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18477 (if to-end
18478 (setq file-alist (append (delq x file-alist) (list x)))
18479 (setq file-alist (cons x (delq x file-alist))))
18480 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18481 (org-install-agenda-files-menu)
18482 (message "File %s to %s of agenda file list"
18483 (if had "moved" "added") (if to-end "end" "front"))))
18485 (defun org-remove-file (&optional file)
18486 "Remove current file from the list of files in variable `org-agenda-files'.
18487 These are the files which are being checked for agenda entries.
18488 Optional argument FILE means use this file instead of the current."
18489 (interactive)
18490 (let* ((org-agenda-skip-unavailable-files nil)
18491 (file (or file buffer-file-name
18492 (user-error "Current buffer does not visit a file")))
18493 (true-file (file-truename file))
18494 (afile (abbreviate-file-name file))
18495 (files (delq nil (mapcar
18496 (lambda (x)
18497 (unless (equal true-file
18498 (file-truename x))
18500 (org-agenda-files t)))))
18501 (if (not (= (length files) (length (org-agenda-files t))))
18502 (progn
18503 (org-store-new-agenda-file-list files)
18504 (org-install-agenda-files-menu)
18505 (message "Removed from Org Agenda list: %s" afile))
18506 (message "File was not in list: %s (not removed)" afile))))
18508 (defun org-file-menu-entry (file)
18509 (vector file (list 'find-file file) t))
18511 (defun org-check-agenda-file (file)
18512 "Make sure FILE exists. If not, ask user what to do."
18513 (unless (file-exists-p file)
18514 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18515 (abbreviate-file-name file))
18516 (let ((r (downcase (read-char-exclusive))))
18517 (cond
18518 ((equal r ?r)
18519 (org-remove-file file)
18520 (throw 'nextfile t))
18521 (t (user-error "Abort"))))))
18523 (defun org-get-agenda-file-buffer (file)
18524 "Get an agenda buffer visiting FILE.
18525 If the buffer needs to be created, add it to the list of buffers
18526 which might be released later."
18527 (let ((buf (org-find-base-buffer-visiting file)))
18528 (if buf
18529 buf ; just return it
18530 ;; Make a new buffer and remember it
18531 (setq buf (find-file-noselect file))
18532 (when buf (push buf org-agenda-new-buffers))
18533 buf)))
18535 (defun org-release-buffers (blist)
18536 "Release all buffers in list, asking the user for confirmation when needed.
18537 When a buffer is unmodified, it is just killed. When modified, it is saved
18538 \(if the user agrees) and then killed."
18539 (let (file)
18540 (dolist (buf blist)
18541 (setq file (buffer-file-name buf))
18542 (when (and (buffer-modified-p buf)
18543 file
18544 (y-or-n-p (format "Save file %s? " file)))
18545 (with-current-buffer buf (save-buffer)))
18546 (kill-buffer buf))))
18548 (defun org-agenda-prepare-buffers (files)
18549 "Create buffers for all agenda files, protect archived trees and comments."
18550 (interactive)
18551 (let ((pa '(:org-archived t))
18552 (pc '(:org-comment t))
18553 (pall '(:org-archived t :org-comment t))
18554 (inhibit-read-only t)
18555 (org-inhibit-startup org-agenda-inhibit-startup)
18556 (rea (concat ":" org-archive-tag ":"))
18557 re pos)
18558 (setq org-tag-alist-for-agenda nil
18559 org-tag-groups-alist-for-agenda nil)
18560 (save-excursion
18561 (save-restriction
18562 (dolist (file files)
18563 (catch 'nextfile
18564 (if (bufferp file)
18565 (set-buffer file)
18566 (org-check-agenda-file file)
18567 (set-buffer (org-get-agenda-file-buffer file)))
18568 (widen)
18569 (org-set-regexps-and-options 'tags-only)
18570 (setq pos (point))
18571 (or (memq 'category org-agenda-ignore-properties)
18572 (org-refresh-category-properties))
18573 (or (memq 'stats org-agenda-ignore-properties)
18574 (org-refresh-stats-properties))
18575 (or (memq 'effort org-agenda-ignore-properties)
18576 (org-refresh-effort-properties))
18577 (or (memq 'appt org-agenda-ignore-properties)
18578 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18579 (setq org-todo-keywords-for-agenda
18580 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18581 (setq org-done-keywords-for-agenda
18582 (append org-done-keywords-for-agenda org-done-keywords))
18583 (setq org-todo-keyword-alist-for-agenda
18584 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18585 (setq org-tag-alist-for-agenda
18586 (org-uniquify
18587 (append org-tag-alist-for-agenda
18588 org-current-tag-alist)))
18589 ;; Merge current file's tag groups into global
18590 ;; `org-tag-groups-alist-for-agenda'.
18591 (when org-group-tags
18592 (dolist (alist org-tag-groups-alist)
18593 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18594 (if old
18595 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18596 (push alist org-tag-groups-alist-for-agenda)))))
18597 (org-with-silent-modifications
18598 (save-excursion
18599 (remove-text-properties (point-min) (point-max) pall)
18600 (when org-agenda-skip-archived-trees
18601 (goto-char (point-min))
18602 (while (re-search-forward rea nil t)
18603 (when (org-at-heading-p t)
18604 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18605 (goto-char (point-min))
18606 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18607 (while (re-search-forward re nil t)
18608 (when (save-match-data (org-in-commented-heading-p t))
18609 (add-text-properties
18610 (match-beginning 0) (org-end-of-subtree t) pc)))))
18611 (goto-char pos)))))
18612 (setq org-todo-keywords-for-agenda
18613 (org-uniquify org-todo-keywords-for-agenda))
18614 (setq org-todo-keyword-alist-for-agenda
18615 (org-uniquify org-todo-keyword-alist-for-agenda))))
18618 ;;;; CDLaTeX minor mode
18620 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18621 "Keymap for the minor `org-cdlatex-mode'.")
18623 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18624 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18625 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18626 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18627 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18629 (defvar org-cdlatex-texmathp-advice-is-done nil
18630 "Flag remembering if we have applied the advice to texmathp already.")
18632 (define-minor-mode org-cdlatex-mode
18633 "Toggle the minor `org-cdlatex-mode'.
18634 This mode supports entering LaTeX environment and math in LaTeX fragments
18635 in Org mode.
18636 \\{org-cdlatex-mode-map}"
18637 nil " OCDL" nil
18638 (when org-cdlatex-mode
18639 (require 'cdlatex)
18640 (run-hooks 'cdlatex-mode-hook)
18641 (cdlatex-compute-tables))
18642 (unless org-cdlatex-texmathp-advice-is-done
18643 (setq org-cdlatex-texmathp-advice-is-done t)
18644 (defadvice texmathp (around org-math-always-on activate)
18645 "Always return t in Org buffers.
18646 This is because we want to insert math symbols without dollars even outside
18647 the LaTeX math segments. If Org mode thinks that point is actually inside
18648 an embedded LaTeX fragment, let `texmathp' do its job.
18649 `\\[org-cdlatex-mode-map]'"
18650 (interactive)
18651 (let (p)
18652 (cond
18653 ((not (derived-mode-p 'org-mode)) ad-do-it)
18654 ((eq this-command 'cdlatex-math-symbol)
18655 (setq ad-return-value t
18656 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18658 (let ((p (org-inside-LaTeX-fragment-p)))
18659 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18660 (setq ad-return-value t
18661 texmathp-why '("Org mode embedded math" . 0))
18662 (when p ad-do-it)))))))))
18664 (defun turn-on-org-cdlatex ()
18665 "Unconditionally turn on `org-cdlatex-mode'."
18666 (org-cdlatex-mode 1))
18668 (defun org-try-cdlatex-tab ()
18669 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18670 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18671 - inside a LaTeX fragment, or
18672 - after the first word in a line, where an abbreviation expansion could
18673 insert a LaTeX environment."
18674 (when org-cdlatex-mode
18675 (cond
18676 ;; Before any word on the line: No expansion possible.
18677 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18678 ;; Just after first word on the line: Expand it. Make sure it
18679 ;; cannot happen on headlines, though.
18680 ((save-excursion
18681 (skip-chars-backward "a-zA-Z0-9*")
18682 (skip-chars-backward " \t")
18683 (and (bolp) (not (org-at-heading-p))))
18684 (cdlatex-tab) t)
18685 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18687 (defun org-cdlatex-underscore-caret (&optional _arg)
18688 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18689 Revert to the normal definition outside of these fragments."
18690 (interactive "P")
18691 (if (org-inside-LaTeX-fragment-p)
18692 (call-interactively 'cdlatex-sub-superscript)
18693 (let (org-cdlatex-mode)
18694 (call-interactively (key-binding (vector last-input-event))))))
18696 (defun org-cdlatex-math-modify (&optional _arg)
18697 "Execute `cdlatex-math-modify' in LaTeX fragments.
18698 Revert to the normal definition outside of these fragments."
18699 (interactive "P")
18700 (if (org-inside-LaTeX-fragment-p)
18701 (call-interactively 'cdlatex-math-modify)
18702 (let (org-cdlatex-mode)
18703 (call-interactively (key-binding (vector last-input-event))))))
18705 (defun org-cdlatex-environment-indent (&optional environment item)
18706 "Execute `cdlatex-environment' and indent the inserted environment.
18708 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18710 The inserted environment is indented to current indentation
18711 unless point is at the beginning of the line, in which the
18712 environment remains unintended."
18713 (interactive)
18714 ;; cdlatex-environment always return nil. Therefore, capture output
18715 ;; first and determine if an environment was selected.
18716 (let* ((beg (point-marker))
18717 (end (copy-marker (point) t))
18718 (inserted (progn
18719 (ignore-errors (cdlatex-environment environment item))
18720 (< beg end)))
18721 ;; Figure out how many lines to move forward after the
18722 ;; environment has been inserted.
18723 (lines (when inserted
18724 (save-excursion
18725 (- (cl-loop while (< beg (point))
18726 with x = 0
18727 do (forward-line -1)
18728 (cl-incf x)
18729 finally return x)
18730 (if (progn (goto-char beg)
18731 (and (progn (skip-chars-forward " \t") (eolp))
18732 (progn (skip-chars-backward " \t") (bolp))))
18733 1 0)))))
18734 (env (org-trim (delete-and-extract-region beg end))))
18735 (when inserted
18736 ;; Get indentation of next line unless at column 0.
18737 (let ((ind (if (bolp) 0
18738 (save-excursion
18739 (org-return-indent)
18740 (prog1 (org-get-indentation)
18741 (when (progn (skip-chars-forward " \t") (eolp))
18742 (delete-region beg (point)))))))
18743 (bol (progn (skip-chars-backward " \t") (bolp))))
18744 ;; Insert a newline before environment unless at column zero
18745 ;; to "escape" the current line. Insert a newline if
18746 ;; something is one the same line as \end{ENVIRONMENT}.
18747 (insert
18748 (concat (unless bol "\n") env
18749 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18750 (unless (zerop ind)
18751 (save-excursion
18752 (goto-char beg)
18753 (while (< (point) end)
18754 (unless (eolp) (indent-line-to ind))
18755 (forward-line))))
18756 (goto-char beg)
18757 (forward-line lines)
18758 (indent-line-to ind)))
18759 (set-marker beg nil)
18760 (set-marker end nil)))
18763 ;;;; LaTeX fragments
18765 (defun org-inside-LaTeX-fragment-p ()
18766 "Test if point is inside a LaTeX fragment.
18767 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18768 sequence appearing also before point.
18769 Even though the matchers for math are configurable, this function assumes
18770 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18771 delimiters are skipped when they have been removed by customization.
18772 The return value is nil, or a cons cell with the delimiter and the
18773 position of this delimiter.
18775 This function does a reasonably good job, but can locally be fooled by
18776 for example currency specifications. For example it will assume being in
18777 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18778 fragments that are properly closed, but during editing, we have to live
18779 with the uncertainty caused by missing closing delimiters. This function
18780 looks only before point, not after."
18781 (catch 'exit
18782 (let ((pos (point))
18783 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18784 (lim (progn
18785 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18786 (point)))
18787 dd-on str (start 0) m re)
18788 (goto-char pos)
18789 (when dodollar
18790 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18791 re (nth 1 (assoc "$" org-latex-regexps)))
18792 (while (string-match re str start)
18793 (cond
18794 ((= (match-end 0) (length str))
18795 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18796 ((= (match-end 0) (- (length str) 5))
18797 (throw 'exit nil))
18798 (t (setq start (match-end 0))))))
18799 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18800 (goto-char pos)
18801 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18802 (and (match-beginning 2) (throw 'exit nil))
18803 ;; count $$
18804 (while (re-search-backward "\\$\\$" lim t)
18805 (setq dd-on (not dd-on)))
18806 (goto-char pos)
18807 (when dd-on (cons "$$" m))))))
18809 (defun org-inside-latex-macro-p ()
18810 "Is point inside a LaTeX macro or its arguments?"
18811 (save-match-data
18812 (org-in-regexp
18813 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18815 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18816 "Build an overlay between BEG and END using IMAGE file.
18817 Argument IMAGETYPE is the extension of the displayed image,
18818 as a string. It defaults to \"png\"."
18819 (let ((ov (make-overlay beg end))
18820 (imagetype (or (intern imagetype) 'png)))
18821 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18822 (overlay-put ov 'evaporate t)
18823 (overlay-put ov
18824 'modification-hooks
18825 (list (lambda (o _flag _beg _end &optional _l)
18826 (delete-overlay o))))
18827 (overlay-put ov
18828 'display
18829 (list 'image :type imagetype :file image :ascent 'center))))
18831 (defun org--list-latex-overlays (&optional beg end)
18832 "List all Org LaTeX overlays in current buffer.
18833 Limit to overlays between BEG and END when those are provided."
18834 (cl-remove-if-not
18835 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18836 (overlays-in (or beg (point-min)) (or end (point-max)))))
18838 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18839 "Remove all overlays with LaTeX fragment images in current buffer.
18840 When optional arguments BEG and END are non-nil, remove all
18841 overlays between them instead. Return a non-nil value when some
18842 overlays were removed, nil otherwise."
18843 (let ((overlays (org--list-latex-overlays beg end)))
18844 (mapc #'delete-overlay overlays)
18845 overlays))
18847 (defun org-toggle-latex-fragment (&optional arg)
18848 "Preview the LaTeX fragment at point, or all locally or globally.
18850 If the cursor is on a LaTeX fragment, create the image and overlay
18851 it over the source code, if there is none. Remove it otherwise.
18852 If there is no fragment at point, display all fragments in the
18853 current section.
18855 With prefix ARG, preview or clear image for all fragments in the
18856 current subtree or in the whole buffer when used before the first
18857 headline. With a prefix ARG `\\[universal-argument] \
18858 \\[universal-argument]' preview or clear images
18859 for all fragments in the buffer."
18860 (interactive "P")
18861 (when (display-graphic-p)
18862 (catch 'exit
18863 (save-excursion
18864 (let (beg end msg)
18865 (cond
18866 ((or (equal arg '(16))
18867 (and (equal arg '(4))
18868 (org-with-limited-levels (org-before-first-heading-p))))
18869 (if (org-remove-latex-fragment-image-overlays)
18870 (progn (message "LaTeX fragments images removed from buffer")
18871 (throw 'exit nil))
18872 (setq msg "Creating images for buffer...")))
18873 ((equal arg '(4))
18874 (org-with-limited-levels (org-back-to-heading t))
18875 (setq beg (point))
18876 (setq end (progn (org-end-of-subtree t) (point)))
18877 (if (org-remove-latex-fragment-image-overlays beg end)
18878 (progn
18879 (message "LaTeX fragment images removed from subtree")
18880 (throw 'exit nil))
18881 (setq msg "Creating images for subtree...")))
18882 ((let ((datum (org-element-context)))
18883 (when (memq (org-element-type datum)
18884 '(latex-environment latex-fragment))
18885 (setq beg (org-element-property :begin datum))
18886 (setq end (org-element-property :end datum))
18887 (if (org-remove-latex-fragment-image-overlays beg end)
18888 (progn (message "LaTeX fragment image removed")
18889 (throw 'exit nil))
18890 (setq msg "Creating image...")))))
18892 (org-with-limited-levels
18893 (setq beg (if (org-at-heading-p) (line-beginning-position)
18894 (outline-previous-heading)
18895 (point)))
18896 (setq end (progn (outline-next-heading) (point)))
18897 (if (org-remove-latex-fragment-image-overlays beg end)
18898 (progn
18899 (message "LaTeX fragment images removed from section")
18900 (throw 'exit nil))
18901 (setq msg "Creating images for section...")))))
18902 (let ((file (buffer-file-name (buffer-base-buffer))))
18903 (org-format-latex
18904 (concat org-preview-latex-image-directory "org-ltximg")
18905 beg end
18906 ;; Emacs cannot overlay images from remote hosts. Create
18907 ;; it in `temporary-file-directory' instead.
18908 (if (or (not file) (file-remote-p file))
18909 temporary-file-directory
18910 default-directory)
18911 'overlays msg 'forbuffer org-preview-latex-default-process))
18912 (message (concat msg "done")))))))
18914 (defun org-format-latex
18915 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18916 "Replace LaTeX fragments with links to an image.
18918 The function takes care of creating the replacement image.
18920 Only consider fragments between BEG and END when those are
18921 provided.
18923 When optional argument OVERLAYS is non-nil, display the image on
18924 top of the fragment instead of replacing it.
18926 PROCESSING-TYPE is the conversion method to use, as a symbol.
18928 Some of the options can be changed using the variable
18929 `org-format-latex-options', which see."
18930 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18931 (unless (eq processing-type 'verbatim)
18932 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18933 (cnt 0)
18934 checkdir-flag)
18935 (goto-char (or beg (point-min)))
18936 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18937 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18938 (overlay-recenter (or end (point-max))))
18939 (while (re-search-forward math-regexp end t)
18940 (unless (and overlays
18941 (eq (get-char-property (point) 'org-overlay-type)
18942 'org-latex-overlay))
18943 (let* ((context (org-element-context))
18944 (type (org-element-type context)))
18945 (when (memq type '(latex-environment latex-fragment))
18946 (let ((block-type (eq type 'latex-environment))
18947 (value (org-element-property :value context))
18948 (beg (org-element-property :begin context))
18949 (end (save-excursion
18950 (goto-char (org-element-property :end context))
18951 (skip-chars-backward " \r\t\n")
18952 (point))))
18953 (cond
18954 ((eq processing-type 'mathjax)
18955 ;; Prepare for MathJax processing.
18956 (if (not (string-match "\\`\\$\\$?" value))
18957 (goto-char end)
18958 (delete-region beg end)
18959 (if (string= (match-string 0 value) "$$")
18960 (insert "\\[" (substring value 2 -2) "\\]")
18961 (insert "\\(" (substring value 1 -1) "\\)"))))
18962 ((assq processing-type org-preview-latex-process-alist)
18963 ;; Process to an image.
18964 (cl-incf cnt)
18965 (goto-char beg)
18966 (let* ((processing-info
18967 (cdr (assq processing-type org-preview-latex-process-alist)))
18968 (face (face-at-point))
18969 ;; Get the colors from the face at point.
18971 (let ((color (plist-get org-format-latex-options
18972 :foreground)))
18973 (if (and forbuffer (eq color 'auto))
18974 (face-attribute face :foreground nil 'default)
18975 color)))
18977 (let ((color (plist-get org-format-latex-options
18978 :background)))
18979 (if (and forbuffer (eq color 'auto))
18980 (face-attribute face :background nil 'default)
18981 color)))
18982 (hash (sha1 (prin1-to-string
18983 (list org-format-latex-header
18984 org-latex-default-packages-alist
18985 org-latex-packages-alist
18986 org-format-latex-options
18987 forbuffer value fg bg))))
18988 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18989 (absprefix (expand-file-name prefix dir))
18990 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18991 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18992 (sep (and block-type "\n\n"))
18993 (link (concat sep "[[file:" linkfile "]]" sep))
18994 (options
18995 (org-combine-plists
18996 org-format-latex-options
18997 `(:foreground ,fg :background ,bg))))
18998 (when msg (message msg cnt))
18999 (unless checkdir-flag ; Ensure the directory exists.
19000 (setq checkdir-flag t)
19001 (let ((todir (file-name-directory absprefix)))
19002 (unless (file-directory-p todir)
19003 (make-directory todir t))))
19004 (unless (file-exists-p movefile)
19005 (org-create-formula-image
19006 value movefile options forbuffer processing-type))
19007 (if overlays
19008 (progn
19009 (dolist (o (overlays-in beg end))
19010 (when (eq (overlay-get o 'org-overlay-type)
19011 'org-latex-overlay)
19012 (delete-overlay o)))
19013 (org--format-latex-make-overlay beg end movefile imagetype)
19014 (goto-char end))
19015 (delete-region beg end)
19016 (insert
19017 (org-add-props link
19018 (list 'org-latex-src
19019 (replace-regexp-in-string "\"" "" value)
19020 'org-latex-src-embed-type
19021 (if block-type 'paragraph 'character)))))))
19022 ((eq processing-type 'mathml)
19023 ;; Process to MathML.
19024 (unless (org-format-latex-mathml-available-p)
19025 (user-error "LaTeX to MathML converter not configured"))
19026 (cl-incf cnt)
19027 (when msg (message msg cnt))
19028 (goto-char beg)
19029 (delete-region beg end)
19030 (insert (org-format-latex-as-mathml
19031 value block-type prefix dir)))
19033 (error "Unknown conversion process %s for LaTeX fragments"
19034 processing-type)))))))))))
19036 (defun org-create-math-formula (latex-frag &optional mathml-file)
19037 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19038 Use `org-latex-to-mathml-convert-command'. If the conversion is
19039 sucessful, return the portion between \"<math...> </math>\"
19040 elements otherwise return nil. When MATHML-FILE is specified,
19041 write the results in to that file. When invoked as an
19042 interactive command, prompt for LATEX-FRAG, with initial value
19043 set to the current active region and echo the results for user
19044 inspection."
19045 (interactive (list (let ((frag (when (org-region-active-p)
19046 (buffer-substring-no-properties
19047 (region-beginning) (region-end)))))
19048 (read-string "LaTeX Fragment: " frag nil frag))))
19049 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19050 (let* ((tmp-in-file
19051 (let ((file (file-relative-name
19052 (make-temp-name (expand-file-name "ltxmathml-in")))))
19053 (write-region latex-frag nil file)
19054 file))
19055 (tmp-out-file (file-relative-name
19056 (make-temp-name (expand-file-name "ltxmathml-out"))))
19057 (cmd (format-spec
19058 org-latex-to-mathml-convert-command
19059 `((?j . ,(and org-latex-to-mathml-jar-file
19060 (shell-quote-argument
19061 (expand-file-name
19062 org-latex-to-mathml-jar-file))))
19063 (?I . ,(shell-quote-argument tmp-in-file))
19064 (?i . ,latex-frag)
19065 (?o . ,(shell-quote-argument tmp-out-file)))))
19066 mathml shell-command-output)
19067 (when (called-interactively-p 'any)
19068 (unless (org-format-latex-mathml-available-p)
19069 (user-error "LaTeX to MathML converter not configured")))
19070 (message "Running %s" cmd)
19071 (setq shell-command-output (shell-command-to-string cmd))
19072 (setq mathml
19073 (when (file-readable-p tmp-out-file)
19074 (with-current-buffer (find-file-noselect tmp-out-file t)
19075 (goto-char (point-min))
19076 (when (re-search-forward
19077 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19078 (regexp-quote
19079 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19080 nil t)
19081 (prog1 (match-string 0) (kill-buffer))))))
19082 (cond
19083 (mathml
19084 (setq mathml
19085 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19086 (when mathml-file
19087 (write-region mathml nil mathml-file))
19088 (when (called-interactively-p 'any)
19089 (message mathml)))
19090 ((message "LaTeX to MathML conversion failed")
19091 (message shell-command-output)))
19092 (delete-file tmp-in-file)
19093 (when (file-exists-p tmp-out-file)
19094 (delete-file tmp-out-file))
19095 mathml))
19097 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19098 prefix &optional dir)
19099 "Use `org-create-math-formula' but check local cache first."
19100 (let* ((absprefix (expand-file-name prefix dir))
19101 (print-length nil) (print-level nil)
19102 (formula-id (concat
19103 "formula-"
19104 (sha1
19105 (prin1-to-string
19106 (list latex-frag
19107 org-latex-to-mathml-convert-command)))))
19108 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19109 (formula-cache-dir (file-name-directory formula-cache)))
19111 (unless (file-directory-p formula-cache-dir)
19112 (make-directory formula-cache-dir t))
19114 (unless (file-exists-p formula-cache)
19115 (org-create-math-formula latex-frag formula-cache))
19117 (if (file-exists-p formula-cache)
19118 ;; Successful conversion. Return the link to MathML file.
19119 (org-add-props
19120 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19121 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19122 'org-latex-src-embed-type (if latex-frag-type
19123 'paragraph 'character)))
19124 ;; Failed conversion. Return the LaTeX fragment verbatim
19125 latex-frag)))
19127 (defun org--get-display-dpi ()
19128 "Get the DPI of the display.
19129 The function assumes that the display has the same pixel width in
19130 the horizontal and vertical directions."
19131 (if (display-graphic-p)
19132 (round (/ (display-pixel-height)
19133 (/ (display-mm-height) 25.4)))
19134 (error "Attempt to calculate the dpi of a non-graphic display")))
19136 (defun org-create-formula-image
19137 (string tofile options buffer &optional processing-type)
19138 "Create an image from LaTeX source using external processes.
19140 The LaTeX STRING is saved to a temporary LaTeX file, then
19141 converted to an image file by process PROCESSING-TYPE defined in
19142 `org-preview-latex-process-alist'. A nil value defaults to
19143 `org-preview-latex-default-process'.
19145 The generated image file is eventually moved to TOFILE.
19147 The OPTIONS argument controls the size, foreground color and
19148 background color of the generated image.
19150 When BUFFER non-nil, this function is used for LaTeX previewing.
19151 Otherwise, it is used to deal with LaTeX snippets showed in
19152 a HTML file."
19153 (let* ((processing-type (or processing-type
19154 org-preview-latex-default-process))
19155 (processing-info
19156 (cdr (assq processing-type org-preview-latex-process-alist)))
19157 (programs (plist-get processing-info :programs))
19158 (error-message (or (plist-get processing-info :message) ""))
19159 (use-xcolor (plist-get processing-info :use-xcolor))
19160 (image-input-type (plist-get processing-info :image-input-type))
19161 (image-output-type (plist-get processing-info :image-output-type))
19162 (post-clean (or (plist-get processing-info :post-clean)
19163 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19164 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19165 (latex-header
19166 (or (plist-get processing-info :latex-header)
19167 (org-latex-make-preamble
19168 (org-export-get-environment (org-export-get-backend 'latex))
19169 org-format-latex-header
19170 'snippet)))
19171 (latex-compiler (plist-get processing-info :latex-compiler))
19172 (image-converter (plist-get processing-info :image-converter))
19173 (tmpdir temporary-file-directory)
19174 (texfilebase (make-temp-name
19175 (expand-file-name "orgtex" tmpdir)))
19176 (texfile (concat texfilebase ".tex"))
19177 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19178 '(1.0 . 1.0)))
19179 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19180 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19181 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19182 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19183 "Black"))
19184 (bg (or (plist-get options (if buffer :background :html-background))
19185 "Transparent"))
19186 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19187 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19188 (dolist (program programs)
19189 (org-check-external-command program error-message))
19190 (if use-xcolor
19191 (progn (if (eq fg 'default)
19192 (setq fg (org-latex-color :foreground))
19193 (setq fg (org-latex-color-format fg)))
19194 (if (eq bg 'default)
19195 (setq bg (org-latex-color :background))
19196 (setq bg (org-latex-color-format
19197 (if (string= bg "Transparent") "white" bg))))
19198 (with-temp-file texfile
19199 (insert latex-header)
19200 (insert "\n\\begin{document}\n"
19201 "\\definecolor{fg}{rgb}{" fg "}\n"
19202 "\\definecolor{bg}{rgb}{" bg "}\n"
19203 "\n\\pagecolor{bg}\n"
19204 "\n{\\color{fg}\n"
19205 string
19206 "\n}\n"
19207 "\n\\end{document}\n")))
19208 (if (eq fg 'default)
19209 (setq fg (org-dvipng-color :foreground))
19210 (unless (string= fg "Transparent")
19211 (setq fg (org-dvipng-color-format fg))))
19212 (if (eq bg 'default)
19213 (setq bg (org-dvipng-color :background))
19214 (unless (string= bg "Transparent")
19215 (setq bg (org-dvipng-color-format bg))))
19216 (with-temp-file texfile
19217 (insert latex-header)
19218 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19220 (let* ((err-msg (format "Please adjust '%s' part of \
19221 `org-preview-latex-process-alist'."
19222 processing-type))
19223 (image-input-file
19224 (org-compile-file
19225 texfile latex-compiler image-input-type err-msg log-buf))
19226 (image-output-file
19227 (org-compile-file
19228 image-input-file image-converter image-output-type err-msg log-buf
19229 `((?F . ,(shell-quote-argument fg))
19230 (?B . ,(shell-quote-argument bg))
19231 (?D . ,(shell-quote-argument (format "%s" dpi)))
19232 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19233 (copy-file image-output-file tofile 'replace)
19234 (dolist (e post-clean)
19235 (when (file-exists-p (concat texfilebase e))
19236 (delete-file (concat texfilebase e))))
19237 image-output-file)))
19239 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19240 "Fill a LaTeX header template TPL.
19241 In the template, the following place holders will be recognized:
19243 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19244 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19245 [PACKAGES] \\usepackage statements for PKG
19246 [NO-PACKAGES] do not include PKG
19247 [EXTRA] the string EXTRA
19248 [NO-EXTRA] do not include EXTRA
19250 For backward compatibility, if both the positive and the negative place
19251 holder is missing, the positive one (without the \"NO-\") will be
19252 assumed to be present at the end of the template.
19253 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19254 EXTRA is a string.
19255 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19256 (let (rpl (end ""))
19257 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19258 (setq rpl (if (or (match-end 1) (not def-pkg))
19259 "" (org-latex-packages-to-string def-pkg snippets-p t))
19260 tpl (replace-match rpl t t tpl))
19261 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19263 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19264 (setq rpl (if (or (match-end 1) (not pkg))
19265 "" (org-latex-packages-to-string pkg snippets-p t))
19266 tpl (replace-match rpl t t tpl))
19267 (when pkg (setq end
19268 (concat end "\n"
19269 (org-latex-packages-to-string pkg snippets-p)))))
19271 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19272 (setq rpl (if (or (match-end 1) (not extra))
19273 "" (concat extra "\n"))
19274 tpl (replace-match rpl t t tpl))
19275 (when (and extra (string-match "\\S-" extra))
19276 (setq end (concat end "\n" extra))))
19278 (if (string-match "\\S-" end)
19279 (concat tpl "\n" end)
19280 tpl)))
19282 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19283 "Turn an alist of packages into a string with the \\usepackage macros."
19284 (setq pkg (mapconcat (lambda(p)
19285 (cond
19286 ((stringp p) p)
19287 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19288 (format "%% Package %s omitted" (cadr p)))
19289 ((equal "" (car p))
19290 (format "\\usepackage{%s}" (cadr p)))
19292 (format "\\usepackage[%s]{%s}"
19293 (car p) (cadr p)))))
19295 "\n"))
19296 (if newline (concat pkg "\n") pkg))
19298 (defun org-dvipng-color (attr)
19299 "Return a RGB color specification for dvipng."
19300 (org-dvipng-color-format (face-attribute 'default attr nil)))
19302 (defun org-dvipng-color-format (color-name)
19303 "Convert COLOR-NAME to a RGB color value for dvipng."
19304 (apply #'format "rgb %s %s %s"
19305 (mapcar 'org-normalize-color
19306 (color-values color-name))))
19308 (defun org-latex-color (attr)
19309 "Return a RGB color for the LaTeX color package."
19310 (org-latex-color-format (face-attribute 'default attr nil)))
19312 (defun org-latex-color-format (color-name)
19313 "Convert COLOR-NAME to a RGB color value."
19314 (apply #'format "%s,%s,%s"
19315 (mapcar 'org-normalize-color
19316 (color-values color-name))))
19318 (defun org-normalize-color (value)
19319 "Return string to be used as color value for an RGB component."
19320 (format "%g" (/ value 65535.0)))
19324 ;; Image display
19326 (defvar-local org-inline-image-overlays nil)
19328 (defun org-toggle-inline-images (&optional include-linked)
19329 "Toggle the display of inline images.
19330 INCLUDE-LINKED is passed to `org-display-inline-images'."
19331 (interactive "P")
19332 (if org-inline-image-overlays
19333 (progn
19334 (org-remove-inline-images)
19335 (when (called-interactively-p 'interactive)
19336 (message "Inline image display turned off")))
19337 (org-display-inline-images include-linked)
19338 (when (called-interactively-p 'interactive)
19339 (message (if org-inline-image-overlays
19340 (format "%d images displayed inline"
19341 (length org-inline-image-overlays))
19342 "No images to display inline")))))
19344 (defun org-redisplay-inline-images ()
19345 "Refresh the display of inline images."
19346 (interactive)
19347 (if (not org-inline-image-overlays)
19348 (org-toggle-inline-images)
19349 (org-toggle-inline-images)
19350 (org-toggle-inline-images)))
19352 (defun org-display-inline-images (&optional include-linked refresh beg end)
19353 "Display inline images.
19355 An inline image is a link which follows either of these
19356 conventions:
19358 1. Its path is a file with an extension matching return value
19359 from `image-file-name-regexp' and it has no contents.
19361 2. Its description consists in a single link of the previous
19362 type.
19364 When optional argument INCLUDE-LINKED is non-nil, also links with
19365 a text description part will be inlined. This can be nice for
19366 a quick look at those images, but it does not reflect what
19367 exported files will look like.
19369 When optional argument REFRESH is non-nil, refresh existing
19370 images between BEG and END. This will create new image displays
19371 only if necessary. BEG and END default to the buffer
19372 boundaries."
19373 (interactive "P")
19374 (when (display-graphic-p)
19375 (unless refresh
19376 (org-remove-inline-images)
19377 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19378 (org-with-wide-buffer
19379 (goto-char (or beg (point-min)))
19380 (let ((case-fold-search t)
19381 (file-extension-re (image-file-name-regexp)))
19382 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19383 (let ((link (save-match-data (org-element-context))))
19384 ;; Check if we're at an inline image.
19385 (when (and (equal (org-element-property :type link) "file")
19386 (or include-linked
19387 (not (org-element-property :contents-begin link)))
19388 (let ((parent (org-element-property :parent link)))
19389 (or (not (eq (org-element-type parent) 'link))
19390 (not (cdr (org-element-contents parent)))))
19391 (string-match-p file-extension-re
19392 (org-element-property :path link)))
19393 (let ((file (expand-file-name
19394 (org-link-unescape
19395 (org-element-property :path link)))))
19396 (when (file-exists-p file)
19397 (let ((width
19398 ;; Apply `org-image-actual-width' specifications.
19399 (cond
19400 ((not (image-type-available-p 'imagemagick)) nil)
19401 ((eq org-image-actual-width t) nil)
19402 ((listp org-image-actual-width)
19404 ;; First try to find a width among
19405 ;; attributes associated to the paragraph
19406 ;; containing link.
19407 (let ((paragraph
19408 (let ((e link))
19409 (while (and (setq e (org-element-property
19410 :parent e))
19411 (not (eq (org-element-type e)
19412 'paragraph))))
19413 e)))
19414 (when paragraph
19415 (save-excursion
19416 (goto-char (org-element-property :begin paragraph))
19417 (when
19418 (re-search-forward
19419 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19420 (org-element-property
19421 :post-affiliated paragraph)
19423 (string-to-number (match-string 1))))))
19424 ;; Otherwise, fall-back to provided number.
19425 (car org-image-actual-width)))
19426 ((numberp org-image-actual-width)
19427 org-image-actual-width)))
19428 (old (get-char-property-and-overlay
19429 (org-element-property :begin link)
19430 'org-image-overlay)))
19431 (if (and (car-safe old) refresh)
19432 (image-refresh (overlay-get (cdr old) 'display))
19433 (let ((image (create-image file
19434 (and width 'imagemagick)
19436 :width width)))
19437 (when image
19438 (let* ((link
19439 ;; If inline image is the description
19440 ;; of another link, be sure to
19441 ;; consider the latter as the one to
19442 ;; apply the overlay on.
19443 (let ((parent
19444 (org-element-property :parent link)))
19445 (if (eq (org-element-type parent) 'link)
19446 parent
19447 link)))
19448 (ov (make-overlay
19449 (org-element-property :begin link)
19450 (progn
19451 (goto-char
19452 (org-element-property :end link))
19453 (skip-chars-backward " \t")
19454 (point)))))
19455 (overlay-put ov 'display image)
19456 (overlay-put ov 'face 'default)
19457 (overlay-put ov 'org-image-overlay t)
19458 (overlay-put
19459 ov 'modification-hooks
19460 (list 'org-display-inline-remove-overlay))
19461 (push ov org-inline-image-overlays)))))))))))))))
19463 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19464 "Remove inline-display overlay if a corresponding region is modified."
19465 (let ((inhibit-modification-hooks t))
19466 (when (and ov after)
19467 (delete ov org-inline-image-overlays)
19468 (delete-overlay ov))))
19470 (defun org-remove-inline-images ()
19471 "Remove inline display of images."
19472 (interactive)
19473 (mapc #'delete-overlay org-inline-image-overlays)
19474 (setq org-inline-image-overlays nil))
19476 ;;;; Key bindings
19478 ;; Outline functions from `outline-mode-prefix-map'
19479 ;; that can be remapped in Org:
19480 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19481 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19482 (define-key org-mode-map [remap outline-forward-same-level]
19483 'org-forward-heading-same-level)
19484 (define-key org-mode-map [remap outline-backward-same-level]
19485 'org-backward-heading-same-level)
19486 (define-key org-mode-map [remap outline-show-branches]
19487 'org-kill-note-or-show-branches)
19488 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19489 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19490 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19491 (define-key org-mode-map [remap outline-next-visible-heading]
19492 'org-next-visible-heading)
19493 (define-key org-mode-map [remap outline-previous-visible-heading]
19494 'org-previous-visible-heading)
19495 (define-key org-mode-map [remap show-children] 'org-show-children)
19497 ;; Outline functions from `outline-mode-prefix-map' that can not
19498 ;; be remapped in Org:
19500 ;; - the column "key binding" shows whether the Outline function is still
19501 ;; available in Org mode on the same key that it has been bound to in
19502 ;; Outline mode:
19503 ;; - "overridden": key used for a different functionality in Org mode
19504 ;; - else: key still bound to the same Outline function in Org mode
19506 ;; | Outline function | key binding | Org replacement |
19507 ;; |------------------------------------+-------------+--------------------------|
19508 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19509 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19510 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19511 ;; | `show-entry' | overridden | no replacement |
19512 ;; | `show-branches' | `C-c C-k' | still same function |
19513 ;; | `show-subtree' | overridden | visibility cycling |
19514 ;; | `show-all' | overridden | no replacement |
19515 ;; | `hide-subtree' | overridden | visibility cycling |
19516 ;; | `hide-body' | overridden | no replacement |
19517 ;; | `hide-entry' | overridden | visibility cycling |
19518 ;; | `hide-leaves' | overridden | no replacement |
19519 ;; | `hide-sublevels' | overridden | no replacement |
19520 ;; | `hide-other' | overridden | no replacement |
19522 ;; Make `C-c C-x' a prefix key
19523 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19525 ;; TAB key with modifiers
19526 (org-defkey org-mode-map "\C-i" 'org-cycle)
19527 (org-defkey org-mode-map [(tab)] 'org-cycle)
19528 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19529 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19530 ;; The following line is necessary under Suse GNU/Linux
19531 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19532 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19533 (define-key org-mode-map [backtab] 'org-shifttab)
19535 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19536 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19537 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19539 ;; Cursor keys with modifiers
19540 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19541 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19542 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19543 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19545 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19546 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19547 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19548 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19549 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19550 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19552 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19553 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19554 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19555 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19557 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19558 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19559 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19560 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19562 ;; Babel keys
19563 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19564 (dolist (pair org-babel-key-bindings)
19565 (define-key org-babel-map (car pair) (cdr pair)))
19567 ;;; Extra keys for tty access.
19568 ;; We only set them when really needed because otherwise the
19569 ;; menus don't show the simple keys
19571 (when (or org-use-extra-keys (not window-system))
19572 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19573 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19574 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19575 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19576 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19577 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19578 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19579 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19580 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19581 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19582 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19583 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19584 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19585 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19586 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19587 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19588 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19589 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19590 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19591 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19592 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19593 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19594 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19595 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19596 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19597 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19598 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19599 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19601 ;; All the other keys
19603 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19604 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19605 (if (boundp 'narrow-map)
19606 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19607 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19608 (if (boundp 'narrow-map)
19609 (org-defkey narrow-map "b" 'org-narrow-to-block)
19610 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19611 (if (boundp 'narrow-map)
19612 (org-defkey narrow-map "e" 'org-narrow-to-element)
19613 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19614 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19615 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19616 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19617 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19618 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19619 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19620 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19621 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19622 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19623 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19624 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19625 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19626 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19627 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19628 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19629 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19630 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19631 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19632 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19633 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19634 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19635 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19636 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19637 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19638 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19639 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19640 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19641 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19642 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19643 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19644 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19645 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19646 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19647 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19648 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19649 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19650 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19651 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19652 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19653 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19654 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19655 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19656 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19657 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19658 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19659 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19660 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19661 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19662 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19663 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19664 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19665 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19666 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19667 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19668 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19669 (org-defkey org-mode-map "\C-c^" 'org-sort)
19670 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19671 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19672 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19673 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19674 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19675 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19676 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19677 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19678 (org-defkey org-mode-map "\C-m" 'org-return)
19679 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19680 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19681 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19682 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19683 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19684 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19685 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19686 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19687 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19688 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19689 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19690 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19691 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19692 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19693 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19694 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19695 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19696 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19697 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19698 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19699 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19700 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19701 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19702 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19703 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19705 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19706 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19707 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19709 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19710 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19711 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19712 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19713 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19714 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19715 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19716 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19717 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19718 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19719 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19720 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19721 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19722 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19723 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19724 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19725 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19726 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19727 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19728 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19729 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19730 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19732 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19733 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19734 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19735 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19736 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19738 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19740 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19742 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19743 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19745 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19748 (defconst org-speed-commands-default
19750 ("Outline Navigation")
19751 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19752 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19753 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19754 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19755 ("F" . org-next-block)
19756 ("B" . org-previous-block)
19757 ("u" . (org-speed-move-safe 'outline-up-heading))
19758 ("j" . org-goto)
19759 ("g" . (org-refile t))
19760 ("Outline Visibility")
19761 ("c" . org-cycle)
19762 ("C" . org-shifttab)
19763 (" " . org-display-outline-path)
19764 ("s" . org-narrow-to-subtree)
19765 ("=" . org-columns)
19766 ("Outline Structure Editing")
19767 ("U" . org-metaup)
19768 ("D" . org-metadown)
19769 ("r" . org-metaright)
19770 ("l" . org-metaleft)
19771 ("R" . org-shiftmetaright)
19772 ("L" . org-shiftmetaleft)
19773 ("i" . (progn (forward-char 1) (call-interactively
19774 'org-insert-heading-respect-content)))
19775 ("^" . org-sort)
19776 ("w" . org-refile)
19777 ("a" . org-archive-subtree-default-with-confirmation)
19778 ("@" . org-mark-subtree)
19779 ("#" . org-toggle-comment)
19780 ("Clock Commands")
19781 ("I" . org-clock-in)
19782 ("O" . org-clock-out)
19783 ("Meta Data Editing")
19784 ("t" . org-todo)
19785 ("," . (org-priority))
19786 ("0" . (org-priority ?\ ))
19787 ("1" . (org-priority ?A))
19788 ("2" . (org-priority ?B))
19789 ("3" . (org-priority ?C))
19790 (":" . org-set-tags-command)
19791 ("e" . org-set-effort)
19792 ("E" . org-inc-effort)
19793 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19794 (org-entry-put (point) "APPT_WARNTIME" m)))
19795 ("Agenda Views etc")
19796 ("v" . org-agenda)
19797 ("/" . org-sparse-tree)
19798 ("Misc")
19799 ("o" . org-open-at-point)
19800 ("?" . org-speed-command-help)
19801 ("<" . (org-agenda-set-restriction-lock 'subtree))
19802 (">" . (org-agenda-remove-restriction-lock))
19804 "The default speed commands.")
19806 (defun org-print-speed-command (e)
19807 (if (> (length (car e)) 1)
19808 (progn
19809 (princ "\n")
19810 (princ (car e))
19811 (princ "\n")
19812 (princ (make-string (length (car e)) ?-))
19813 (princ "\n"))
19814 (princ (car e))
19815 (princ " ")
19816 (if (symbolp (cdr e))
19817 (princ (symbol-name (cdr e)))
19818 (prin1 (cdr e)))
19819 (princ "\n")))
19821 (defun org-speed-command-help ()
19822 "Show the available speed commands."
19823 (interactive)
19824 (if (not org-use-speed-commands)
19825 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19826 (with-output-to-temp-buffer "*Help*"
19827 (princ "User-defined Speed commands\n===========================\n")
19828 (mapc #'org-print-speed-command org-speed-commands-user)
19829 (princ "\n")
19830 (princ "Built-in Speed commands\n=======================\n")
19831 (mapc #'org-print-speed-command org-speed-commands-default))
19832 (with-current-buffer "*Help*"
19833 (setq truncate-lines t))))
19835 (defun org-speed-move-safe (cmd)
19836 "Execute CMD, but make sure that the cursor always ends up in a headline.
19837 If not, return to the original position and throw an error."
19838 (interactive)
19839 (let ((pos (point)))
19840 (call-interactively cmd)
19841 (unless (and (bolp) (org-at-heading-p))
19842 (goto-char pos)
19843 (error "Boundary reached while executing %s" cmd))))
19845 (defvar org-self-insert-command-undo-counter 0)
19847 (defvar org-table-auto-blank-field) ; defined in org-table.el
19848 (defvar org-speed-command nil)
19850 (defun org-speed-command-activate (keys)
19851 "Hook for activating single-letter speed commands.
19852 `org-speed-commands-default' specifies a minimal command set.
19853 Use `org-speed-commands-user' for further customization."
19854 (when (or (and (bolp) (looking-at org-outline-regexp))
19855 (and (functionp org-use-speed-commands)
19856 (funcall org-use-speed-commands)))
19857 (cdr (assoc keys (append org-speed-commands-user
19858 org-speed-commands-default)))))
19860 (defun org-babel-speed-command-activate (keys)
19861 "Hook for activating single-letter code block commands."
19862 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19863 (cdr (assoc keys org-babel-key-bindings))))
19865 (defcustom org-speed-command-hook
19866 '(org-speed-command-activate org-babel-speed-command-activate)
19867 "Hook for activating speed commands at strategic locations.
19868 Hook functions are called in sequence until a valid handler is
19869 found.
19871 Each hook takes a single argument, a user-pressed command key
19872 which is also a `self-insert-command' from the global map.
19874 Within the hook, examine the cursor position and the command key
19875 and return nil or a valid handler as appropriate. Handler could
19876 be one of an interactive command, a function, or a form.
19878 Set `org-use-speed-commands' to non-nil value to enable this
19879 hook. The default setting is `org-speed-command-activate'."
19880 :group 'org-structure
19881 :version "24.1"
19882 :type 'hook)
19884 (defun org-self-insert-command (N)
19885 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19886 If the cursor is in a table looking at whitespace, the whitespace is
19887 overwritten, and the table is not marked as requiring realignment."
19888 (interactive "p")
19889 (org-check-before-invisible-edit 'insert)
19890 (cond
19891 ((and org-use-speed-commands
19892 (let ((kv (this-command-keys-vector)))
19893 (setq org-speed-command
19894 (run-hook-with-args-until-success
19895 'org-speed-command-hook
19896 (make-string 1 (aref kv (1- (length kv))))))))
19897 (cond
19898 ((commandp org-speed-command)
19899 (setq this-command org-speed-command)
19900 (call-interactively org-speed-command))
19901 ((functionp org-speed-command)
19902 (funcall org-speed-command))
19903 ((and org-speed-command (listp org-speed-command))
19904 (eval org-speed-command))
19905 (t (let (org-use-speed-commands)
19906 (call-interactively 'org-self-insert-command)))))
19907 ((and
19908 (org-at-table-p)
19909 (progn
19910 ;; Check if we blank the field, and if that triggers align.
19911 (and (featurep 'org-table) org-table-auto-blank-field
19912 (memq last-command
19913 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19914 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19915 ;; Got extra space, this field does not determine
19916 ;; column width.
19917 (let (org-table-may-need-update) (org-table-blank-field))
19918 ;; No extra space, this field may determine column
19919 ;; width.
19920 (org-table-blank-field)))
19922 (eq N 1)
19923 (looking-at "[^|\n]* \\( \\)|"))
19924 ;; There is room for insertion without re-aligning the table.
19925 (delete-region (match-beginning 1) (match-end 1))
19926 (self-insert-command N))
19928 (setq org-table-may-need-update t)
19929 (self-insert-command N)
19930 (org-fix-tags-on-the-fly)
19931 (when org-self-insert-cluster-for-undo
19932 (if (not (eq last-command 'org-self-insert-command))
19933 (setq org-self-insert-command-undo-counter 1)
19934 (if (>= org-self-insert-command-undo-counter 20)
19935 (setq org-self-insert-command-undo-counter 1)
19936 (and (> org-self-insert-command-undo-counter 0)
19937 buffer-undo-list (listp buffer-undo-list)
19938 (not (cadr buffer-undo-list)) ; remove nil entry
19939 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19940 (setq org-self-insert-command-undo-counter
19941 (1+ org-self-insert-command-undo-counter))))))))
19943 (defun org-check-before-invisible-edit (kind)
19944 "Check is editing if kind KIND would be dangerous with invisible text around.
19945 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19946 ;; First, try to get out of here as quickly as possible, to reduce overhead
19947 (when (and org-catch-invisible-edits
19948 (or (not (boundp 'visible-mode)) (not visible-mode))
19949 (or (get-char-property (point) 'invisible)
19950 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19951 ;; OK, we need to take a closer look
19952 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19953 (invisible-before-point (unless (bobp) (get-char-property
19954 (1- (point)) 'invisible)))
19955 (border-and-ok-direction
19957 ;; Check if we are acting predictably before invisible text
19958 (and invisible-at-point (not invisible-before-point)
19959 (memq kind '(insert delete-backward)))
19960 ;; Check if we are acting predictably after invisible text
19961 ;; This works not well, and I have turned it off. It seems
19962 ;; better to always show and stop after invisible text.
19963 ;; (and (not invisible-at-point) invisible-before-point
19964 ;; (memq kind '(insert delete)))
19966 (when (or (memq invisible-at-point '(outline org-hide-block t))
19967 (memq invisible-before-point '(outline org-hide-block t)))
19968 (when (eq org-catch-invisible-edits 'error)
19969 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19970 (if (and org-custom-properties-overlays
19971 (y-or-n-p "Display invisible properties in this buffer? "))
19972 (org-toggle-custom-properties-visibility)
19973 ;; Make the area visible
19974 (save-excursion
19975 (when invisible-before-point
19976 (goto-char (previous-single-char-property-change
19977 (point) 'invisible)))
19978 (outline-show-subtree))
19979 (cond
19980 ((eq org-catch-invisible-edits 'show)
19981 ;; That's it, we do the edit after showing
19982 (message
19983 "Unfolding invisible region around point before editing")
19984 (sit-for 1))
19985 ((and (eq org-catch-invisible-edits 'smart)
19986 border-and-ok-direction)
19987 (message "Unfolding invisible region around point before editing"))
19989 ;; Don't do the edit, make the user repeat it in full visibility
19990 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19992 (defun org-fix-tags-on-the-fly ()
19993 "Align tags in headline at point.
19994 Unlike to `org-set-tags', it ignores region and sorting."
19995 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19996 (org-at-heading-p))
19997 (let ((org-ignore-region t)
19998 (org-tags-sort-function nil))
19999 (org-set-tags nil t))))
20001 (defun org-delete-backward-char (N)
20002 "Like `delete-backward-char', insert whitespace at field end in tables.
20003 When deleting backwards, in tables this function will insert whitespace in
20004 front of the next \"|\" separator, to keep the table aligned. The table will
20005 still be marked for re-alignment if the field did fill the entire column,
20006 because, in this case the deletion might narrow the column."
20007 (interactive "p")
20008 (save-match-data
20009 (org-check-before-invisible-edit 'delete-backward)
20010 (if (and (org-at-table-p)
20011 (eq N 1)
20012 (string-match "|" (buffer-substring (point-at-bol) (point)))
20013 (looking-at ".*?|"))
20014 (let ((pos (point))
20015 (noalign (looking-at "[^|\n\r]* |"))
20016 (c org-table-may-need-update))
20017 (backward-delete-char N)
20018 (unless overwrite-mode
20019 (skip-chars-forward "^|")
20020 (insert " ")
20021 (goto-char (1- pos)))
20022 ;; noalign: if there were two spaces at the end, this field
20023 ;; does not determine the width of the column.
20024 (when noalign (setq org-table-may-need-update c)))
20025 (backward-delete-char N)
20026 (org-fix-tags-on-the-fly))))
20028 (defun org-delete-char (N)
20029 "Like `delete-char', but insert whitespace at field end in tables.
20030 When deleting characters, in tables this function will insert whitespace in
20031 front of the next \"|\" separator, to keep the table aligned. The table will
20032 still be marked for re-alignment if the field did fill the entire column,
20033 because, in this case the deletion might narrow the column."
20034 (interactive "p")
20035 (save-match-data
20036 (org-check-before-invisible-edit 'delete)
20037 (if (and (org-at-table-p)
20038 (not (bolp))
20039 (not (= (char-after) ?|))
20040 (eq N 1))
20041 (if (looking-at ".*?|")
20042 (let ((pos (point))
20043 (noalign (looking-at "[^|\n\r]* |"))
20044 (c org-table-may-need-update))
20045 (replace-match
20046 (concat (substring (match-string 0) 1 -1) " |") nil t)
20047 (goto-char pos)
20048 ;; noalign: if there were two spaces at the end, this field
20049 ;; does not determine the width of the column.
20050 (when noalign (setq org-table-may-need-update c)))
20051 (delete-char N))
20052 (delete-char N)
20053 (org-fix-tags-on-the-fly))))
20055 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20056 (put 'org-self-insert-command 'delete-selection
20057 (lambda ()
20058 (not (run-hook-with-args-until-success
20059 'self-insert-uses-region-functions))))
20060 (put 'orgtbl-self-insert-command 'delete-selection
20061 (lambda ()
20062 (not (run-hook-with-args-until-success
20063 'self-insert-uses-region-functions))))
20064 (put 'org-delete-char 'delete-selection 'supersede)
20065 (put 'org-delete-backward-char 'delete-selection 'supersede)
20066 (put 'org-yank 'delete-selection 'yank)
20068 ;; Make `flyspell-mode' delay after some commands
20069 (put 'org-self-insert-command 'flyspell-delayed t)
20070 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20071 (put 'org-delete-char 'flyspell-delayed t)
20072 (put 'org-delete-backward-char 'flyspell-delayed t)
20074 ;; Make pabbrev-mode expand after Org mode commands
20075 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20076 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20078 (defun org-remap (map &rest commands)
20079 "In MAP, remap the functions given in COMMANDS.
20080 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20081 (let (new old)
20082 (while commands
20083 (setq old (pop commands) new (pop commands))
20084 (org-defkey map (vector 'remap old) new))))
20086 (defun org-transpose-words ()
20087 "Transpose words for Org.
20088 This uses the `org-mode-transpose-word-syntax-table' syntax
20089 table, which interprets characters in `org-emphasis-alist' as
20090 word constituents."
20091 (interactive)
20092 (with-syntax-table org-mode-transpose-word-syntax-table
20093 (call-interactively 'transpose-words)))
20094 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20096 (when (eq org-enable-table-editor 'optimized)
20097 ;; If the user wants maximum table support, we need to hijack
20098 ;; some standard editing functions
20099 (org-remap org-mode-map
20100 'self-insert-command 'org-self-insert-command
20101 'delete-char 'org-delete-char
20102 'delete-backward-char 'org-delete-backward-char)
20103 (org-defkey org-mode-map "|" 'org-force-self-insert))
20105 (defvar org-ctrl-c-ctrl-c-hook nil
20106 "Hook for functions attaching themselves to `C-c C-c'.
20108 This can be used to add additional functionality to the C-c C-c
20109 key which executes context-dependent commands. This hook is run
20110 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20111 run after the last test.
20113 Each function will be called with no arguments. The function
20114 must check if the context is appropriate for it to act. If yes,
20115 it should do its thing and then return a non-nil value. If the
20116 context is wrong, just do nothing and return nil.")
20118 (defvar org-ctrl-c-ctrl-c-final-hook nil
20119 "Hook for functions attaching themselves to `C-c C-c'.
20121 This can be used to add additional functionality to the C-c C-c
20122 key which executes context-dependent commands. This hook is run
20123 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20124 before the first test.
20126 Each function will be called with no arguments. The function
20127 must check if the context is appropriate for it to act. If yes,
20128 it should do its thing and then return a non-nil value. If the
20129 context is wrong, just do nothing and return nil.")
20131 (defvar org-tab-first-hook nil
20132 "Hook for functions to attach themselves to TAB.
20133 See `org-ctrl-c-ctrl-c-hook' for more information.
20134 This hook runs as the first action when TAB is pressed, even before
20135 `org-cycle' messes around with the `outline-regexp' to cater for
20136 inline tasks and plain list item folding.
20137 If any function in this hook returns t, any other actions that
20138 would have been caused by TAB (such as table field motion or visibility
20139 cycling) will not occur.")
20141 (defvar org-tab-after-check-for-table-hook nil
20142 "Hook for functions to attach themselves to TAB.
20143 See `org-ctrl-c-ctrl-c-hook' for more information.
20144 This hook runs after it has been established that the cursor is not in a
20145 table, but before checking if the cursor is in a headline or if global cycling
20146 should be done.
20147 If any function in this hook returns t, not other actions like visibility
20148 cycling will be done.")
20150 (defvar org-tab-after-check-for-cycling-hook nil
20151 "Hook for functions to attach themselves to TAB.
20152 See `org-ctrl-c-ctrl-c-hook' for more information.
20153 This hook runs after it has been established that not table field motion and
20154 not visibility should be done because of current context. This is probably
20155 the place where a package like yasnippets can hook in.")
20157 (defvar org-tab-before-tab-emulation-hook nil
20158 "Hook for functions to attach themselves to TAB.
20159 See `org-ctrl-c-ctrl-c-hook' for more information.
20160 This hook runs after every other options for TAB have been exhausted, but
20161 before indentation and \t insertion takes place.")
20163 (defvar org-metaleft-hook nil
20164 "Hook for functions attaching themselves to `M-left'.
20165 See `org-ctrl-c-ctrl-c-hook' for more information.")
20166 (defvar org-metaright-hook nil
20167 "Hook for functions attaching themselves to `M-right'.
20168 See `org-ctrl-c-ctrl-c-hook' for more information.")
20169 (defvar org-metaup-hook nil
20170 "Hook for functions attaching themselves to `M-up'.
20171 See `org-ctrl-c-ctrl-c-hook' for more information.")
20172 (defvar org-metadown-hook nil
20173 "Hook for functions attaching themselves to `M-down'.
20174 See `org-ctrl-c-ctrl-c-hook' for more information.")
20175 (defvar org-shiftmetaleft-hook nil
20176 "Hook for functions attaching themselves to `M-S-left'.
20177 See `org-ctrl-c-ctrl-c-hook' for more information.")
20178 (defvar org-shiftmetaright-hook nil
20179 "Hook for functions attaching themselves to `M-S-right'.
20180 See `org-ctrl-c-ctrl-c-hook' for more information.")
20181 (defvar org-shiftmetaup-hook nil
20182 "Hook for functions attaching themselves to `M-S-up'.
20183 See `org-ctrl-c-ctrl-c-hook' for more information.")
20184 (defvar org-shiftmetadown-hook nil
20185 "Hook for functions attaching themselves to `M-S-down'.
20186 See `org-ctrl-c-ctrl-c-hook' for more information.")
20187 (defvar org-metareturn-hook nil
20188 "Hook for functions attaching themselves to `M-RET'.
20189 See `org-ctrl-c-ctrl-c-hook' for more information.")
20190 (defvar org-shiftup-hook nil
20191 "Hook for functions attaching themselves to `S-up'.
20192 See `org-ctrl-c-ctrl-c-hook' for more information.")
20193 (defvar org-shiftup-final-hook nil
20194 "Hook for functions attaching themselves to `S-up'.
20195 This one runs after all other options except shift-select have been excluded.
20196 See `org-ctrl-c-ctrl-c-hook' for more information.")
20197 (defvar org-shiftdown-hook nil
20198 "Hook for functions attaching themselves to `S-down'.
20199 See `org-ctrl-c-ctrl-c-hook' for more information.")
20200 (defvar org-shiftdown-final-hook nil
20201 "Hook for functions attaching themselves to `S-down'.
20202 This one runs after all other options except shift-select have been excluded.
20203 See `org-ctrl-c-ctrl-c-hook' for more information.")
20204 (defvar org-shiftleft-hook nil
20205 "Hook for functions attaching themselves to `S-left'.
20206 See `org-ctrl-c-ctrl-c-hook' for more information.")
20207 (defvar org-shiftleft-final-hook nil
20208 "Hook for functions attaching themselves to `S-left'.
20209 This one runs after all other options except shift-select have been excluded.
20210 See `org-ctrl-c-ctrl-c-hook' for more information.")
20211 (defvar org-shiftright-hook nil
20212 "Hook for functions attaching themselves to `S-right'.
20213 See `org-ctrl-c-ctrl-c-hook' for more information.")
20214 (defvar org-shiftright-final-hook nil
20215 "Hook for functions attaching themselves to `S-right'.
20216 This one runs after all other options except shift-select have been excluded.
20217 See `org-ctrl-c-ctrl-c-hook' for more information.")
20219 (defun org-modifier-cursor-error ()
20220 "Throw an error, a modified cursor command was applied in wrong context."
20221 (user-error "This command is active in special context like tables, headlines or items"))
20223 (defun org-shiftselect-error ()
20224 "Throw an error because Shift-Cursor command was applied in wrong context."
20225 (if (and (boundp 'shift-select-mode) shift-select-mode)
20226 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20227 (user-error "This command works only in special context like headlines or timestamps")))
20229 (defun org-call-for-shift-select (cmd)
20230 (let ((this-command-keys-shift-translated t))
20231 (call-interactively cmd)))
20233 (defun org-shifttab (&optional arg)
20234 "Global visibility cycling or move to previous table field.
20235 Call `org-table-previous-field' within a table.
20236 When ARG is nil, cycle globally through visibility states.
20237 When ARG is a numeric prefix, show contents of this level."
20238 (interactive "P")
20239 (cond
20240 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20241 ((integerp arg)
20242 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20243 (message "Content view to level: %d" arg)
20244 (org-content (prefix-numeric-value arg2))
20245 (org-cycle-show-empty-lines t)
20246 (setq org-cycle-global-status 'overview)))
20247 (t (call-interactively 'org-global-cycle))))
20249 (defun org-shiftmetaleft ()
20250 "Promote subtree or delete table column.
20251 Calls `org-promote-subtree', `org-outdent-item-tree', or
20252 `org-table-delete-column', depending on context. See the
20253 individual commands for more information."
20254 (interactive)
20255 (cond
20256 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20257 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20258 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20259 ((if (not (org-region-active-p)) (org-at-item-p)
20260 (save-excursion (goto-char (region-beginning))
20261 (org-at-item-p)))
20262 (call-interactively 'org-outdent-item-tree))
20263 (t (org-modifier-cursor-error))))
20265 (defun org-shiftmetaright ()
20266 "Demote subtree or insert table column.
20267 Calls `org-demote-subtree', `org-indent-item-tree', or
20268 `org-table-insert-column', depending on context. See the
20269 individual commands for more information."
20270 (interactive)
20271 (cond
20272 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20273 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20274 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20275 ((if (not (org-region-active-p)) (org-at-item-p)
20276 (save-excursion (goto-char (region-beginning))
20277 (org-at-item-p)))
20278 (call-interactively 'org-indent-item-tree))
20279 (t (org-modifier-cursor-error))))
20281 (defun org-shiftmetaup (&optional _arg)
20282 "Drag the line at point up.
20283 In a table, kill the current row.
20284 On a clock timestamp, update the value of the timestamp like `S-<up>'
20285 but also adjust the previous clocked item in the clock history.
20286 Everywhere else, drag the line at point up."
20287 (interactive "P")
20288 (cond
20289 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20290 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20291 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20292 (call-interactively 'org-timestamp-up)))
20293 (t (call-interactively 'org-drag-line-backward))))
20295 (defun org-shiftmetadown (&optional _arg)
20296 "Drag the line at point down.
20297 In a table, insert an empty row at the current line.
20298 On a clock timestamp, update the value of the timestamp like `S-<down>'
20299 but also adjust the previous clocked item in the clock history.
20300 Everywhere else, drag the line at point down."
20301 (interactive "P")
20302 (cond
20303 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20304 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20305 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20306 (call-interactively 'org-timestamp-down)))
20307 (t (call-interactively 'org-drag-line-forward))))
20309 (defsubst org-hidden-tree-error ()
20310 (user-error
20311 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20313 (defun org-metaleft (&optional _arg)
20314 "Promote heading, list item at point or move table column left.
20316 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20317 depending on context. With no specific context, calls the Emacs
20318 default `backward-word'. See the individual commands for more
20319 information.
20321 This function runs the hook `org-metaleft-hook' as a first step,
20322 and returns at first non-nil value."
20323 (interactive "P")
20324 (cond
20325 ((run-hook-with-args-until-success 'org-metaleft-hook))
20326 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20327 ((org-with-limited-levels
20328 (or (org-at-heading-p)
20329 (and (org-region-active-p)
20330 (save-excursion
20331 (goto-char (region-beginning))
20332 (org-at-heading-p)))))
20333 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20334 (call-interactively 'org-do-promote))
20335 ;; At an inline task.
20336 ((org-at-heading-p)
20337 (call-interactively 'org-inlinetask-promote))
20338 ((or (org-at-item-p)
20339 (and (org-region-active-p)
20340 (save-excursion
20341 (goto-char (region-beginning))
20342 (org-at-item-p))))
20343 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20344 (call-interactively 'org-outdent-item))
20345 (t (call-interactively 'backward-word))))
20347 (defun org-metaright (&optional _arg)
20348 "Demote heading, list item at point or move table column right.
20350 In front of a drawer or a block keyword, indent it correctly.
20352 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20353 `org-indent-drawer' or `org-indent-block' depending on context.
20354 With no specific context, calls the Emacs default `forward-word'.
20355 See the individual commands for more information.
20357 This function runs the hook `org-metaright-hook' as a first step,
20358 and returns at first non-nil value."
20359 (interactive "P")
20360 (cond
20361 ((run-hook-with-args-until-success 'org-metaright-hook))
20362 ((org-at-table-p) (call-interactively 'org-table-move-column))
20363 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20364 ((org-at-block-p) (call-interactively 'org-indent-block))
20365 ((org-with-limited-levels
20366 (or (org-at-heading-p)
20367 (and (org-region-active-p)
20368 (save-excursion
20369 (goto-char (region-beginning))
20370 (org-at-heading-p)))))
20371 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20372 (call-interactively 'org-do-demote))
20373 ;; At an inline task.
20374 ((org-at-heading-p)
20375 (call-interactively 'org-inlinetask-demote))
20376 ((or (org-at-item-p)
20377 (and (org-region-active-p)
20378 (save-excursion
20379 (goto-char (region-beginning))
20380 (org-at-item-p))))
20381 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20382 (call-interactively 'org-indent-item))
20383 (t (call-interactively 'forward-word))))
20385 (defun org-check-for-hidden (what)
20386 "Check if there are hidden headlines/items in the current visual line.
20387 WHAT can be either `headlines' or `items'. If the current line is
20388 an outline or item heading and it has a folded subtree below it,
20389 this function returns t, nil otherwise."
20390 (let ((re (cond
20391 ((eq what 'headlines) org-outline-regexp-bol)
20392 ((eq what 'items) (org-item-beginning-re))
20393 (t (error "This should not happen"))))
20394 beg end)
20395 (save-excursion
20396 (catch 'exit
20397 (unless (org-region-active-p)
20398 (setq beg (point-at-bol))
20399 (beginning-of-line 2)
20400 (while (and (not (eobp)) ;; this is like `next-line'
20401 (get-char-property (1- (point)) 'invisible))
20402 (beginning-of-line 2))
20403 (setq end (point))
20404 (goto-char beg)
20405 (goto-char (point-at-eol))
20406 (setq end (max end (point)))
20407 (while (re-search-forward re end t)
20408 (when (get-char-property (match-beginning 0) 'invisible)
20409 (throw 'exit t))))
20410 nil))))
20412 (defun org-metaup (&optional _arg)
20413 "Move subtree up or move table row up.
20414 Calls `org-move-subtree-up' or `org-table-move-row' or
20415 `org-move-item-up', depending on context. See the individual commands
20416 for more information."
20417 (interactive "P")
20418 (cond
20419 ((run-hook-with-args-until-success 'org-metaup-hook))
20420 ((org-region-active-p)
20421 (let* ((a (min (region-beginning) (region-end)))
20422 (b (1- (max (region-beginning) (region-end))))
20423 (c (save-excursion (goto-char a)
20424 (move-beginning-of-line 0)))
20425 (d (save-excursion (goto-char a)
20426 (move-end-of-line 0) (point))))
20427 (transpose-regions a b c d)
20428 (goto-char c)))
20429 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20430 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20431 ((org-at-item-p) (call-interactively 'org-move-item-up))
20432 (t (org-drag-element-backward))))
20434 (defun org-metadown (&optional _arg)
20435 "Move subtree down or move table row down.
20436 Calls `org-move-subtree-down' or `org-table-move-row' or
20437 `org-move-item-down', depending on context. See the individual
20438 commands for more information."
20439 (interactive "P")
20440 (cond
20441 ((run-hook-with-args-until-success 'org-metadown-hook))
20442 ((org-region-active-p)
20443 (let* ((a (min (region-beginning) (region-end)))
20444 (b (max (region-beginning) (region-end)))
20445 (c (save-excursion (goto-char b)
20446 (move-beginning-of-line 1)))
20447 (d (save-excursion (goto-char b)
20448 (move-end-of-line 1) (1+ (point)))))
20449 (transpose-regions a b c d)
20450 (goto-char d)))
20451 ((org-at-table-p) (call-interactively 'org-table-move-row))
20452 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20453 ((org-at-item-p) (call-interactively 'org-move-item-down))
20454 (t (org-drag-element-forward))))
20456 (defun org-shiftup (&optional arg)
20457 "Increase item in timestamp or increase priority of current headline.
20458 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20459 depending on context. See the individual commands for more information."
20460 (interactive "P")
20461 (cond
20462 ((run-hook-with-args-until-success 'org-shiftup-hook))
20463 ((and org-support-shift-select (org-region-active-p))
20464 (org-call-for-shift-select 'previous-line))
20465 ((org-at-timestamp-p 'lax)
20466 (call-interactively (if org-edit-timestamp-down-means-later
20467 'org-timestamp-down 'org-timestamp-up)))
20468 ((and (not (eq org-support-shift-select 'always))
20469 org-enable-priority-commands
20470 (org-at-heading-p))
20471 (call-interactively 'org-priority-up))
20472 ((and (not org-support-shift-select) (org-at-item-p))
20473 (call-interactively 'org-previous-item))
20474 ((org-clocktable-try-shift 'up arg))
20475 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20476 (org-support-shift-select
20477 (org-call-for-shift-select 'previous-line))
20478 (t (org-shiftselect-error))))
20480 (defun org-shiftdown (&optional arg)
20481 "Decrease item in timestamp or decrease priority of current headline.
20482 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20483 depending on context. See the individual commands for more information."
20484 (interactive "P")
20485 (cond
20486 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20487 ((and org-support-shift-select (org-region-active-p))
20488 (org-call-for-shift-select 'next-line))
20489 ((org-at-timestamp-p 'lax)
20490 (call-interactively (if org-edit-timestamp-down-means-later
20491 'org-timestamp-up 'org-timestamp-down)))
20492 ((and (not (eq org-support-shift-select 'always))
20493 org-enable-priority-commands
20494 (org-at-heading-p))
20495 (call-interactively 'org-priority-down))
20496 ((and (not org-support-shift-select) (org-at-item-p))
20497 (call-interactively 'org-next-item))
20498 ((org-clocktable-try-shift 'down arg))
20499 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20500 (org-support-shift-select
20501 (org-call-for-shift-select 'next-line))
20502 (t (org-shiftselect-error))))
20504 (defun org-shiftright (&optional arg)
20505 "Cycle the thing at point or in the current line, depending on context.
20506 Depending on context, this does one of the following:
20508 - switch a timestamp at point one day into the future
20509 - on a headline, switch to the next TODO keyword.
20510 - on an item, switch entire list to the next bullet type
20511 - on a property line, switch to the next allowed value
20512 - on a clocktable definition line, move time block into the future"
20513 (interactive "P")
20514 (cond
20515 ((run-hook-with-args-until-success 'org-shiftright-hook))
20516 ((and org-support-shift-select (org-region-active-p))
20517 (org-call-for-shift-select 'forward-char))
20518 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20519 ((and (not (eq org-support-shift-select 'always))
20520 (org-at-heading-p))
20521 (let ((org-inhibit-logging
20522 (not org-treat-S-cursor-todo-selection-as-state-change))
20523 (org-inhibit-blocking
20524 (not org-treat-S-cursor-todo-selection-as-state-change)))
20525 (org-call-with-arg 'org-todo 'right)))
20526 ((or (and org-support-shift-select
20527 (not (eq org-support-shift-select 'always))
20528 (org-at-item-bullet-p))
20529 (and (not org-support-shift-select) (org-at-item-p)))
20530 (org-call-with-arg 'org-cycle-list-bullet nil))
20531 ((and (not (eq org-support-shift-select 'always))
20532 (org-at-property-p))
20533 (call-interactively 'org-property-next-allowed-value))
20534 ((org-clocktable-try-shift 'right arg))
20535 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20536 (org-support-shift-select
20537 (org-call-for-shift-select 'forward-char))
20538 (t (org-shiftselect-error))))
20540 (defun org-shiftleft (&optional arg)
20541 "Cycle the thing at point or in the current line, depending on context.
20542 Depending on context, this does one of the following:
20544 - switch a timestamp at point one day into the past
20545 - on a headline, switch to the previous TODO keyword.
20546 - on an item, switch entire list to the previous bullet type
20547 - on a property line, switch to the previous allowed value
20548 - on a clocktable definition line, move time block into the past"
20549 (interactive "P")
20550 (cond
20551 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20552 ((and org-support-shift-select (org-region-active-p))
20553 (org-call-for-shift-select 'backward-char))
20554 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20555 ((and (not (eq org-support-shift-select 'always))
20556 (org-at-heading-p))
20557 (let ((org-inhibit-logging
20558 (not org-treat-S-cursor-todo-selection-as-state-change))
20559 (org-inhibit-blocking
20560 (not org-treat-S-cursor-todo-selection-as-state-change)))
20561 (org-call-with-arg 'org-todo 'left)))
20562 ((or (and org-support-shift-select
20563 (not (eq org-support-shift-select 'always))
20564 (org-at-item-bullet-p))
20565 (and (not org-support-shift-select) (org-at-item-p)))
20566 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20567 ((and (not (eq org-support-shift-select 'always))
20568 (org-at-property-p))
20569 (call-interactively 'org-property-previous-allowed-value))
20570 ((org-clocktable-try-shift 'left arg))
20571 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20572 (org-support-shift-select
20573 (org-call-for-shift-select 'backward-char))
20574 (t (org-shiftselect-error))))
20576 (defun org-shiftcontrolright ()
20577 "Switch to next TODO set."
20578 (interactive)
20579 (cond
20580 ((and org-support-shift-select (org-region-active-p))
20581 (org-call-for-shift-select 'forward-word))
20582 ((and (not (eq org-support-shift-select 'always))
20583 (org-at-heading-p))
20584 (org-call-with-arg 'org-todo 'nextset))
20585 (org-support-shift-select
20586 (org-call-for-shift-select 'forward-word))
20587 (t (org-shiftselect-error))))
20589 (defun org-shiftcontrolleft ()
20590 "Switch to previous TODO set."
20591 (interactive)
20592 (cond
20593 ((and org-support-shift-select (org-region-active-p))
20594 (org-call-for-shift-select 'backward-word))
20595 ((and (not (eq org-support-shift-select 'always))
20596 (org-at-heading-p))
20597 (org-call-with-arg 'org-todo 'previousset))
20598 (org-support-shift-select
20599 (org-call-for-shift-select 'backward-word))
20600 (t (org-shiftselect-error))))
20602 (defun org-shiftcontrolup (&optional n)
20603 "Change timestamps synchronously up in CLOCK log lines.
20604 Optional argument N tells to change by that many units."
20605 (interactive "P")
20606 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20607 (let (org-support-shift-select)
20608 (org-clock-timestamps-up n))
20609 (user-error "Not at a clock log")))
20611 (defun org-shiftcontroldown (&optional n)
20612 "Change timestamps synchronously down in CLOCK log lines.
20613 Optional argument N tells to change by that many units."
20614 (interactive "P")
20615 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20616 (let (org-support-shift-select)
20617 (org-clock-timestamps-down n))
20618 (user-error "Not at a clock log")))
20620 (defun org-increase-number-at-point (&optional inc)
20621 "Increment the number at point.
20622 With an optional prefix numeric argument INC, increment using
20623 this numeric value."
20624 (interactive "p")
20625 (if (not (number-at-point))
20626 (user-error "Not on a number")
20627 (unless inc (setq inc 1))
20628 (let ((pos (point))
20629 (beg (skip-chars-backward "-+^/*0-9eE."))
20630 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20631 (setq nap (buffer-substring-no-properties
20632 (+ pos beg) (+ pos beg end)))
20633 (delete-region (+ pos beg) (+ pos beg end))
20634 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20635 (when (org-at-table-p)
20636 (org-table-align)
20637 (org-table-end-of-field 1))))
20639 (defun org-decrease-number-at-point (&optional inc)
20640 "Decrement the number at point.
20641 With an optional prefix numeric argument INC, decrement using
20642 this numeric value."
20643 (interactive "p")
20644 (org-increase-number-at-point (- (or inc 1))))
20646 (defun org-ctrl-c-ret ()
20647 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20648 (interactive)
20649 (cond
20650 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20651 (t (call-interactively 'org-insert-heading))))
20653 (defun org-find-visible ()
20654 (let ((s (point)))
20655 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20656 (get-char-property s 'invisible)))
20658 (defun org-find-invisible ()
20659 (let ((s (point)))
20660 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20661 (not (get-char-property s 'invisible))))
20664 (defun org-copy-visible (beg end)
20665 "Copy the visible parts of the region."
20666 (interactive "r")
20667 (let (snippets s)
20668 (save-excursion
20669 (save-restriction
20670 (narrow-to-region beg end)
20671 (setq s (goto-char (point-min)))
20672 (while (not (= (point) (point-max)))
20673 (goto-char (org-find-invisible))
20674 (push (buffer-substring s (point)) snippets)
20675 (setq s (goto-char (org-find-visible))))))
20676 (kill-new (apply 'concat (nreverse snippets)))))
20678 (defun org-copy-special ()
20679 "Copy region in table or copy current subtree.
20680 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20681 context. See the individual commands for more information."
20682 (interactive)
20683 (call-interactively
20684 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20686 (defun org-cut-special ()
20687 "Cut region in table or cut current subtree.
20688 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20689 context. See the individual commands for more information."
20690 (interactive)
20691 (call-interactively
20692 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20694 (defun org-paste-special (arg)
20695 "Paste rectangular region into table, or past subtree relative to level.
20696 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20697 See the individual commands for more information."
20698 (interactive "P")
20699 (if (org-at-table-p)
20700 (org-table-paste-rectangle)
20701 (org-paste-subtree arg)))
20703 (defun org-edit-special (&optional arg)
20704 "Call a special editor for the element at point.
20705 When at a table, call the formula editor with `org-table-edit-formulas'.
20706 When in a source code block, call `org-edit-src-code'.
20707 When in a fixed-width region, call `org-edit-fixed-width-region'.
20708 When in an export block, call `org-edit-export-block'.
20709 When in a LaTeX environment, call `org-edit-latex-environment'.
20710 When at an #+INCLUDE keyword, visit the included file.
20711 When at a footnote reference, call `org-edit-footnote-reference'
20712 On a link, call `ffap' to visit the link at point.
20713 Otherwise, return a user error."
20714 (interactive "P")
20715 (let ((element (org-element-at-point)))
20716 (barf-if-buffer-read-only)
20717 (pcase (org-element-type element)
20718 (`src-block
20719 (if (not arg) (org-edit-src-code)
20720 (let* ((info (org-babel-get-src-block-info))
20721 (lang (nth 0 info))
20722 (params (nth 2 info))
20723 (session (cdr (assq :session params))))
20724 (if (not session) (org-edit-src-code)
20725 ;; At a src-block with a session and function called with
20726 ;; an ARG: switch to the buffer related to the inferior
20727 ;; process.
20728 (switch-to-buffer
20729 (funcall (intern (concat "org-babel-prep-session:" lang))
20730 session params))))))
20731 (`keyword
20732 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20733 (org-open-link-from-string
20734 (format "[[%s]]"
20735 (expand-file-name
20736 (let ((value (org-element-property :value element)))
20737 (cond ((org-file-url-p value)
20738 (user-error "The file is specified as a URL, cannot be edited"))
20739 ((not (org-string-nw-p value))
20740 (user-error "No file to edit"))
20741 ((string-match "\\`\"\\(.*?\\)\"" value)
20742 (match-string 1 value))
20743 ((string-match "\\`[^ \t\"]\\S-*" value)
20744 (match-string 0 value))
20745 (t (user-error "No valid file specified")))))))
20746 (user-error "No special environment to edit here")))
20747 (`table
20748 (if (eq (org-element-property :type element) 'table.el)
20749 (org-edit-table.el)
20750 (call-interactively 'org-table-edit-formulas)))
20751 ;; Only Org tables contain `table-row' type elements.
20752 (`table-row (call-interactively 'org-table-edit-formulas))
20753 (`example-block (org-edit-src-code))
20754 (`export-block (org-edit-export-block))
20755 (`fixed-width (org-edit-fixed-width-region))
20756 (`latex-environment (org-edit-latex-environment))
20758 ;; No notable element at point. Though, we may be at a link or
20759 ;; a footnote reference, which are objects. Thus, scan deeper.
20760 (let ((context (org-element-context element)))
20761 (pcase (org-element-type context)
20762 (`footnote-reference (org-edit-footnote-reference))
20763 (`inline-src-block (org-edit-inline-src-code))
20764 (`link (call-interactively #'ffap))
20765 (_ (user-error "No special environment to edit here"))))))))
20767 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20768 (defun org-ctrl-c-ctrl-c (&optional arg)
20769 "Set tags in headline, or update according to changed information at point.
20771 This command does many different things, depending on context:
20773 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20774 this is what we do.
20776 - If the cursor is on a statistics cookie, update it.
20778 - If the cursor is in a headline, prompt for tags and insert them
20779 into the current line, aligned to `org-tags-column'. When called
20780 with prefix arg, realign all tags in the current buffer.
20782 - If the cursor is in one of the special #+KEYWORD lines, this
20783 triggers scanning the buffer for these lines and updating the
20784 information.
20786 - If the cursor is inside a table, realign the table. This command
20787 works even if the automatic table editor has been turned off.
20789 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20790 the entire table.
20792 - If the cursor is at a footnote reference or definition, jump to
20793 the corresponding definition or references, respectively.
20795 - If the cursor is a the beginning of a dynamic block, update it.
20797 - If the current buffer is a capture buffer, close note and file it.
20799 - If the cursor is on a <<<target>>>, update radio targets and
20800 corresponding links in this buffer.
20802 - If the cursor is on a numbered item in a plain list, renumber the
20803 ordered list.
20805 - If the cursor is on a checkbox, toggle it.
20807 - If the cursor is on a code block, evaluate it. The variable
20808 `org-confirm-babel-evaluate' can be used to control prompting
20809 before code block evaluation, by default every code block
20810 evaluation requires confirmation. Code block evaluation can be
20811 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20812 (interactive "P")
20813 (cond
20814 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20815 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20816 (org-remove-occur-highlights)
20817 (message "Temporary highlights/overlays removed from current buffer"))
20818 ((and (local-variable-p 'org-finish-function)
20819 (fboundp org-finish-function))
20820 (funcall org-finish-function))
20821 ((org-babel-hash-at-point))
20822 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20824 (let* ((context
20825 (org-element-lineage
20826 (org-element-context)
20827 ;; Limit to supported contexts.
20828 '(babel-call clock dynamic-block footnote-definition
20829 footnote-reference inline-babel-call inline-src-block
20830 inlinetask item keyword node-property paragraph
20831 plain-list property-drawer radio-target src-block
20832 statistics-cookie table table-cell table-row
20833 timestamp)
20835 (type (org-element-type context)))
20836 ;; For convenience: at the first line of a paragraph on the same
20837 ;; line as an item, apply function on that item instead.
20838 (when (eq type 'paragraph)
20839 (let ((parent (org-element-property :parent context)))
20840 (when (and (eq (org-element-type parent) 'item)
20841 (= (line-beginning-position)
20842 (org-element-property :begin parent)))
20843 (setq context parent)
20844 (setq type 'item))))
20845 ;; Act according to type of element or object at point.
20847 ;; Do nothing on a blank line, except if it is contained in
20848 ;; a src block. Hence, we first check if point is in such
20849 ;; a block and then if it is at a blank line.
20850 (pcase type
20851 ((or `inline-src-block `src-block)
20852 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20853 (org-babel-eval-wipe-error-buffer)
20854 (org-babel-execute-src-block
20855 current-prefix-arg (org-babel-get-src-block-info nil context))))
20856 ((guard (org-match-line "[ \t]*$"))
20857 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20858 (user-error
20859 (substitute-command-keys
20860 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20861 ((or `babel-call `inline-babel-call)
20862 (let ((info (org-babel-lob-get-info context)))
20863 (when info (org-babel-execute-src-block nil info))))
20864 (`clock (org-clock-update-time-maybe))
20865 (`dynamic-block
20866 (save-excursion
20867 (goto-char (org-element-property :post-affiliated context))
20868 (org-update-dblock)))
20869 (`footnote-definition
20870 (goto-char (org-element-property :post-affiliated context))
20871 (call-interactively 'org-footnote-action))
20872 (`footnote-reference (call-interactively #'org-footnote-action))
20873 ((or `headline `inlinetask)
20874 (save-excursion (goto-char (org-element-property :begin context))
20875 (call-interactively #'org-set-tags)))
20876 (`item
20877 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20878 ;; unconditionally, whereas `C-u' will toggle its presence.
20879 ;; Without a universal argument, if the item has a checkbox,
20880 ;; toggle it. Otherwise repair the list.
20881 (let* ((box (org-element-property :checkbox context))
20882 (struct (org-element-property :structure context))
20883 (old-struct (copy-tree struct))
20884 (parents (org-list-parents-alist struct))
20885 (prevs (org-list-prevs-alist struct))
20886 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20887 (org-list-set-checkbox
20888 (org-element-property :begin context) struct
20889 (cond ((equal arg '(16)) "[-]")
20890 ((and (not box) (equal arg '(4))) "[ ]")
20891 ((or (not box) (equal arg '(4))) nil)
20892 ((eq box 'on) "[ ]")
20893 (t "[X]")))
20894 ;; Mimic `org-list-write-struct' but with grabbing a return
20895 ;; value from `org-list-struct-fix-box'.
20896 (org-list-struct-fix-ind struct parents 2)
20897 (org-list-struct-fix-item-end struct)
20898 (org-list-struct-fix-bul struct prevs)
20899 (org-list-struct-fix-ind struct parents)
20900 (let ((block-item
20901 (org-list-struct-fix-box struct parents prevs orderedp)))
20902 (if (and box (equal struct old-struct))
20903 (if (equal arg '(16))
20904 (message "Checkboxes already reset")
20905 (user-error "Cannot toggle this checkbox: %s"
20906 (if (eq box 'on)
20907 "all subitems checked"
20908 "unchecked subitems")))
20909 (org-list-struct-apply-struct struct old-struct)
20910 (org-update-checkbox-count-maybe))
20911 (when block-item
20912 (message "Checkboxes were removed due to empty box at line %d"
20913 (org-current-line block-item))))))
20914 (`keyword
20915 (let ((org-inhibit-startup-visibility-stuff t)
20916 (org-startup-align-all-tables nil))
20917 (when (boundp 'org-table-coordinate-overlays)
20918 (mapc #'delete-overlay org-table-coordinate-overlays)
20919 (setq org-table-coordinate-overlays nil))
20920 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20921 (message "Local setup has been refreshed"))
20922 (`plain-list
20923 ;; At a plain list, with a double C-u argument, set
20924 ;; checkboxes of each item to "[-]", whereas a single one
20925 ;; will toggle their presence according to the state of the
20926 ;; first item in the list. Without an argument, repair the
20927 ;; list.
20928 (let* ((begin (org-element-property :contents-begin context))
20929 (beginm (move-marker (make-marker) begin))
20930 (struct (org-element-property :structure context))
20931 (old-struct (copy-tree struct))
20932 (first-box (save-excursion
20933 (goto-char begin)
20934 (looking-at org-list-full-item-re)
20935 (match-string-no-properties 3)))
20936 (new-box (cond ((equal arg '(16)) "[-]")
20937 ((equal arg '(4)) (unless first-box "[ ]"))
20938 ((equal first-box "[X]") "[ ]")
20939 (t "[X]"))))
20940 (cond
20941 (arg
20942 (dolist (pos
20943 (org-list-get-all-items
20944 begin struct (org-list-prevs-alist struct)))
20945 (org-list-set-checkbox pos struct new-box)))
20946 ((and first-box (eq (point) begin))
20947 ;; For convenience, when point is at bol on the first
20948 ;; item of the list and no argument is provided, simply
20949 ;; toggle checkbox of that item, if any.
20950 (org-list-set-checkbox begin struct new-box)))
20951 (org-list-write-struct
20952 struct (org-list-parents-alist struct) old-struct)
20953 (org-update-checkbox-count-maybe)
20954 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20955 ((or `property-drawer `node-property)
20956 (call-interactively #'org-property-action))
20957 (`radio-target
20958 (call-interactively #'org-update-radio-target-regexp))
20959 (`statistics-cookie
20960 (call-interactively #'org-update-statistics-cookies))
20961 ((or `table `table-cell `table-row)
20962 ;; At a table, recalculate every field and align it. Also
20963 ;; send the table if necessary. If the table has
20964 ;; a `table.el' type, just give up. At a table row or cell,
20965 ;; maybe recalculate line but always align table.
20966 (if (eq (org-element-property :type context) 'table.el)
20967 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20968 Use `\\[org-edit-special]' to edit table.el tables"))
20969 (let ((org-enable-table-editor t))
20970 (if (or (eq type 'table)
20971 ;; Check if point is at a TBLFM line.
20972 (and (eq type 'table-row)
20973 (= (point) (org-element-property :end context))))
20974 (save-excursion
20975 (if (org-at-TBLFM-p)
20976 (progn (require 'org-table)
20977 (org-table-calc-current-TBLFM))
20978 (goto-char (org-element-property :contents-begin context))
20979 (org-call-with-arg 'org-table-recalculate (or arg t))
20980 (orgtbl-send-table 'maybe)))
20981 (org-table-maybe-eval-formula)
20982 (cond (arg (call-interactively #'org-table-recalculate))
20983 ((org-table-maybe-recalculate-line))
20984 (t (org-table-align)))))))
20985 (`timestamp (org-timestamp-change 0 'day))
20986 ((and `nil (guard (org-at-heading-p)))
20987 ;; When point is on an unsupported object type, we can miss
20988 ;; the fact that it also is at a heading. Handle it here.
20989 (call-interactively #'org-set-tags))
20990 ((guard
20991 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20993 (user-error
20994 (substitute-command-keys
20995 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20997 (defun org-mode-restart ()
20998 (interactive)
20999 (let ((indent-status (bound-and-true-p org-indent-mode)))
21000 (funcall major-mode)
21001 (hack-local-variables)
21002 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21003 (org-indent-mode -1))
21004 (org-reset-file-cache))
21005 (message "%s restarted" major-mode))
21007 (defun org-kill-note-or-show-branches ()
21008 "Abort storing current note, or call `outline-show-branches'."
21009 (interactive)
21010 (if (not org-finish-function)
21011 (progn
21012 (outline-hide-subtree)
21013 (call-interactively 'outline-show-branches))
21014 (let ((org-note-abort t))
21015 (funcall org-finish-function))))
21017 (defun org-delete-indentation (&optional arg)
21018 "Join current line to previous and fix whitespace at join.
21020 If previous line is a headline add to headline title. Otherwise
21021 the function calls `delete-indentation'.
21023 With a non-nil optional argument, join it to the following one."
21024 (interactive "*P")
21025 (if (save-excursion
21026 (beginning-of-line (if arg 1 0))
21027 (let ((case-fold-search nil))
21028 (looking-at org-complex-heading-regexp)))
21029 ;; At headline.
21030 (let ((tags-column (when (match-beginning 5)
21031 (save-excursion (goto-char (match-beginning 5))
21032 (current-column))))
21033 (string (concat " " (progn (when arg (forward-line 1))
21034 (org-trim (delete-and-extract-region
21035 (line-beginning-position)
21036 (line-end-position)))))))
21037 (unless (bobp) (delete-region (point) (1- (point))))
21038 (goto-char (or (match-end 4)
21039 (match-beginning 5)
21040 (match-end 0)))
21041 (skip-chars-backward " \t")
21042 (save-excursion (insert string))
21043 ;; Adjust alignment of tags.
21044 (cond
21045 ((not tags-column)) ;no tags
21046 (org-auto-align-tags (org-set-tags nil t))
21047 (t (org--align-tags-here tags-column)))) ;preserve tags column
21048 (delete-indentation arg)))
21050 (defun org-open-line (n)
21051 "Insert a new row in tables, call `open-line' elsewhere.
21052 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21053 As a special case, when a document starts with a table, allow to
21054 call `open-line' on the very first character."
21055 (interactive "*p")
21056 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21057 (org-table-insert-row)
21058 (open-line n)))
21060 (defun org-return (&optional indent)
21061 "Goto next table row or insert a newline.
21063 Calls `org-table-next-row' or `newline', depending on context.
21065 When optional INDENT argument is non-nil, call
21066 `newline-and-indent' instead of `newline'.
21068 When `org-return-follows-link' is non-nil and point is on
21069 a timestamp or a link, call `org-open-at-point'. However, it
21070 will not happen if point is in a table or on a \"dead\"
21071 object (e.g., within a comment). In these case, you need to use
21072 `org-open-at-point' directly."
21073 (interactive)
21074 (let ((context (if org-return-follows-link (org-element-context)
21075 (org-element-at-point))))
21076 (cond
21077 ;; In a table, call `org-table-next-row'.
21078 ((or (and (eq (org-element-type context) 'table)
21079 (>= (point) (org-element-property :contents-begin context))
21080 (< (point) (org-element-property :contents-end context)))
21081 (org-element-lineage context '(table-row table-cell) t))
21082 (org-table-justify-field-maybe)
21083 (call-interactively #'org-table-next-row))
21084 ;; On a link or a timestamp, call `org-open-at-point' if
21085 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21086 ;; locations, e.g., in a comment, as `org-open-at-point'.
21087 ((and org-return-follows-link
21088 (or (org-in-regexp org-ts-regexp-both nil t)
21089 (org-in-regexp org-tsr-regexp-both nil t)
21090 (org-in-regexp org-any-link-re nil t)))
21091 (call-interactively #'org-open-at-point))
21092 ;; Insert newline in heading, but preserve tags.
21093 ((and (not (bolp))
21094 (save-excursion (beginning-of-line)
21095 (let ((case-fold-search nil))
21096 (looking-at org-complex-heading-regexp))))
21097 ;; At headline. Split line. However, if point is on keyword,
21098 ;; priority cookie or tags, do not break any of them: add
21099 ;; a newline after the headline instead.
21100 (let ((tags-column (and (match-beginning 5)
21101 (save-excursion (goto-char (match-beginning 5))
21102 (current-column))))
21103 (string
21104 (when (and (match-end 4) (org-point-in-group (point) 4))
21105 (delete-and-extract-region (point) (match-end 4)))))
21106 ;; Adjust tag alignment.
21107 (cond
21108 ((not (and tags-column string)))
21109 (org-auto-align-tags (org-set-tags nil t))
21110 (t (org--align-tags-here tags-column))) ;preserve tags column
21111 (end-of-line)
21112 (org-show-entry)
21113 (if indent (newline-and-indent) (newline))
21114 (when string (save-excursion (insert (org-trim string))))))
21115 ;; In a list, make sure indenting keeps trailing text within.
21116 ((and indent
21117 (not (eolp))
21118 (org-element-lineage context '(item)))
21119 (let ((trailing-data
21120 (delete-and-extract-region (point) (line-end-position))))
21121 (newline-and-indent)
21122 (save-excursion (insert trailing-data))))
21123 (t (if indent (newline-and-indent) (newline))))))
21125 (defun org-return-indent ()
21126 "Goto next table row or insert a newline and indent.
21127 Calls `org-table-next-row' or `newline-and-indent', depending on
21128 context. See the individual commands for more information."
21129 (interactive)
21130 (org-return t))
21132 (defun org-ctrl-c-star ()
21133 "Compute table, or change heading status of lines.
21134 Calls `org-table-recalculate' or `org-toggle-heading',
21135 depending on context."
21136 (interactive)
21137 (cond
21138 ((org-at-table-p)
21139 (call-interactively 'org-table-recalculate))
21141 ;; Convert all lines in region to list items
21142 (call-interactively 'org-toggle-heading))))
21144 (defun org-ctrl-c-minus ()
21145 "Insert separator line in table or modify bullet status of line.
21146 Also turns a plain line or a region of lines into list items.
21147 Calls `org-table-insert-hline', `org-toggle-item', or
21148 `org-cycle-list-bullet', depending on context."
21149 (interactive)
21150 (cond
21151 ((org-at-table-p)
21152 (call-interactively 'org-table-insert-hline))
21153 ((org-region-active-p)
21154 (call-interactively 'org-toggle-item))
21155 ((org-in-item-p)
21156 (call-interactively 'org-cycle-list-bullet))
21158 (call-interactively 'org-toggle-item))))
21160 (defun org-toggle-heading (&optional nstars)
21161 "Convert headings to normal text, or items or text to headings.
21162 If there is no active region, only convert the current line.
21164 With a `\\[universal-argument]' prefix, convert the whole list at
21165 point into heading.
21167 In a region:
21169 - If the first non blank line is a headline, remove the stars
21170 from all headlines in the region.
21172 - If it is a normal line, turn each and every normal line (i.e.,
21173 not an heading or an item) in the region into headings. If you
21174 want to convert only the first line of this region, use one
21175 universal prefix argument.
21177 - If it is a plain list item, turn all plain list items into headings.
21179 When converting a line into a heading, the number of stars is chosen
21180 such that the lines become children of the current entry. However,
21181 when a numeric prefix argument is given, its value determines the
21182 number of stars to add."
21183 (interactive "P")
21184 (let ((skip-blanks
21185 (function
21186 ;; Return beginning of first non-blank line, starting from
21187 ;; line at POS.
21188 (lambda (pos)
21189 (save-excursion
21190 (goto-char pos)
21191 (while (org-at-comment-p) (forward-line))
21192 (skip-chars-forward " \r\t\n")
21193 (point-at-bol)))))
21194 beg end toggled)
21195 ;; Determine boundaries of changes. If a universal prefix has
21196 ;; been given, put the list in a region. If region ends at a bol,
21197 ;; do not consider the last line to be in the region.
21199 (when (and current-prefix-arg (org-at-item-p))
21200 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21201 (org-mark-element))
21203 (if (org-region-active-p)
21204 (setq beg (funcall skip-blanks (region-beginning))
21205 end (copy-marker (save-excursion
21206 (goto-char (region-end))
21207 (if (bolp) (point) (point-at-eol)))))
21208 (setq beg (funcall skip-blanks (point-at-bol))
21209 end (copy-marker (point-at-eol))))
21210 ;; Ensure inline tasks don't count as headings.
21211 (org-with-limited-levels
21212 (save-excursion
21213 (goto-char beg)
21214 (cond
21215 ;; Case 1. Started at an heading: de-star headings.
21216 ((org-at-heading-p)
21217 (while (< (point) end)
21218 (when (org-at-heading-p t)
21219 (looking-at org-outline-regexp) (replace-match "")
21220 (setq toggled t))
21221 (forward-line)))
21222 ;; Case 2. Started at an item: change items into headlines.
21223 ;; One star will be added by `org-list-to-subtree'.
21224 ((org-at-item-p)
21225 (while (< (point) end)
21226 (when (org-at-item-p)
21227 ;; Pay attention to cases when region ends before list.
21228 (let* ((struct (org-list-struct))
21229 (list-end
21230 (min (org-list-get-bottom-point struct) (1+ end))))
21231 (save-restriction
21232 (narrow-to-region (point) list-end)
21233 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21234 (setq toggled t))
21235 (forward-line)))
21236 ;; Case 3. Started at normal text: make every line an heading,
21237 ;; skipping headlines and items.
21238 (t (let* ((stars
21239 (make-string
21240 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21241 (add-stars
21242 (cond (nstars "") ; stars from prefix only
21243 ((equal stars "") "*") ; before first heading
21244 (org-odd-levels-only "**") ; inside heading, odd
21245 (t "*"))) ; inside heading, oddeven
21246 (rpl (concat stars add-stars " "))
21247 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21248 (while (< (point) (if (equal nstars '(4)) lend end))
21249 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21250 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21251 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21252 (forward-line)))))))
21253 (unless toggled (message "Cannot toggle heading from here"))))
21255 (defun org-meta-return (&optional arg)
21256 "Insert a new heading or wrap a region in a table.
21257 Calls `org-insert-heading', `org-insert-item' or
21258 `org-table-wrap-region', depending on context. When called with
21259 an argument, unconditionally call `org-insert-heading'."
21260 (interactive "P")
21261 (org-check-before-invisible-edit 'insert)
21262 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21263 (call-interactively (cond (arg #'org-insert-heading)
21264 ((org-at-table-p) #'org-table-wrap-region)
21265 ((org-in-item-p) #'org-insert-item)
21266 (t #'org-insert-heading)))))
21268 ;;; Menu entries
21270 (defsubst org-in-subtree-not-table-p ()
21271 "Are we in a subtree and not in a table?"
21272 (and (not (org-before-first-heading-p))
21273 (not (org-at-table-p))))
21275 ;; Define the Org mode menus
21276 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21277 '("Tbl"
21278 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21279 ["Next Field" org-cycle (org-at-table-p)]
21280 ["Previous Field" org-shifttab (org-at-table-p)]
21281 ["Next Row" org-return (org-at-table-p)]
21282 "--"
21283 ["Blank Field" org-table-blank-field (org-at-table-p)]
21284 ["Edit Field" org-table-edit-field (org-at-table-p)]
21285 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21286 "--"
21287 ("Column"
21288 ["Move Column Left" org-metaleft (org-at-table-p)]
21289 ["Move Column Right" org-metaright (org-at-table-p)]
21290 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21291 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21292 ("Row"
21293 ["Move Row Up" org-metaup (org-at-table-p)]
21294 ["Move Row Down" org-metadown (org-at-table-p)]
21295 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21296 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21297 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21298 "--"
21299 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21300 ("Rectangle"
21301 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21302 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21303 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21304 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21305 "--"
21306 ("Calculate"
21307 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21308 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21309 ["Edit Formulas" org-edit-special (org-at-table-p)]
21310 "--"
21311 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21312 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21313 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21314 "--"
21315 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21316 "--"
21317 ["Sum Column/Rectangle" org-table-sum
21318 (or (org-at-table-p) (org-region-active-p))]
21319 ["Which Column?" org-table-current-column (org-at-table-p)])
21320 ["Debug Formulas"
21321 org-table-toggle-formula-debugger
21322 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21323 ["Show Col/Row Numbers"
21324 org-table-toggle-coordinate-overlays
21325 :style toggle
21326 :selected (bound-and-true-p org-table-overlay-coordinates)]
21327 "--"
21328 ["Create" org-table-create (and (not (org-at-table-p))
21329 org-enable-table-editor)]
21330 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21331 ["Import from File" org-table-import (not (org-at-table-p))]
21332 ["Export to File" org-table-export (org-at-table-p)]
21333 "--"
21334 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21335 "--"
21336 ("Plot"
21337 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21338 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21340 (easy-menu-define org-org-menu org-mode-map "Org menu"
21341 '("Org"
21342 ("Show/Hide"
21343 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21344 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21345 ["Sparse Tree..." org-sparse-tree t]
21346 ["Reveal Context" org-reveal t]
21347 ["Show All" outline-show-all t]
21348 "--"
21349 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21350 "--"
21351 ["New Heading" org-insert-heading t]
21352 ("Navigate Headings"
21353 ["Up" outline-up-heading t]
21354 ["Next" outline-next-visible-heading t]
21355 ["Previous" outline-previous-visible-heading t]
21356 ["Next Same Level" outline-forward-same-level t]
21357 ["Previous Same Level" outline-backward-same-level t]
21358 "--"
21359 ["Jump" org-goto t])
21360 ("Edit Structure"
21361 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21362 "--"
21363 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21364 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21365 "--"
21366 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21367 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21368 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21369 "--"
21370 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21371 "--"
21372 ["Copy visible text" org-copy-visible t]
21373 "--"
21374 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21375 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21376 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21377 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21378 "--"
21379 ["Sort Region/Children" org-sort t]
21380 "--"
21381 ["Convert to odd levels" org-convert-to-odd-levels t]
21382 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21383 ("Editing"
21384 ["Emphasis..." org-emphasize t]
21385 ["Edit Source Example" org-edit-special t]
21386 "--"
21387 ["Footnote new/jump" org-footnote-action t]
21388 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21389 ("Archive"
21390 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21391 "--"
21392 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21393 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21394 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21396 "--"
21397 ("Hyperlinks"
21398 ["Store Link (Global)" org-store-link t]
21399 ["Find existing link to here" org-occur-link-in-agenda-files t]
21400 ["Insert Link" org-insert-link t]
21401 ["Follow Link" org-open-at-point t]
21402 "--"
21403 ["Next link" org-next-link t]
21404 ["Previous link" org-previous-link t]
21405 "--"
21406 ["Descriptive Links"
21407 org-toggle-link-display
21408 :style radio
21409 :selected org-descriptive-links
21411 ["Literal Links"
21412 org-toggle-link-display
21413 :style radio
21414 :selected (not org-descriptive-links)])
21415 "--"
21416 ("TODO Lists"
21417 ["TODO/DONE/-" org-todo t]
21418 ("Select keyword"
21419 ["Next keyword" org-shiftright (org-at-heading-p)]
21420 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21421 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21422 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21423 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21424 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21425 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21426 "--"
21427 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21428 :selected org-enforce-todo-dependencies :style toggle :active t]
21429 "Settings for tree at point"
21430 ["Do Children sequentially" org-toggle-ordered-property :style radio
21431 :selected (org-entry-get nil "ORDERED")
21432 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21433 ["Do Children parallel" org-toggle-ordered-property :style radio
21434 :selected (not (org-entry-get nil "ORDERED"))
21435 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21436 "--"
21437 ["Set Priority" org-priority t]
21438 ["Priority Up" org-shiftup t]
21439 ["Priority Down" org-shiftdown t]
21440 "--"
21441 ["Get news from all feeds" org-feed-update-all t]
21442 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21443 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21444 ("TAGS and Properties"
21445 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21446 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21447 "--"
21448 ["Set property" org-set-property (not (org-before-first-heading-p))]
21449 ["Column view of properties" org-columns t]
21450 ["Insert Column View DBlock" org-columns-insert-dblock t])
21451 ("Dates and Scheduling"
21452 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21453 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21454 ("Change Date"
21455 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21456 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21457 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21458 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21459 ["Compute Time Range" org-evaluate-time-range t]
21460 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21461 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21462 "--"
21463 ["Custom time format" org-toggle-time-stamp-overlays
21464 :style radio :selected org-display-custom-times]
21465 "--"
21466 ["Goto Calendar" org-goto-calendar t]
21467 ["Date from Calendar" org-date-from-calendar t]
21468 "--"
21469 ["Start/Restart Timer" org-timer-start t]
21470 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21471 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21472 ["Insert Timer String" org-timer t]
21473 ["Insert Timer Item" org-timer-item t])
21474 ("Logging work"
21475 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21476 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21477 ["Clock out" org-clock-out t]
21478 ["Clock cancel" org-clock-cancel t]
21479 "--"
21480 ["Mark as default task" org-clock-mark-default-task t]
21481 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21482 ["Goto running clock" org-clock-goto t]
21483 "--"
21484 ["Display times" org-clock-display t]
21485 ["Create clock table" org-clock-report t]
21486 "--"
21487 ["Record DONE time"
21488 (progn (setq org-log-done (not org-log-done))
21489 (message "Switching to %s will %s record a timestamp"
21490 (car org-done-keywords)
21491 (if org-log-done "automatically" "not")))
21492 :style toggle :selected org-log-done])
21493 "--"
21494 ["Agenda Command..." org-agenda t]
21495 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21496 ("File List for Agenda")
21497 ("Special views current file"
21498 ["TODO Tree" org-show-todo-tree t]
21499 ["Check Deadlines" org-check-deadlines t]
21500 ["Tags/Property tree" org-match-sparse-tree t])
21501 "--"
21502 ["Export/Publish..." org-export-dispatch t]
21503 ("LaTeX"
21504 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21505 :selected org-cdlatex-mode]
21506 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21507 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21508 ["Modify math symbol" org-cdlatex-math-modify
21509 (org-inside-LaTeX-fragment-p)]
21510 ["Insert citation" org-reftex-citation t])
21511 "--"
21512 ("MobileOrg"
21513 ["Push Files and Views" org-mobile-push t]
21514 ["Get Captured and Flagged" org-mobile-pull t]
21515 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21516 "--"
21517 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21518 "--"
21519 ("Documentation"
21520 ["Show Version" org-version t]
21521 ["Info Documentation" org-info t])
21522 ("Customize"
21523 ["Browse Org Group" org-customize t]
21524 "--"
21525 ["Expand This Menu" org-create-customize-menu
21526 (fboundp 'customize-menu-create)])
21527 ["Send bug report" org-submit-bug-report t]
21528 "--"
21529 ("Refresh/Reload"
21530 ["Refresh setup current buffer" org-mode-restart t]
21531 ["Reload Org (after update)" org-reload t]
21532 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21535 (defun org-info (&optional node)
21536 "Read documentation for Org in the info system.
21537 With optional NODE, go directly to that node."
21538 (interactive)
21539 (info (format "(org)%s" (or node ""))))
21541 ;;;###autoload
21542 (defun org-submit-bug-report ()
21543 "Submit a bug report on Org via mail.
21545 Don't hesitate to report any problems or inaccurate documentation.
21547 If you don't have setup sending mail from (X)Emacs, please copy the
21548 output buffer into your mail program, as it gives us important
21549 information about your Org version and configuration."
21550 (interactive)
21551 (require 'reporter)
21552 (defvar reporter-prompt-for-summary-p)
21553 (org-load-modules-maybe)
21554 (org-require-autoloaded-modules)
21555 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21556 (reporter-submit-bug-report
21557 "emacs-orgmode@gnu.org"
21558 (org-version nil 'full)
21559 (let (list)
21560 (save-window-excursion
21561 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21562 (delete-other-windows)
21563 (erase-buffer)
21564 (insert "You are about to submit a bug report to the Org mailing list.
21566 We would like to add your full Org and Outline configuration to the
21567 bug report. This greatly simplifies the work of the maintainer and
21568 other experts on the mailing list.
21570 HOWEVER, some variables you have customized may contain private
21571 information. The names of customers, colleagues, or friends, might
21572 appear in the form of file names, tags, todo states, or search strings.
21573 If you answer yes to the prompt, you might want to check and remove
21574 such private information before sending the email.")
21575 (add-text-properties (point-min) (point-max) '(face org-warning))
21576 (when (yes-or-no-p "Include your Org configuration ")
21577 (mapatoms
21578 (lambda (v)
21579 (and (boundp v)
21580 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21581 (or (and (symbol-value v)
21582 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21583 (and
21584 (get v 'custom-type) (get v 'standard-value)
21585 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21586 (push v list)))))
21587 (kill-buffer (get-buffer "*Warn about privacy*"))
21588 list))
21589 nil nil
21590 "Remember to cover the basics, that is, what you expected to happen and
21591 what in fact did happen. You don't know how to make a good report? See
21593 http://orgmode.org/manual/Feedback.html#Feedback
21595 Your bug report will be posted to the Org mailing list.
21596 ------------------------------------------------------------------------")
21597 (save-excursion
21598 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21599 (replace-match "\\1Bug: \\3 [\\2]")))))
21602 (defun org-install-agenda-files-menu ()
21603 (let ((bl (buffer-list)))
21604 (save-excursion
21605 (while bl
21606 (set-buffer (pop bl))
21607 (when (derived-mode-p 'org-mode) (setq bl nil)))
21608 (when (derived-mode-p 'org-mode)
21609 (easy-menu-change
21610 '("Org") "File List for Agenda"
21611 (append
21612 (list
21613 ["Edit File List" (org-edit-agenda-file-list) t]
21614 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21615 ["Remove Current File from List" org-remove-file t]
21616 ["Cycle through agenda files" org-cycle-agenda-files t]
21617 ["Occur in all agenda files" org-occur-in-agenda-files t]
21618 "--")
21619 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21621 ;;;; Documentation
21623 (defun org-require-autoloaded-modules ()
21624 (interactive)
21625 (mapc #'require
21626 '(org-agenda org-archive org-attach org-clock org-colview org-id
21627 org-table org-timer)))
21629 ;;;###autoload
21630 (defun org-reload (&optional uncompiled)
21631 "Reload all org lisp files.
21632 With prefix arg UNCOMPILED, load the uncompiled versions."
21633 (interactive "P")
21634 (require 'loadhist)
21635 (let* ((org-dir (org-find-library-dir "org"))
21636 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21637 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21638 (remove-re (format "\\`%s\\'"
21639 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21640 (feats (delete-dups
21641 (mapcar 'file-name-sans-extension
21642 (mapcar 'file-name-nondirectory
21643 (delq nil
21644 (mapcar 'feature-file
21645 features))))))
21646 (lfeat (append
21647 (sort
21648 (setq feats
21649 (delq nil (mapcar
21650 (lambda (f)
21651 (if (and (string-match feature-re f)
21652 (not (string-match remove-re f)))
21653 f nil))
21654 feats)))
21655 'string-lessp)
21656 (list "org-version" "org")))
21657 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21658 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21659 load-uncore load-misses)
21660 (setq load-misses
21661 (delq 't
21662 (mapcar (lambda (f)
21663 (or (org-load-noerror-mustsuffix (concat org-dir f))
21664 (and (string= org-dir contrib-dir)
21665 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21666 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21667 (add-to-list 'load-uncore f 'append)
21670 lfeat)))
21671 (when load-uncore
21672 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21673 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21674 (if load-misses
21675 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21676 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21677 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21679 ;;;###autoload
21680 (defun org-customize ()
21681 "Call the customize function with org as argument."
21682 (interactive)
21683 (org-load-modules-maybe)
21684 (org-require-autoloaded-modules)
21685 (customize-browse 'org))
21687 (defun org-create-customize-menu ()
21688 "Create a full customization menu for Org mode, insert it into the menu."
21689 (interactive)
21690 (org-load-modules-maybe)
21691 (org-require-autoloaded-modules)
21692 (if (fboundp 'customize-menu-create)
21693 (progn
21694 (easy-menu-change
21695 '("Org") "Customize"
21696 `(["Browse Org group" org-customize t]
21697 "--"
21698 ,(customize-menu-create 'org)
21699 ["Set" Custom-set t]
21700 ["Save" Custom-save t]
21701 ["Reset to Current" Custom-reset-current t]
21702 ["Reset to Saved" Custom-reset-saved t]
21703 ["Reset to Standard Settings" Custom-reset-standard t]))
21704 (message "\"Org\"-menu now contains full customization menu"))
21705 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21707 ;;;; Miscellaneous stuff
21709 ;;; Generally useful functions
21711 (defun org-get-at-eol (property n)
21712 "Get text property PROPERTY at the end of line less N characters."
21713 (get-text-property (- (point-at-eol) n) property))
21715 (defun org-find-text-property-in-string (prop s)
21716 "Return the first non-nil value of property PROP in string S."
21717 (or (get-text-property 0 prop s)
21718 (get-text-property (or (next-single-property-change 0 prop s) 0)
21719 prop s)))
21721 (defun org-display-warning (message)
21722 "Display the given MESSAGE as a warning."
21723 (display-warning 'org message :warning))
21725 (defun org-eval (form)
21726 "Eval FORM and return result."
21727 (condition-case error
21728 (eval form)
21729 (error (format "%%![Error: %s]" error))))
21731 (defun org-in-clocktable-p ()
21732 "Check if the cursor is in a clocktable."
21733 (let ((pos (point)) start)
21734 (save-excursion
21735 (end-of-line 1)
21736 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21737 (setq start (match-beginning 0))
21738 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21739 (>= (match-end 0) pos)
21740 start))))
21742 (defun org-in-verbatim-emphasis ()
21743 (save-match-data
21744 (and (org-in-regexp org-verbatim-re 2)
21745 (>= (point) (match-beginning 3))
21746 (<= (point) (match-end 4)))))
21748 (defun org-overlay-display (ovl text &optional face evap)
21749 "Make overlay OVL display TEXT with face FACE."
21750 (overlay-put ovl 'display text)
21751 (if face (overlay-put ovl 'face face))
21752 (if evap (overlay-put ovl 'evaporate t)))
21754 (defun org-overlay-before-string (ovl text &optional face evap)
21755 "Make overlay OVL display TEXT with face FACE."
21756 (if face (org-add-props text nil 'face face))
21757 (overlay-put ovl 'before-string text)
21758 (if evap (overlay-put ovl 'evaporate t)))
21760 (defun org-find-overlays (prop &optional pos delete)
21761 "Find all overlays specifying PROP at POS or point.
21762 If DELETE is non-nil, delete all those overlays."
21763 (let (found)
21764 (dolist (ov (overlays-at (or pos (point))) found)
21765 (cond ((not (overlay-get ov prop)))
21766 (delete (delete-overlay ov))
21767 (t (push ov found))))))
21769 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21770 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21771 (if (and marker (marker-buffer marker)
21772 (buffer-live-p (marker-buffer marker)))
21773 (progn
21774 (pop-to-buffer-same-window (marker-buffer marker))
21775 (when (or (> marker (point-max)) (< marker (point-min)))
21776 (widen))
21777 (goto-char marker)
21778 (org-show-context 'org-goto))
21779 (if bookmark
21780 (bookmark-jump bookmark)
21781 (error "Cannot find location"))))
21783 (defun org-quote-csv-field (s)
21784 "Quote field for inclusion in CSV material."
21785 (if (string-match "[\",]" s)
21786 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21789 (defun org-force-self-insert (N)
21790 "Needed to enforce self-insert under remapping."
21791 (interactive "p")
21792 (self-insert-command N))
21794 (defun org-string-width (s)
21795 "Compute width of string, ignoring invisible characters.
21796 This ignores character with invisibility property `org-link', and also
21797 characters with property `org-cwidth', because these will become invisible
21798 upon the next fontification round."
21799 (let (b l)
21800 (when (or (eq t buffer-invisibility-spec)
21801 (assq 'org-link buffer-invisibility-spec))
21802 (while (setq b (text-property-any 0 (length s)
21803 'invisible 'org-link s))
21804 (setq s (concat (substring s 0 b)
21805 (substring s (or (next-single-property-change
21806 b 'invisible s)
21807 (length s)))))))
21808 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21809 (setq s (concat (substring s 0 b)
21810 (substring s (or (next-single-property-change
21811 b 'org-cwidth s)
21812 (length s))))))
21813 (setq l (string-width s) b -1)
21814 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21815 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21818 (defun org-shorten-string (s maxlength)
21819 "Shorten string S so that it is no longer than MAXLENGTH characters.
21820 If the string is shorter or has length MAXLENGTH, just return the
21821 original string. If it is longer, the functions finds a space in the
21822 string, breaks this string off at that locations and adds three dots
21823 as ellipsis. Including the ellipsis, the string will not be longer
21824 than MAXLENGTH. If finding a good breaking point in the string does
21825 not work, the string is just chopped off in the middle of a word
21826 if necessary."
21827 (if (<= (length s) maxlength)
21829 (let* ((n (max (- maxlength 4) 1))
21830 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21831 (if (string-match re s)
21832 (concat (match-string 1 s) "...")
21833 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21835 (defun org-get-indentation (&optional line)
21836 "Get the indentation of the current line, interpreting tabs.
21837 When LINE is given, assume it represents a line and compute its indentation."
21838 (if line
21839 (when (string-match "^ *" (org-remove-tabs line))
21840 (match-end 0))
21841 (save-excursion
21842 (beginning-of-line 1)
21843 (skip-chars-forward " \t")
21844 (current-column))))
21846 (defun org-get-string-indentation (s)
21847 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21848 (let ((n -1) (i 0) (w tab-width) c)
21849 (catch 'exit
21850 (while (< (setq n (1+ n)) (length s))
21851 (setq c (aref s n))
21852 (cond ((= c ?\ ) (setq i (1+ i)))
21853 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21854 (t (throw 'exit t)))))
21857 (defun org-remove-tabs (s &optional width)
21858 "Replace tabulators in S with spaces.
21859 Assumes that s is a single line, starting in column 0."
21860 (setq width (or width tab-width))
21861 (while (string-match "\t" s)
21862 (setq s (replace-match
21863 (make-string
21864 (- (* width (/ (+ (match-beginning 0) width) width))
21865 (match-beginning 0)) ?\ )
21866 t t s)))
21869 (defun org-fix-indentation (line ind)
21870 "Fix indentation in LINE.
21871 IND is a cons cell with target and minimum indentation.
21872 If the current indentation in LINE is smaller than the minimum,
21873 leave it alone. If it is larger than ind, set it to the target."
21874 (let* ((l (org-remove-tabs line))
21875 (i (org-get-indentation l))
21876 (i1 (car ind)) (i2 (cdr ind)))
21877 (when (>= i i2) (setq l (substring line i2)))
21878 (if (> i1 0)
21879 (concat (make-string i1 ?\ ) l)
21880 l)))
21882 (defun org-remove-indentation (code &optional n)
21883 "Remove maximum common indentation in string CODE and return it.
21884 N may optionally be the number of columns to remove. Return CODE
21885 as-is if removal failed."
21886 (with-temp-buffer
21887 (insert code)
21888 (if (org-do-remove-indentation n) (buffer-string) code)))
21890 (defun org-do-remove-indentation (&optional n)
21891 "Remove the maximum common indentation from the buffer.
21892 When optional argument N is a positive integer, remove exactly
21893 that much characters from indentation, if possible. Return nil
21894 if it fails."
21895 (catch :exit
21896 (goto-char (point-min))
21897 ;; Find maximum common indentation, if not specified.
21898 (let ((n (or n
21899 (let ((min-ind (point-max)))
21900 (save-excursion
21901 (while (re-search-forward "^[ \t]*\\S-" nil t)
21902 (let ((ind (1- (current-column))))
21903 (if (zerop ind) (throw :exit nil)
21904 (setq min-ind (min min-ind ind))))))
21905 min-ind))))
21906 (if (zerop n) (throw :exit nil)
21907 ;; Remove exactly N indentation, but give up if not possible.
21908 (while (not (eobp))
21909 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21910 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21911 ((< ind n) (throw :exit nil))
21912 (t (indent-line-to (- ind n))))
21913 (forward-line)))
21914 ;; Signal success.
21915 t))))
21917 (defun org-fill-template (template alist)
21918 "Find each %key of ALIST in TEMPLATE and replace it."
21919 (let ((case-fold-search nil))
21920 (dolist (entry (sort (copy-sequence alist)
21921 (lambda (a b) (< (length (car a)) (length (car b))))))
21922 (setq template
21923 (replace-regexp-in-string
21924 (concat "%" (regexp-quote (car entry)))
21925 (or (cdr entry) "") template t t)))
21926 template))
21928 (defun org-base-buffer (buffer)
21929 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21930 (if (not buffer)
21931 buffer
21932 (or (buffer-base-buffer buffer)
21933 buffer)))
21935 (defun org-wrap (string &optional width lines)
21936 "Wrap string to either a number of lines, or a width in characters.
21937 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21938 that costs. If there is a word longer than WIDTH, the text is actually
21939 wrapped to the length of that word.
21940 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21941 many lines, whatever width that takes.
21942 The return value is a list of lines, without newlines at the end."
21943 (let* ((words (org-split-string string "[ \t\n]+"))
21944 (maxword (apply 'max (mapcar 'org-string-width words)))
21945 w ll)
21946 (cond (width
21947 (org-do-wrap words (max maxword width)))
21948 (lines
21949 (setq w maxword)
21950 (setq ll (org-do-wrap words maxword))
21951 (if (<= (length ll) lines)
21953 (setq ll words)
21954 (while (> (length ll) lines)
21955 (setq w (1+ w))
21956 (setq ll (org-do-wrap words w)))
21957 ll))
21958 (t (error "Cannot wrap this")))))
21960 (defun org-do-wrap (words width)
21961 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21962 (let (lines line)
21963 (while words
21964 (setq line (pop words))
21965 (while (and words (< (+ (length line) (length (car words))) width))
21966 (setq line (concat line " " (pop words))))
21967 (setq lines (push line lines)))
21968 (nreverse lines)))
21970 (defun org-split-string (string &optional separators)
21971 "Splits STRING into substrings at SEPARATORS.
21972 SEPARATORS is a regular expression.
21973 No empty strings are returned if there are matches at the beginning
21974 and end of string."
21975 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
21976 (let ((start 0) notfirst list)
21977 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
21978 (if (and notfirst
21979 (= start (match-beginning 0))
21980 (< start (length string)))
21981 (1+ start) start))
21982 (< (match-beginning 0) (length string)))
21983 (setq notfirst t)
21984 (or (eq (match-beginning 0) 0)
21985 (and (eq (match-beginning 0) (match-end 0))
21986 (eq (match-beginning 0) start))
21987 (push (substring string start (match-beginning 0)) list))
21988 (setq start (match-end 0)))
21989 (or (eq start (length string))
21990 (push (substring string start) list))
21991 (nreverse list)))
21993 (defun org-quote-vert (s)
21994 "Replace \"|\" with \"\\vert\"."
21995 (while (string-match "|" s)
21996 (setq s (replace-match "\\vert" t t s)))
21999 (defun org-uuidgen-p (s)
22000 "Is S an ID created by UUIDGEN?"
22001 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22003 (defun org-in-src-block-p (&optional inside)
22004 "Whether point is in a code source block.
22005 When INSIDE is non-nil, don't consider we are within a src block
22006 when point is at #+BEGIN_SRC or #+END_SRC."
22007 (let ((case-fold-search t))
22008 (or (and (eq (get-char-property (point) 'src-block) t))
22009 (and (not inside)
22010 (save-match-data
22011 (save-excursion
22012 (beginning-of-line)
22013 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22015 (defun org-context ()
22016 "Return a list of contexts of the current cursor position.
22017 If several contexts apply, all are returned.
22018 Each context entry is a list with a symbol naming the context, and
22019 two positions indicating start and end of the context. Possible
22020 contexts are:
22022 :headline anywhere in a headline
22023 :headline-stars on the leading stars in a headline
22024 :todo-keyword on a TODO keyword (including DONE) in a headline
22025 :tags on the TAGS in a headline
22026 :priority on the priority cookie in a headline
22027 :item on the first line of a plain list item
22028 :item-bullet on the bullet/number of a plain list item
22029 :checkbox on the checkbox in a plain list item
22030 :table in an Org table
22031 :table-special on a special filed in a table
22032 :table-table in a table.el table
22033 :clocktable in a clocktable
22034 :src-block in a source block
22035 :link on a hyperlink
22036 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22037 :target on a <<target>>
22038 :radio-target on a <<<radio-target>>>
22039 :latex-fragment on a LaTeX fragment
22040 :latex-preview on a LaTeX fragment with overlaid preview image
22042 This function expects the position to be visible because it uses font-lock
22043 faces as a help to recognize the following contexts: :table-special, :link,
22044 and :keyword."
22045 (let* ((f (get-text-property (point) 'face))
22046 (faces (if (listp f) f (list f)))
22047 (case-fold-search t)
22048 (p (point)) clist o)
22049 ;; First the large context
22050 (cond
22051 ((org-at-heading-p t)
22052 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22053 (when (progn
22054 (beginning-of-line 1)
22055 (looking-at org-todo-line-tags-regexp))
22056 (push (org-point-in-group p 1 :headline-stars) clist)
22057 (push (org-point-in-group p 2 :todo-keyword) clist)
22058 (push (org-point-in-group p 4 :tags) clist))
22059 (goto-char p)
22060 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22061 (when (looking-at "\\[#[A-Z0-9]\\]")
22062 (push (org-point-in-group p 0 :priority) clist)))
22064 ((org-at-item-p)
22065 (push (org-point-in-group p 2 :item-bullet) clist)
22066 (push (list :item (point-at-bol)
22067 (save-excursion (org-end-of-item) (point)))
22068 clist)
22069 (and (org-at-item-checkbox-p)
22070 (push (org-point-in-group p 0 :checkbox) clist)))
22072 ((org-at-table-p)
22073 (push (list :table (org-table-begin) (org-table-end)) clist)
22074 (when (memq 'org-formula faces)
22075 (push (list :table-special
22076 (previous-single-property-change p 'face)
22077 (next-single-property-change p 'face)) clist)))
22078 ((org-at-table-p 'any)
22079 (push (list :table-table) clist)))
22080 (goto-char p)
22082 (let ((case-fold-search t))
22083 ;; New the "medium" contexts: clocktables, source blocks
22084 (cond ((org-in-clocktable-p)
22085 (push (list :clocktable
22086 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22087 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22088 (match-beginning 1))
22089 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22090 (match-end 0))) clist))
22091 ((org-in-src-block-p)
22092 (push (list :src-block
22093 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22094 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22095 (match-beginning 1))
22096 (and (search-forward "#+END_SRC" nil t)
22097 (match-beginning 0))) clist))))
22098 (goto-char p)
22100 ;; Now the small context
22101 (cond
22102 ((org-at-timestamp-p)
22103 (push (org-point-in-group p 0 :timestamp) clist))
22104 ((memq 'org-link faces)
22105 (push (list :link
22106 (previous-single-property-change p 'face)
22107 (next-single-property-change p 'face)) clist))
22108 ((memq 'org-special-keyword faces)
22109 (push (list :keyword
22110 (previous-single-property-change p 'face)
22111 (next-single-property-change p 'face)) clist))
22112 ((org-at-target-p)
22113 (push (org-point-in-group p 0 :target) clist)
22114 (goto-char (1- (match-beginning 0)))
22115 (when (looking-at org-radio-target-regexp)
22116 (push (org-point-in-group p 0 :radio-target) clist))
22117 (goto-char p))
22118 ((setq o (cl-some
22119 (lambda (o)
22120 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22122 (overlays-at (point))))
22123 (push (list :latex-fragment
22124 (overlay-start o) (overlay-end o)) clist)
22125 (push (list :latex-preview
22126 (overlay-start o) (overlay-end o)) clist))
22127 ((org-inside-LaTeX-fragment-p)
22128 ;; FIXME: positions wrong.
22129 (push (list :latex-fragment (point) (point)) clist)))
22131 (setq clist (nreverse (delq nil clist)))
22132 clist))
22134 (defun org-in-regexp (regexp &optional nlines visually)
22135 "Check if point is inside a match of REGEXP.
22137 Normally only the current line is checked, but you can include
22138 NLINES extra lines around point into the search. If VISUALLY is
22139 set, require that the cursor is not after the match but really
22140 on, so that the block visually is on the match.
22142 Return nil or a cons cell (BEG . END) where BEG and END are,
22143 respectively, the positions at the beginning and the end of the
22144 match."
22145 (catch :exit
22146 (let ((pos (point))
22147 (eol (line-end-position (if nlines (1+ nlines) 1))))
22148 (save-excursion
22149 (beginning-of-line (- 1 (or nlines 0)))
22150 (while (and (re-search-forward regexp eol t)
22151 (<= (match-beginning 0) pos))
22152 (let ((end (match-end 0)))
22153 (when (or (> end pos) (and (= end pos) (not visually)))
22154 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22156 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22157 "Non-nil when point is between matches of START-RE and END-RE.
22159 Also return a non-nil value when point is on one of the matches.
22161 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22162 buffer positions. Default values are the positions of headlines
22163 surrounding the point.
22165 The functions returns a cons cell whose car (resp. cdr) is the
22166 position before START-RE (resp. after END-RE)."
22167 (save-match-data
22168 (let ((pos (point))
22169 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22170 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22171 beg end)
22172 (save-excursion
22173 ;; Point is on a block when on START-RE or if START-RE can be
22174 ;; found before it...
22175 (and (or (org-in-regexp start-re)
22176 (re-search-backward start-re limit-up t))
22177 (setq beg (match-beginning 0))
22178 ;; ... and END-RE after it...
22179 (goto-char (match-end 0))
22180 (re-search-forward end-re limit-down t)
22181 (> (setq end (match-end 0)) pos)
22182 ;; ... without another START-RE in-between.
22183 (goto-char (match-beginning 0))
22184 (not (re-search-backward start-re (1+ beg) t))
22185 ;; Return value.
22186 (cons beg end))))))
22188 (defun org-in-block-p (names)
22189 "Non-nil when point belongs to a block whose name belongs to NAMES.
22191 NAMES is a list of strings containing names of blocks.
22193 Return first block name matched, or nil. Beware that in case of
22194 nested blocks, the returned name may not belong to the closest
22195 block from point."
22196 (save-match-data
22197 (catch 'exit
22198 (let ((case-fold-search t)
22199 (lim-up (save-excursion (outline-previous-heading)))
22200 (lim-down (save-excursion (outline-next-heading))))
22201 (dolist (name names)
22202 (let ((n (regexp-quote name)))
22203 (when (org-between-regexps-p
22204 (concat "^[ \t]*#\\+begin_" n)
22205 (concat "^[ \t]*#\\+end_" n)
22206 lim-up lim-down)
22207 (throw 'exit n)))))
22208 nil)))
22210 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22211 "Call `multi-occur' with buffers for all agenda files."
22212 (interactive "sOrg-files matching: ")
22213 (let* ((files (org-agenda-files))
22214 (tnames (mapcar #'file-truename files))
22215 (extra org-agenda-text-search-extra-files))
22216 (when (eq (car extra) 'agenda-archives)
22217 (setq extra (cdr extra))
22218 (setq files (org-add-archive-files files)))
22219 (dolist (f extra)
22220 (unless (member (file-truename f) tnames)
22221 (unless (member f files) (setq files (append files (list f))))
22222 (setq tnames (append tnames (list (file-truename f))))))
22223 (multi-occur
22224 (mapcar (lambda (x)
22225 (with-current-buffer
22226 ;; FIXME: Why not just (find-file-noselect x)?
22227 ;; Is it to avoid the "revert buffer" prompt?
22228 (or (get-file-buffer x) (find-file-noselect x))
22229 (widen)
22230 (current-buffer)))
22231 files)
22232 regexp)))
22234 (add-hook 'occur-mode-find-occurrence-hook
22235 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22237 (defun org-occur-link-in-agenda-files ()
22238 "Create a link and search for it in the agendas.
22239 The link is not stored in `org-stored-links', it is just created
22240 for the search purpose."
22241 (interactive)
22242 (let ((link (condition-case nil
22243 (org-store-link nil)
22244 (error "Unable to create a link to here"))))
22245 (org-occur-in-agenda-files (regexp-quote link))))
22247 (defun org-reverse-string (string)
22248 "Return the reverse of STRING."
22249 (apply 'string (reverse (string-to-list string))))
22251 ;; defsubst org-uniquify must be defined before first use
22253 (defun org-uniquify-alist (alist)
22254 "Merge elements of ALIST with the same key.
22256 For example, in this alist:
22258 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22259 => \\='((a 1 3) (b 2))
22261 merge (a 1) and (a 3) into (a 1 3).
22263 The function returns the new ALIST."
22264 (let (rtn)
22265 (dolist (e alist rtn)
22266 (let (n)
22267 (if (not (assoc (car e) rtn))
22268 (push e rtn)
22269 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22270 (setq rtn (assq-delete-all (car e) rtn))
22271 (push n rtn))))))
22273 (defun org-delete-all (elts list)
22274 "Remove all elements in ELTS from LIST.
22275 Comparison is done with `equal'. It is a destructive operation
22276 that may remove elements by altering the list structure."
22277 (while elts
22278 (setq list (delete (pop elts) list)))
22279 list)
22281 (defun org-back-over-empty-lines ()
22282 "Move backwards over whitespace, to the beginning of the first empty line.
22283 Returns the number of empty lines passed."
22284 (let ((pos (point)))
22285 (if (cdr (assq 'heading org-blank-before-new-entry))
22286 (skip-chars-backward " \t\n\r")
22287 (unless (eobp)
22288 (forward-line -1)))
22289 (beginning-of-line 2)
22290 (goto-char (min (point) pos))
22291 (count-lines (point) pos)))
22293 (defun org-skip-whitespace ()
22294 (skip-chars-forward " \t\n\r"))
22296 (defun org-point-in-group (point group &optional context)
22297 "Check if POINT is in match-group GROUP.
22298 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22299 match. If the match group does not exist or point is not inside it,
22300 return nil."
22301 (and (match-beginning group)
22302 (>= point (match-beginning group))
22303 (<= point (match-end group))
22304 (if context
22305 (list context (match-beginning group) (match-end group))
22306 t)))
22308 (defun org-switch-to-buffer-other-window (&rest args)
22309 "Switch to buffer in a second window on the current frame.
22310 In particular, do not allow pop-up frames.
22311 Returns the newly created buffer."
22312 (org-no-popups
22313 (apply 'switch-to-buffer-other-window args)))
22315 (defun org-combine-plists (&rest plists)
22316 "Create a single property list from all plists in PLISTS.
22317 The process starts by copying the first list, and then setting properties
22318 from the other lists. Settings in the last list are the most significant
22319 ones and overrule settings in the other lists."
22320 (let ((rtn (copy-sequence (pop plists)))
22321 p v ls)
22322 (while plists
22323 (setq ls (pop plists))
22324 (while ls
22325 (setq p (pop ls) v (pop ls))
22326 (setq rtn (plist-put rtn p v))))
22327 rtn))
22329 (defun org-replace-escapes (string table)
22330 "Replace %-escapes in STRING with values in TABLE.
22331 TABLE is an association list with keys like \"%a\" and string values.
22332 The sequences in STRING may contain normal field width and padding information,
22333 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22334 so values can contain further %-escapes if they are define later in TABLE."
22335 (let ((tbl (copy-alist table))
22336 (case-fold-search nil)
22337 (pchg 0)
22338 re rpl)
22339 (dolist (e tbl)
22340 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22341 (when (and (cdr e) (string-match re (cdr e)))
22342 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22343 (safe "SREF"))
22344 (add-text-properties 0 3 (list 'sref sref) safe)
22345 (setcdr e (replace-match safe t t (cdr e)))))
22346 (while (string-match re string)
22347 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22348 (cdr e)))
22349 (setq string (replace-match rpl t t string))))
22350 (while (setq pchg (next-property-change pchg string))
22351 (let ((sref (get-text-property pchg 'sref string)))
22352 (when (and sref (string-match "SREF" string pchg))
22353 (setq string (replace-match sref t t string)))))
22354 string))
22356 (defun org-find-base-buffer-visiting (file)
22357 "Like `find-buffer-visiting' but always return the base buffer and
22358 not an indirect buffer."
22359 (let ((buf (or (get-file-buffer file)
22360 (find-buffer-visiting file))))
22361 (if buf
22362 (or (buffer-base-buffer buf) buf)
22363 nil)))
22365 ;;; TODO: Only called once, from ox-odt which should probably use
22366 ;;; org-export-inline-image-p or something.
22367 (defun org-file-image-p (file)
22368 "Return non-nil if FILE is an image."
22369 (save-match-data
22370 (string-match (image-file-name-regexp) file)))
22372 (defun org-get-cursor-date (&optional with-time)
22373 "Return the date at cursor in as a time.
22374 This works in the calendar and in the agenda, anywhere else it just
22375 returns the current time.
22376 If WITH-TIME is non-nil, returns the time of the event at point (in
22377 the agenda) or the current time of the day."
22378 (let (date day defd tp hod mod)
22379 (when with-time
22380 (setq tp (get-text-property (point) 'time))
22381 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22382 (setq hod (string-to-number (match-string 1 tp))
22383 mod (string-to-number (match-string 2 tp))))
22384 (or tp (let ((now (decode-time)))
22385 (setq hod (nth 2 now)
22386 mod (nth 1 now)))))
22387 (cond
22388 ((eq major-mode 'calendar-mode)
22389 (setq date (calendar-cursor-to-date)
22390 defd (encode-time 0 (or mod 0) (or hod 0)
22391 (nth 1 date) (nth 0 date) (nth 2 date))))
22392 ((eq major-mode 'org-agenda-mode)
22393 (setq day (get-text-property (point) 'day))
22394 (when day
22395 (setq date (calendar-gregorian-from-absolute day)
22396 defd (encode-time 0 (or mod 0) (or hod 0)
22397 (nth 1 date) (nth 0 date) (nth 2 date))))))
22398 (or defd (current-time))))
22400 (defun org-mark-subtree (&optional up)
22401 "Mark the current subtree.
22402 This puts point at the start of the current subtree, and mark at
22403 the end. If a numeric prefix UP is given, move up into the
22404 hierarchy of headlines by UP levels before marking the subtree."
22405 (interactive "P")
22406 (org-with-limited-levels
22407 (cond ((org-at-heading-p) (beginning-of-line))
22408 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22409 (t (outline-previous-visible-heading 1))))
22410 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22411 (if (called-interactively-p 'any)
22412 (call-interactively 'org-mark-element)
22413 (org-mark-element)))
22415 (defun org-file-newer-than-p (file time)
22416 "Non-nil if FILE is newer than TIME.
22417 FILE is a filename, as a string, TIME is a list of integers, as
22418 returned by, e.g., `current-time'."
22419 (and (file-exists-p file)
22420 ;; Only compare times up to whole seconds as some file-systems
22421 ;; (e.g. HFS+) do not retain any finer granularity. As
22422 ;; a consequence, make sure we return non-nil when the two
22423 ;; times are equal.
22424 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22425 (cl-subseq time 0 2)))))
22427 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22428 "Compile a SOURCE file using PROCESS.
22430 PROCESS is either a function or a list of shell commands, as
22431 strings. EXT is a file extension, without the leading dot, as
22432 a string. It is used to check if the process actually succeeded.
22434 PROCESS must create a file with the same base name and directory
22435 as SOURCE, but ending with EXT. The function then returns its
22436 filename. Otherwise, it raises an error. The error message can
22437 then be refined by providing string ERR-MSG, which is appended to
22438 the standard message.
22440 If PROCESS is a function, it is called with a single argument:
22441 the SOURCE file.
22443 If it is a list of commands, each of them is called using
22444 `shell-command'. By default, in each command, %b, %f, %F, %o and
22445 %O are replaced with, respectively, SOURCE base name, name, full
22446 name, directory and absolute output file name. It is possible,
22447 however, to use more place-holders by specifying them in optional
22448 argument SPEC, as an alist following the pattern
22450 (CHARACTER . REPLACEMENT-STRING).
22452 When PROCESS is a list of commands, optional argument LOG-BUF can
22453 be set to a buffer or a buffer name. `shell-command' then uses
22454 it for output."
22455 (let* ((base-name (file-name-base source))
22456 (full-name (file-truename source))
22457 (out-dir (or (file-name-directory source) "./"))
22458 (output (expand-file-name (concat base-name "." ext) out-dir))
22459 (time (current-time))
22460 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22461 (save-window-excursion
22462 (pcase process
22463 ((pred functionp) (funcall process (shell-quote-argument source)))
22464 ((pred consp)
22465 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22466 (spec (append spec
22467 `((?b . ,(shell-quote-argument base-name))
22468 (?f . ,(shell-quote-argument source))
22469 (?F . ,(shell-quote-argument full-name))
22470 (?o . ,(shell-quote-argument out-dir))
22471 (?O . ,(shell-quote-argument output))))))
22472 (dolist (command process)
22473 (shell-command (format-spec command spec) log-buf))
22474 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22475 (_ (error "No valid command to process %S%s" source err-msg))))
22476 ;; Check for process failure. Output file is expected to be
22477 ;; located in the same directory as SOURCE.
22478 (unless (org-file-newer-than-p output time)
22479 (error (format "File %S wasn't produced%s" output err-msg)))
22480 output))
22482 ;;; Indentation
22484 (defvar org-element-greater-elements)
22485 (defun org--get-expected-indentation (element contentsp)
22486 "Expected indentation column for current line, according to ELEMENT.
22487 ELEMENT is an element containing point. CONTENTSP is non-nil
22488 when indentation is to be computed according to contents of
22489 ELEMENT."
22490 (let ((type (org-element-type element))
22491 (start (org-element-property :begin element))
22492 (post-affiliated (org-element-property :post-affiliated element)))
22493 (org-with-wide-buffer
22494 (cond
22495 (contentsp
22496 (cl-case type
22497 ((diary-sexp footnote-definition) 0)
22498 ((headline inlinetask nil)
22499 (if (not org-adapt-indentation) 0
22500 (let ((level (org-current-level)))
22501 (if level (1+ level) 0))))
22502 ((item plain-list) (org-list-item-body-column post-affiliated))
22504 (goto-char start)
22505 (org-get-indentation))))
22506 ((memq type '(headline inlinetask nil))
22507 (if (org-match-line "[ \t]*$")
22508 (org--get-expected-indentation element t)
22510 ((memq type '(diary-sexp footnote-definition)) 0)
22511 ;; First paragraph of a footnote definition or an item.
22512 ;; Indent like parent.
22513 ((< (line-beginning-position) start)
22514 (org--get-expected-indentation
22515 (org-element-property :parent element) t))
22516 ;; At first line: indent according to previous sibling, if any,
22517 ;; ignoring footnote definitions and inline tasks, or parent's
22518 ;; contents.
22519 ((= (line-beginning-position) start)
22520 (catch 'exit
22521 (while t
22522 (if (= (point-min) start) (throw 'exit 0)
22523 (goto-char (1- start))
22524 (let* ((previous (org-element-at-point))
22525 (parent previous))
22526 (while (and parent (<= (org-element-property :end parent) start))
22527 (setq previous parent
22528 parent (org-element-property :parent parent)))
22529 (cond
22530 ((not previous) (throw 'exit 0))
22531 ((> (org-element-property :end previous) start)
22532 (throw 'exit (org--get-expected-indentation previous t)))
22533 ((memq (org-element-type previous)
22534 '(footnote-definition inlinetask))
22535 (setq start (org-element-property :begin previous)))
22536 (t (goto-char (org-element-property :begin previous))
22537 (throw 'exit
22538 (if (bolp) (org-get-indentation)
22539 ;; At first paragraph in an item or
22540 ;; a footnote definition.
22541 (org--get-expected-indentation
22542 (org-element-property :parent previous) t))))))))))
22543 ;; Otherwise, move to the first non-blank line above.
22545 (beginning-of-line)
22546 (let ((pos (point)))
22547 (skip-chars-backward " \r\t\n")
22548 (cond
22549 ;; Two blank lines end a footnote definition or a plain
22550 ;; list. When we indent an empty line after them, the
22551 ;; containing list or footnote definition is over, so it
22552 ;; qualifies as a previous sibling. Therefore, we indent
22553 ;; like its first line.
22554 ((and (memq type '(footnote-definition plain-list))
22555 (> (count-lines (point) pos) 2))
22556 (goto-char start)
22557 (org-get-indentation))
22558 ;; Line above is the first one of a paragraph at the
22559 ;; beginning of an item or a footnote definition. Indent
22560 ;; like parent.
22561 ((< (line-beginning-position) start)
22562 (org--get-expected-indentation
22563 (org-element-property :parent element) t))
22564 ;; Line above is the beginning of an element, i.e., point
22565 ;; was originally on the blank lines between element's start
22566 ;; and contents.
22567 ((= (line-beginning-position) post-affiliated)
22568 (org--get-expected-indentation element t))
22569 ;; POS is after contents in a greater element. Indent like
22570 ;; the beginning of the element.
22571 ((and (memq type org-element-greater-elements)
22572 (let ((cend (org-element-property :contents-end element)))
22573 (and cend (<= cend pos))))
22574 ;; As a special case, if point is at the end of a footnote
22575 ;; definition or an item, indent like the very last element
22576 ;; within. If that last element is an item, indent like
22577 ;; its contents.
22578 (if (memq type '(footnote-definition item plain-list))
22579 (let ((last (org-element-at-point)))
22580 (goto-char pos)
22581 (org--get-expected-indentation
22582 last (eq (org-element-type last) 'item)))
22583 (goto-char start)
22584 (org-get-indentation)))
22585 ;; In any other case, indent like the current line.
22586 (t (org-get-indentation)))))))))
22588 (defun org--align-node-property ()
22589 "Align node property at point.
22590 Alignment is done according to `org-property-format', which see."
22591 (when (save-excursion
22592 (beginning-of-line)
22593 (looking-at org-property-re))
22594 (replace-match
22595 (concat (match-string 4)
22596 (org-trim
22597 (format org-property-format (match-string 1) (match-string 3))))
22598 t t)))
22600 (defun org-indent-line ()
22601 "Indent line depending on context.
22603 Indentation is done according to the following rules:
22605 - Footnote definitions, diary sexps, headlines and inline tasks
22606 have to start at column 0.
22608 - On the very first line of an element, consider, in order, the
22609 next rules until one matches:
22611 1. If there's a sibling element before, ignoring footnote
22612 definitions and inline tasks, indent like its first line.
22614 2. If element has a parent, indent like its contents. More
22615 precisely, if parent is an item, indent after the
22616 description part, if any, or the bullet (see
22617 `org-list-description-max-indent'). Else, indent like
22618 parent's first line.
22620 3. Otherwise, indent relatively to current level, if
22621 `org-adapt-indentation' is non-nil, or to left margin.
22623 - On a blank line at the end of an element, indent according to
22624 the type of the element. More precisely
22626 1. If element is a plain list, an item, or a footnote
22627 definition, indent like the very last element within.
22629 2. If element is a paragraph, indent like its last non blank
22630 line.
22632 3. Otherwise, indent like its very first line.
22634 - In the code part of a source block, use language major mode
22635 to indent current line if `org-src-tab-acts-natively' is
22636 non-nil. If it is nil, do nothing.
22638 - Otherwise, indent like the first non-blank line above.
22640 The function doesn't indent an item as it could break the whole
22641 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22642 `\\[org-shiftmetaright]'.
22644 Also align node properties according to `org-property-format'."
22645 (interactive)
22646 (cond
22647 (orgstruct-is-++
22648 (let ((indent-line-function
22649 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22650 (indent-according-to-mode)))
22651 ((org-at-heading-p) 'noindent)
22653 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22654 (type (org-element-type element)))
22655 (cond ((and (memq type '(plain-list item))
22656 (= (line-beginning-position)
22657 (org-element-property :post-affiliated element)))
22658 'noindent)
22659 ((and (eq type 'latex-environment)
22660 (>= (point) (org-element-property :post-affiliated element))
22661 (< (point) (org-with-wide-buffer
22662 (goto-char (org-element-property :end element))
22663 (skip-chars-backward " \r\t\n")
22664 (line-beginning-position 2))))
22665 'noindent)
22666 ((and (eq type 'src-block)
22667 org-src-tab-acts-natively
22668 (> (line-beginning-position)
22669 (org-element-property :post-affiliated element))
22670 (< (line-beginning-position)
22671 (org-with-wide-buffer
22672 (goto-char (org-element-property :end element))
22673 (skip-chars-backward " \r\t\n")
22674 (line-beginning-position))))
22675 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22677 (let ((column (org--get-expected-indentation element nil)))
22678 ;; Preserve current column.
22679 (if (<= (current-column) (current-indentation))
22680 (indent-line-to column)
22681 (save-excursion (indent-line-to column))))
22682 ;; Align node property. Also preserve current column.
22683 (when (eq type 'node-property)
22684 (let ((column (current-column)))
22685 (org--align-node-property)
22686 (org-move-to-column column)))))))))
22688 (defun org-indent-region (start end)
22689 "Indent each non-blank line in the region.
22690 Called from a program, START and END specify the region to
22691 indent. The function will not indent contents of example blocks,
22692 verse blocks and export blocks as leading white spaces are
22693 assumed to be significant there."
22694 (interactive "r")
22695 (save-excursion
22696 (goto-char start)
22697 (skip-chars-forward " \r\t\n")
22698 (unless (eobp) (beginning-of-line))
22699 (let ((indent-to
22700 (lambda (ind pos)
22701 ;; Set IND as indentation for all lines between point and
22702 ;; POS. Blank lines are ignored. Leave point after POS
22703 ;; once done.
22704 (let ((limit (copy-marker pos)))
22705 (while (< (point) limit)
22706 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22707 (forward-line))
22708 (set-marker limit nil))))
22709 (end (copy-marker end)))
22710 (while (< (point) end)
22711 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22712 (let* ((element (org-element-at-point))
22713 (type (org-element-type element))
22714 (element-end (copy-marker (org-element-property :end element)))
22715 (ind (org--get-expected-indentation element nil)))
22716 (cond
22717 ;; Element indented as a single block. Example blocks
22718 ;; preserving indentation are a special case since the
22719 ;; "contents" must not be indented whereas the block
22720 ;; boundaries can.
22721 ((or (memq type '(export-block latex-environment))
22722 (and (eq type 'example-block)
22723 (not
22724 (or org-src-preserve-indentation
22725 (org-element-property :preserve-indent element)))))
22726 (let ((offset (- ind (org-get-indentation))))
22727 (unless (zerop offset)
22728 (indent-rigidly (org-element-property :begin element)
22729 (org-element-property :end element)
22730 offset)))
22731 (goto-char element-end))
22732 ;; Elements indented line wise. Be sure to exclude
22733 ;; example blocks (preserving indentation) and source
22734 ;; blocks from this category as they are treated
22735 ;; specially later.
22736 ((or (memq type '(paragraph table table-row))
22737 (not (or (org-element-property :contents-begin element)
22738 (memq type '(example-block src-block)))))
22739 (when (eq type 'node-property)
22740 (org--align-node-property)
22741 (beginning-of-line))
22742 (funcall indent-to ind (min element-end end)))
22743 ;; Elements consisting of three parts: before the
22744 ;; contents, the contents, and after the contents. The
22745 ;; contents are treated specially, according to the
22746 ;; element type, or not indented at all. Other parts are
22747 ;; indented as a single block.
22749 (let* ((post (copy-marker
22750 (org-element-property :post-affiliated element)))
22751 (cbeg
22752 (copy-marker
22753 (cond
22754 ((not (org-element-property :contents-begin element))
22755 ;; Fake contents for source blocks.
22756 (org-with-wide-buffer
22757 (goto-char post)
22758 (line-beginning-position 2)))
22759 ((memq type '(footnote-definition item plain-list))
22760 ;; Contents in these elements could start on
22761 ;; the same line as the beginning of the
22762 ;; element. Make sure we start indenting
22763 ;; from the second line.
22764 (org-with-wide-buffer
22765 (goto-char post)
22766 (end-of-line)
22767 (skip-chars-forward " \r\t\n")
22768 (if (eobp) (point) (line-beginning-position))))
22769 (t (org-element-property :contents-begin element)))))
22770 (cend (copy-marker
22771 (or (org-element-property :contents-end element)
22772 ;; Fake contents for source blocks.
22773 (org-with-wide-buffer
22774 (goto-char element-end)
22775 (skip-chars-backward " \r\t\n")
22776 (line-beginning-position)))
22777 t)))
22778 ;; Do not change items indentation individually as it
22779 ;; might break the list as a whole. On the other
22780 ;; hand, when at a plain list, indent it as a whole.
22781 (cond ((eq type 'plain-list)
22782 (let ((offset (- ind (org-get-indentation))))
22783 (unless (zerop offset)
22784 (indent-rigidly (org-element-property :begin element)
22785 (org-element-property :end element)
22786 offset))
22787 (goto-char cbeg)))
22788 ((eq type 'item) (goto-char cbeg))
22789 (t (funcall indent-to ind (min cbeg end))))
22790 (when (< (point) end)
22791 (cl-case type
22792 ((example-block verse-block))
22793 (src-block
22794 ;; In a source block, indent source code
22795 ;; according to language major mode, but only if
22796 ;; `org-src-tab-acts-natively' is non-nil.
22797 (when (and (< (point) end) org-src-tab-acts-natively)
22798 (ignore-errors
22799 (org-babel-do-in-edit-buffer
22800 (indent-region (point-min) (point-max))))))
22801 (t (org-indent-region (point) (min cend end))))
22802 (goto-char (min cend end))
22803 (when (< (point) end)
22804 (funcall indent-to ind (min element-end end))))
22805 (set-marker post nil)
22806 (set-marker cbeg nil)
22807 (set-marker cend nil))))
22808 (set-marker element-end nil))))
22809 (set-marker end nil))))
22811 (defun org-indent-drawer ()
22812 "Indent the drawer at point."
22813 (interactive)
22814 (unless (save-excursion
22815 (beginning-of-line)
22816 (looking-at-p org-drawer-regexp))
22817 (user-error "Not at a drawer"))
22818 (let ((element (org-element-at-point)))
22819 (unless (memq (org-element-type element) '(drawer property-drawer))
22820 (user-error "Not at a drawer"))
22821 (org-with-wide-buffer
22822 (org-indent-region (org-element-property :begin element)
22823 (org-element-property :end element))))
22824 (message "Drawer at point indented"))
22826 (defun org-indent-block ()
22827 "Indent the block at point."
22828 (interactive)
22829 (unless (save-excursion
22830 (beginning-of-line)
22831 (let ((case-fold-search t))
22832 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22833 (user-error "Not at a block"))
22834 (let ((element (org-element-at-point)))
22835 (unless (memq (org-element-type element)
22836 '(comment-block center-block dynamic-block example-block
22837 export-block quote-block special-block
22838 src-block verse-block))
22839 (user-error "Not at a block"))
22840 (org-with-wide-buffer
22841 (org-indent-region (org-element-property :begin element)
22842 (org-element-property :end element))))
22843 (message "Block at point indented"))
22846 ;;; Filling
22848 ;; We use our own fill-paragraph and auto-fill functions.
22850 ;; `org-fill-paragraph' relies on adaptive filling and context
22851 ;; checking. Appropriate `fill-prefix' is computed with
22852 ;; `org-adaptive-fill-function'.
22854 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22855 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22856 ;; `org-adaptive-fill-function' value. Internally,
22857 ;; `org-comment-line-break-function' breaks the line.
22859 ;; `org-setup-filling' installs filling and auto-filling related
22860 ;; variables during `org-mode' initialization.
22862 (defvar org-element-paragraph-separate) ; org-element.el
22863 (defun org-setup-filling ()
22864 (require 'org-element)
22865 ;; Prevent auto-fill from inserting unwanted new items.
22866 (when (boundp 'fill-nobreak-predicate)
22867 (setq-local
22868 fill-nobreak-predicate
22869 (org-uniquify
22870 (append fill-nobreak-predicate
22871 '(org-fill-line-break-nobreak-p
22872 org-fill-n-macro-as-item-nobreak-p
22873 org-fill-paragraph-with-timestamp-nobreak-p)))))
22874 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22875 (setq-local paragraph-start paragraph-ending)
22876 (setq-local paragraph-separate paragraph-ending))
22877 (setq-local fill-paragraph-function 'org-fill-paragraph)
22878 (setq-local auto-fill-inhibit-regexp nil)
22879 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22880 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22881 (setq-local comment-line-break-function 'org-comment-line-break-function))
22883 (defun org-fill-line-break-nobreak-p ()
22884 "Non-nil when a new line at point would create an Org line break."
22885 (save-excursion
22886 (skip-chars-backward "[ \t]")
22887 (skip-chars-backward "\\\\")
22888 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22890 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22891 "Non-nil when a new line at point would split a timestamp."
22892 (and (org-at-timestamp-p 'lax)
22893 (not (looking-at org-ts-regexp-both))))
22895 (defun org-fill-n-macro-as-item-nobreak-p ()
22896 "Non-nil when a new line at point would create a new list."
22897 ;; During export, a "n" macro followed by a dot or a closing
22898 ;; parenthesis can end up being parsed as a new list item.
22899 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22901 (declare-function message-in-body-p "message" ())
22902 (defvar orgtbl-line-start-regexp) ; From org-table.el
22903 (defun org-adaptive-fill-function ()
22904 "Compute a fill prefix for the current line.
22905 Return fill prefix, as a string, or nil if current line isn't
22906 meant to be filled. For convenience, if `adaptive-fill-regexp'
22907 matches in paragraphs or comments, use it."
22908 (catch 'exit
22909 (when (derived-mode-p 'message-mode)
22910 (save-excursion
22911 (beginning-of-line)
22912 (cond ((not (message-in-body-p)) (throw 'exit nil))
22913 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22914 ((looking-at message-cite-prefix-regexp)
22915 (throw 'exit (match-string-no-properties 0)))
22916 ((looking-at org-outline-regexp)
22917 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22918 (org-with-wide-buffer
22919 (unless (org-at-heading-p)
22920 (let* ((p (line-beginning-position))
22921 (element (save-excursion
22922 (beginning-of-line)
22923 (org-element-at-point)))
22924 (type (org-element-type element))
22925 (post-affiliated (org-element-property :post-affiliated element)))
22926 (unless (< p post-affiliated)
22927 (cl-case type
22928 (comment
22929 (save-excursion
22930 (beginning-of-line)
22931 (looking-at "[ \t]*")
22932 (concat (match-string 0) "# ")))
22933 (footnote-definition "")
22934 ((item plain-list)
22935 (make-string (org-list-item-body-column post-affiliated) ?\s))
22936 (paragraph
22937 ;; Fill prefix is usually the same as the current line,
22938 ;; unless the paragraph is at the beginning of an item.
22939 (let ((parent (org-element-property :parent element)))
22940 (save-excursion
22941 (beginning-of-line)
22942 (cond ((eq (org-element-type parent) 'item)
22943 (make-string (org-list-item-body-column
22944 (org-element-property :begin parent))
22945 ?\s))
22946 ((and adaptive-fill-regexp
22947 ;; Locally disable
22948 ;; `adaptive-fill-function' to let
22949 ;; `fill-context-prefix' handle
22950 ;; `adaptive-fill-regexp' variable.
22951 (let (adaptive-fill-function)
22952 (fill-context-prefix
22953 post-affiliated
22954 (org-element-property :end element)))))
22955 ((looking-at "[ \t]+") (match-string 0))
22956 (t "")))))
22957 (comment-block
22958 ;; Only fill contents if P is within block boundaries.
22959 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22960 (forward-line)
22961 (point)))
22962 (cend (save-excursion
22963 (goto-char (org-element-property :end element))
22964 (skip-chars-backward " \r\t\n")
22965 (line-beginning-position))))
22966 (when (and (>= p cbeg) (< p cend))
22967 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22968 (match-string 0)
22969 "")))))))))))
22971 (declare-function message-goto-body "message" ())
22972 (defvar message-cite-prefix-regexp) ; From message.el
22974 (defun org-fill-element (&optional justify)
22975 "Fill element at point, when applicable.
22977 This function only applies to comment blocks, comments, example
22978 blocks and paragraphs. Also, as a special case, re-align table
22979 when point is at one.
22981 If JUSTIFY is non-nil (interactively, with prefix argument),
22982 justify as well. If `sentence-end-double-space' is non-nil, then
22983 period followed by one space does not end a sentence, so don't
22984 break a line there. The variable `fill-column' controls the
22985 width for filling.
22987 For convenience, when point is at a plain list, an item or
22988 a footnote definition, try to fill the first paragraph within."
22989 (with-syntax-table org-mode-transpose-word-syntax-table
22990 ;; Move to end of line in order to get the first paragraph within
22991 ;; a plain list or a footnote definition.
22992 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22993 ;; First check if point is in a blank line at the beginning of
22994 ;; the buffer. In that case, ignore filling.
22995 (cl-case (org-element-type element)
22996 ;; Use major mode filling function is src blocks.
22997 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22998 ;; Align Org tables, leave table.el tables as-is.
22999 (table-row (org-table-align) t)
23000 (table
23001 (when (eq (org-element-property :type element) 'org)
23002 (save-excursion
23003 (goto-char (org-element-property :post-affiliated element))
23004 (org-table-align)))
23006 (paragraph
23007 ;; Paragraphs may contain `line-break' type objects.
23008 (let ((beg (max (point-min)
23009 (org-element-property :contents-begin element)))
23010 (end (min (point-max)
23011 (org-element-property :contents-end element))))
23012 ;; Do nothing if point is at an affiliated keyword.
23013 (if (< (line-end-position) beg) t
23014 (when (derived-mode-p 'message-mode)
23015 ;; In `message-mode', do not fill following citation
23016 ;; in current paragraph nor text before message body.
23017 (let ((body-start (save-excursion (message-goto-body))))
23018 (when body-start (setq beg (max body-start beg))))
23019 (when (save-excursion
23020 (re-search-forward
23021 (concat "^" message-cite-prefix-regexp) end t))
23022 (setq end (match-beginning 0))))
23023 ;; Fill paragraph, taking line breaks into account.
23024 (save-excursion
23025 (goto-char beg)
23026 (let ((cuts (list beg)))
23027 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23028 (when (eq 'line-break
23029 (org-element-type
23030 (save-excursion (backward-char)
23031 (org-element-context))))
23032 (push (point) cuts)))
23033 (dolist (c (delq end cuts))
23034 (fill-region-as-paragraph c end justify)
23035 (setq end c))))
23036 t)))
23037 ;; Contents of `comment-block' type elements should be
23038 ;; filled as plain text, but only if point is within block
23039 ;; markers.
23040 (comment-block
23041 (let* ((case-fold-search t)
23042 (beg (save-excursion
23043 (goto-char (org-element-property :begin element))
23044 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23045 (forward-line)
23046 (point)))
23047 (end (save-excursion
23048 (goto-char (org-element-property :end element))
23049 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23050 (line-beginning-position))))
23051 (if (or (< (point) beg) (> (point) end)) t
23052 (fill-region-as-paragraph
23053 (save-excursion (end-of-line)
23054 (re-search-backward "^[ \t]*$" beg 'move)
23055 (line-beginning-position))
23056 (save-excursion (beginning-of-line)
23057 (re-search-forward "^[ \t]*$" end 'move)
23058 (line-beginning-position))
23059 justify))))
23060 ;; Fill comments.
23061 (comment
23062 (let ((begin (org-element-property :post-affiliated element))
23063 (end (org-element-property :end element)))
23064 (when (and (>= (point) begin) (<= (point) end))
23065 (let ((begin (save-excursion
23066 (end-of-line)
23067 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23068 (progn (forward-line) (point))
23069 begin)))
23070 (end (save-excursion
23071 (end-of-line)
23072 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23073 (1- (line-beginning-position))
23074 (skip-chars-backward " \r\t\n")
23075 (line-end-position)))))
23076 ;; Do not fill comments when at a blank line.
23077 (when (> end begin)
23078 (let ((fill-prefix
23079 (save-excursion
23080 (beginning-of-line)
23081 (looking-at "[ \t]*#")
23082 (let ((comment-prefix (match-string 0)))
23083 (goto-char (match-end 0))
23084 (if (looking-at adaptive-fill-regexp)
23085 (concat comment-prefix (match-string 0))
23086 (concat comment-prefix " "))))))
23087 (save-excursion
23088 (fill-region-as-paragraph begin end justify))))))
23090 ;; Ignore every other element.
23091 (otherwise t)))))
23093 (defun org-fill-paragraph (&optional justify region)
23094 "Fill element at point, when applicable.
23096 This function only applies to comment blocks, comments, example
23097 blocks and paragraphs. Also, as a special case, re-align table
23098 when point is at one.
23100 For convenience, when point is at a plain list, an item or
23101 a footnote definition, try to fill the first paragraph within.
23103 If JUSTIFY is non-nil (interactively, with prefix argument),
23104 justify as well. If `sentence-end-double-space' is non-nil, then
23105 period followed by one space does not end a sentence, so don't
23106 break a line there. The variable `fill-column' controls the
23107 width for filling.
23109 The REGION argument is non-nil if called interactively; in that
23110 case, if Transient Mark mode is enabled and the mark is active,
23111 fill each of the elements in the active region, instead of just
23112 filling the current element."
23113 (interactive (progn
23114 (barf-if-buffer-read-only)
23115 (list (if current-prefix-arg 'full) t)))
23116 (cond
23117 ((and (derived-mode-p 'message-mode)
23118 (or (not (message-in-body-p))
23119 (save-excursion (move-beginning-of-line 1)
23120 (looking-at message-cite-prefix-regexp))))
23121 ;; First ensure filling is correct in message-mode.
23122 (let ((fill-paragraph-function
23123 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23124 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23125 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23126 (paragraph-separate
23127 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23128 (fill-paragraph nil)))
23129 ((and region transient-mark-mode mark-active
23130 (not (eq (region-beginning) (region-end))))
23131 (let ((origin (point-marker))
23132 (start (region-beginning)))
23133 (unwind-protect
23134 (progn
23135 (goto-char (region-end))
23136 (while (> (point) start)
23137 (org-backward-paragraph)
23138 (org-fill-element justify)))
23139 (goto-char origin)
23140 (set-marker origin nil))))
23141 (t (org-fill-element justify))))
23142 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23144 (defun org-auto-fill-function ()
23145 "Auto-fill function."
23146 ;; Check if auto-filling is meaningful.
23147 (let ((fc (current-fill-column)))
23148 (when (and fc (> (current-column) fc))
23149 (let* ((fill-prefix (org-adaptive-fill-function))
23150 ;; Enforce empty fill prefix, if required. Otherwise, it
23151 ;; will be computed again.
23152 (adaptive-fill-mode (not (equal fill-prefix ""))))
23153 (when fill-prefix (do-auto-fill))))))
23155 (defun org-comment-line-break-function (&optional soft)
23156 "Break line at point and indent, continuing comment if within one.
23157 The inserted newline is marked hard if variable
23158 `use-hard-newlines' is true, unless optional argument SOFT is
23159 non-nil."
23160 (if soft (insert-and-inherit ?\n) (newline 1))
23161 (save-excursion (forward-char -1) (delete-horizontal-space))
23162 (delete-horizontal-space)
23163 (indent-to-left-margin)
23164 (insert-before-markers-and-inherit fill-prefix))
23167 ;;; Fixed Width Areas
23169 (defun org-toggle-fixed-width ()
23170 "Toggle fixed-width markup.
23172 Add or remove fixed-width markup on current line, whenever it
23173 makes sense. Return an error otherwise.
23175 If a region is active and if it contains only fixed-width areas
23176 or blank lines, remove all fixed-width markup in it. If the
23177 region contains anything else, convert all non-fixed-width lines
23178 to fixed-width ones.
23180 Blank lines at the end of the region are ignored unless the
23181 region only contains such lines."
23182 (interactive)
23183 (if (not (org-region-active-p))
23184 ;; No region:
23186 ;; Remove fixed width marker only in a fixed-with element.
23188 ;; Add fixed width maker in paragraphs, in blank lines after
23189 ;; elements or at the beginning of a headline or an inlinetask,
23190 ;; and before any one-line elements (e.g., a clock).
23191 (progn
23192 (beginning-of-line)
23193 (let* ((element (org-element-at-point))
23194 (type (org-element-type element)))
23195 (cond
23196 ((and (eq type 'fixed-width)
23197 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23198 (replace-match
23199 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23200 ((and (memq type '(babel-call clock comment diary-sexp headline
23201 horizontal-rule keyword paragraph
23202 planning))
23203 (<= (org-element-property :post-affiliated element) (point)))
23204 (skip-chars-forward " \t")
23205 (insert ": "))
23206 ((and (looking-at-p "[ \t]*$")
23207 (or (eq type 'inlinetask)
23208 (save-excursion
23209 (skip-chars-forward " \r\t\n")
23210 (<= (org-element-property :end element) (point)))))
23211 (delete-region (point) (line-end-position))
23212 (org-indent-line)
23213 (insert ": "))
23214 (t (user-error "Cannot insert a fixed-width line here")))))
23215 ;; Region active.
23216 (let* ((begin (save-excursion
23217 (goto-char (region-beginning))
23218 (line-beginning-position)))
23219 (end (copy-marker
23220 (save-excursion
23221 (goto-char (region-end))
23222 (unless (eolp) (beginning-of-line))
23223 (if (save-excursion (re-search-backward "\\S-" begin t))
23224 (progn (skip-chars-backward " \r\t\n") (point))
23225 (point)))))
23226 (all-fixed-width-p
23227 (catch 'not-all-p
23228 (save-excursion
23229 (goto-char begin)
23230 (skip-chars-forward " \r\t\n")
23231 (when (eobp) (throw 'not-all-p nil))
23232 (while (< (point) end)
23233 (let ((element (org-element-at-point)))
23234 (if (eq (org-element-type element) 'fixed-width)
23235 (goto-char (org-element-property :end element))
23236 (throw 'not-all-p nil))))
23237 t))))
23238 (if all-fixed-width-p
23239 (save-excursion
23240 (goto-char begin)
23241 (while (< (point) end)
23242 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23243 (replace-match
23244 "" nil nil nil
23245 (if (= (line-end-position) (match-end 0)) 0 1)))
23246 (forward-line)))
23247 (let ((min-ind (point-max)))
23248 ;; Find minimum indentation across all lines.
23249 (save-excursion
23250 (goto-char begin)
23251 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23252 (setq min-ind 0)
23253 (catch 'zerop
23254 (while (< (point) end)
23255 (unless (looking-at-p "[ \t]*$")
23256 (let ((ind (org-get-indentation)))
23257 (setq min-ind (min min-ind ind))
23258 (when (zerop ind) (throw 'zerop t))))
23259 (forward-line)))))
23260 ;; Loop over all lines and add fixed-width markup everywhere
23261 ;; but in fixed-width lines.
23262 (save-excursion
23263 (goto-char begin)
23264 (while (< (point) end)
23265 (cond
23266 ((org-at-heading-p)
23267 (insert ": ")
23268 (forward-line)
23269 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23270 (insert ":")
23271 (forward-line)))
23272 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23273 (let* ((element (org-element-at-point))
23274 (element-end (org-element-property :end element)))
23275 (if (eq (org-element-type element) 'fixed-width)
23276 (progn (goto-char element-end)
23277 (skip-chars-backward " \r\t\n")
23278 (forward-line))
23279 (let ((limit (min end element-end)))
23280 (while (< (point) limit)
23281 (org-move-to-column min-ind t)
23282 (insert ": ")
23283 (forward-line))))))
23285 (org-move-to-column min-ind t)
23286 (insert ": ")
23287 (forward-line)))))))
23288 (set-marker end nil))))
23291 ;;; Comments
23293 ;; Org comments syntax is quite complex. It requires the entire line
23294 ;; to be just a comment. Also, even with the right syntax at the
23295 ;; beginning of line, some elements (e.g., verse-block or
23296 ;; example-block) don't accept comments. Usual Emacs comment commands
23297 ;; cannot cope with those requirements. Therefore, Org replaces them.
23299 ;; Org still relies on `comment-dwim', but cannot trust
23300 ;; `comment-only-p'. So, `comment-region-function' and
23301 ;; `uncomment-region-function' both point
23302 ;; to`org-comment-or-uncomment-region'. Eventually,
23303 ;; `org-insert-comment' takes care of insertion of comments at the
23304 ;; beginning of line.
23306 ;; `org-setup-comments-handling' install comments related variables
23307 ;; during `org-mode' initialization.
23309 (defun org-setup-comments-handling ()
23310 (interactive)
23311 (setq-local comment-use-syntax nil)
23312 (setq-local comment-start "# ")
23313 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23314 (setq-local comment-insert-comment-function 'org-insert-comment)
23315 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23316 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23318 (defun org-insert-comment ()
23319 "Insert an empty comment above current line.
23320 If the line is empty, insert comment at its beginning. When
23321 point is within a source block, comment according to the related
23322 major mode."
23323 (if (let ((element (org-element-at-point)))
23324 (and (eq (org-element-type element) 'src-block)
23325 (< (save-excursion
23326 (goto-char (org-element-property :post-affiliated element))
23327 (line-end-position))
23328 (point))
23329 (> (save-excursion
23330 (goto-char (org-element-property :end element))
23331 (skip-chars-backward " \r\t\n")
23332 (line-beginning-position))
23333 (point))))
23334 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23335 (beginning-of-line)
23336 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23337 (open-line 1))
23338 (org-indent-line)
23339 (insert "# ")))
23341 (defvar comment-empty-lines) ; From newcomment.el.
23342 (defun org-comment-or-uncomment-region (beg end &rest _)
23343 "Comment or uncomment each non-blank line in the region.
23344 Uncomment each non-blank line between BEG and END if it only
23345 contains commented lines. Otherwise, comment them. If region is
23346 strictly within a source block, use appropriate comment syntax."
23347 (if (let ((element (org-element-at-point)))
23348 (and (eq (org-element-type element) 'src-block)
23349 (< (save-excursion
23350 (goto-char (org-element-property :post-affiliated element))
23351 (line-end-position))
23352 beg)
23353 (>= (save-excursion
23354 (goto-char (org-element-property :end element))
23355 (skip-chars-backward " \r\t\n")
23356 (line-beginning-position))
23357 end)))
23358 ;; Translate region boundaries for the Org buffer to the source
23359 ;; buffer.
23360 (let ((offset (- end beg)))
23361 (save-excursion
23362 (goto-char beg)
23363 (org-babel-do-in-edit-buffer
23364 (comment-or-uncomment-region (point) (+ offset (point))))))
23365 (save-restriction
23366 ;; Restrict region
23367 (narrow-to-region (save-excursion (goto-char beg)
23368 (skip-chars-forward " \r\t\n" end)
23369 (line-beginning-position))
23370 (save-excursion (goto-char end)
23371 (skip-chars-backward " \r\t\n" beg)
23372 (line-end-position)))
23373 (let ((uncommentp
23374 ;; UNCOMMENTP is non-nil when every non blank line between
23375 ;; BEG and END is a comment.
23376 (save-excursion
23377 (goto-char (point-min))
23378 (while (and (not (eobp))
23379 (let ((element (org-element-at-point)))
23380 (and (eq (org-element-type element) 'comment)
23381 (goto-char (min (point-max)
23382 (org-element-property
23383 :end element)))))))
23384 (eobp))))
23385 (if uncommentp
23386 ;; Only blank lines and comments in region: uncomment it.
23387 (save-excursion
23388 (goto-char (point-min))
23389 (while (not (eobp))
23390 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23391 (replace-match "" nil nil nil 1))
23392 (forward-line)))
23393 ;; Comment each line in region.
23394 (let ((min-indent (point-max)))
23395 ;; First find the minimum indentation across all lines.
23396 (save-excursion
23397 (goto-char (point-min))
23398 (while (and (not (eobp)) (not (zerop min-indent)))
23399 (unless (looking-at "[ \t]*$")
23400 (setq min-indent (min min-indent (current-indentation))))
23401 (forward-line)))
23402 ;; Then loop over all lines.
23403 (save-excursion
23404 (goto-char (point-min))
23405 (while (not (eobp))
23406 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23407 ;; Don't get fooled by invisible text (e.g. link path)
23408 ;; when moving to column MIN-INDENT.
23409 (let ((buffer-invisibility-spec nil))
23410 (org-move-to-column min-indent t))
23411 (insert comment-start))
23412 (forward-line)))))))))
23414 (defun org-comment-dwim (_arg)
23415 "Call `comment-dwim' within a source edit buffer if needed."
23416 (interactive "*P")
23417 (if (org-in-src-block-p)
23418 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23419 (call-interactively 'comment-dwim)))
23422 ;;; Timestamps API
23424 ;; This section contains tools to operate on timestamp objects, as
23425 ;; returned by, e.g. `org-element-context'.
23427 (defun org-timestamp--to-internal-time (timestamp &optional end)
23428 "Encode TIMESTAMP object into Emacs internal time.
23429 Use end of date range or time range when END is non-nil."
23430 (apply #'encode-time
23431 (cons 0
23432 (mapcar
23433 (lambda (prop) (or (org-element-property prop timestamp) 0))
23434 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23435 '(:minute-start :hour-start :day-start :month-start
23436 :year-start))))))
23438 (defun org-timestamp-has-time-p (timestamp)
23439 "Non-nil when TIMESTAMP has a time specified."
23440 (org-element-property :hour-start timestamp))
23442 (defun org-timestamp-format (timestamp format &optional end utc)
23443 "Format a TIMESTAMP object into a string.
23445 FORMAT is a format specifier to be passed to
23446 `format-time-string'.
23448 When optional argument END is non-nil, use end of date-range or
23449 time-range, if possible.
23451 When optional argument UTC is non-nil, time will be expressed as
23452 Universal Time."
23453 (format-time-string
23454 format (org-timestamp--to-internal-time timestamp end)
23455 (and utc t)))
23457 (defun org-timestamp-split-range (timestamp &optional end)
23458 "Extract a TIMESTAMP object from a date or time range.
23460 END, when non-nil, means extract the end of the range.
23461 Otherwise, extract its start.
23463 Return a new timestamp object."
23464 (let ((type (org-element-property :type timestamp)))
23465 (if (memq type '(active inactive diary)) timestamp
23466 (let ((split-ts (org-element-copy timestamp)))
23467 ;; Set new type.
23468 (org-element-put-property
23469 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23470 ;; Copy start properties over end properties if END is
23471 ;; non-nil. Otherwise, copy end properties over `start' ones.
23472 (let ((p-alist '((:minute-start . :minute-end)
23473 (:hour-start . :hour-end)
23474 (:day-start . :day-end)
23475 (:month-start . :month-end)
23476 (:year-start . :year-end))))
23477 (dolist (p-cell p-alist)
23478 (org-element-put-property
23479 split-ts
23480 (funcall (if end #'car #'cdr) p-cell)
23481 (org-element-property
23482 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23483 ;; Eventually refresh `:raw-value'.
23484 (org-element-put-property split-ts :raw-value nil)
23485 (org-element-put-property
23486 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23488 (defun org-timestamp-translate (timestamp &optional boundary)
23489 "Translate TIMESTAMP object to custom format.
23491 Format string is defined in `org-time-stamp-custom-formats',
23492 which see.
23494 When optional argument BOUNDARY is non-nil, it is either the
23495 symbol `start' or `end'. In this case, only translate the
23496 starting or ending part of TIMESTAMP if it is a date or time
23497 range. Otherwise, translate both parts.
23499 Return timestamp as-is if `org-display-custom-times' is nil or if
23500 it has a `diary' type."
23501 (let ((type (org-element-property :type timestamp)))
23502 (if (or (not org-display-custom-times) (eq type 'diary))
23503 (org-element-interpret-data timestamp)
23504 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23505 org-time-stamp-custom-formats)))
23506 (if (and (not boundary) (memq type '(active-range inactive-range)))
23507 (concat (org-timestamp-format timestamp fmt)
23508 "--"
23509 (org-timestamp-format timestamp fmt t))
23510 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23514 ;;; Other stuff.
23516 (defvar reftex-docstruct-symbol)
23517 (defvar org--rds)
23519 (defun org-reftex-citation ()
23520 "Use reftex-citation to insert a citation into the buffer.
23521 This looks for a line like
23523 #+BIBLIOGRAPHY: foo plain option:-d
23525 and derives from it that foo.bib is the bibliography file relevant
23526 for this document. It then installs the necessary environment for RefTeX
23527 to work in this buffer and calls `reftex-citation' to insert a citation
23528 into the buffer.
23530 Export of such citations to both LaTeX and HTML is handled by the contributed
23531 package ox-bibtex by Taru Karttunen."
23532 (interactive)
23533 (let ((reftex-docstruct-symbol 'org--rds)
23534 org--rds bib)
23535 (org-with-wide-buffer
23536 (let ((case-fold-search t)
23537 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23538 (if (not (save-excursion
23539 (or (re-search-forward re nil t)
23540 (re-search-backward re nil t))))
23541 (user-error "No bibliography defined in file")
23542 (setq bib (concat (match-string 1) ".bib")
23543 org--rds (list (list 'bib bib))))))
23544 (call-interactively 'reftex-citation)))
23546 ;;;; Functions extending outline functionality
23548 (defun org-beginning-of-line (&optional n)
23549 "Go to the beginning of the current visible line.
23551 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23552 tags on the first attempt, and only move to after the tags when
23553 the cursor is already beyond the end of the headline.
23555 With argument N not nil or 1, move forward N - 1 lines first."
23556 (interactive "^p")
23557 (let ((origin (point))
23558 (special (pcase org-special-ctrl-a/e
23559 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23560 deactivate-mark)
23561 ;; First move to a visible line.
23562 (if (bound-and-true-p visual-line-mode)
23563 (beginning-of-visual-line n)
23564 (move-beginning-of-line n)
23565 ;; `move-beginning-of-line' may leave point after invisible
23566 ;; characters if line starts with such of these (e.g., with
23567 ;; a link at column 0). Really move to the beginning of the
23568 ;; current visible line.
23569 (beginning-of-line))
23570 (cond
23571 ;; No special behavior. Point is already at the beginning of
23572 ;; a line, logical or visual.
23573 ((not special))
23574 ;; `beginning-of-visual-line' left point before logical beginning
23575 ;; of line: point is at the beginning of a visual line. Bail
23576 ;; out.
23577 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23578 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23579 ;; At a headline, special position is before the title, but
23580 ;; after any TODO keyword or priority cookie.
23581 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23582 (line-end-position)))
23583 (bol (point)))
23584 (if (eq special 'reversed)
23585 (when (and (= origin bol) (eq last-command this-command))
23586 (goto-char refpos))
23587 (when (or (> origin refpos) (= origin bol))
23588 (goto-char refpos)))))
23589 ((and (looking-at org-list-full-item-re)
23590 (memq (org-element-type (save-match-data (org-element-at-point)))
23591 '(item plain-list)))
23592 ;; Set special position at first white space character after
23593 ;; bullet, and check-box, if any.
23594 (let ((after-bullet
23595 (let ((box (match-end 3)))
23596 (cond ((not box) (match-end 1))
23597 ((eq (char-after box) ?\s) (1+ box))
23598 (t box)))))
23599 (if (eq special 'reversed)
23600 (when (and (= (point) origin) (eq last-command this-command))
23601 (goto-char after-bullet))
23602 (when (or (> origin after-bullet) (= (point) origin))
23603 (goto-char after-bullet)))))
23604 ;; No special context. Point is already at beginning of line.
23605 (t nil))))
23607 (defun org-end-of-line (&optional n)
23608 "Go to the end of the line, but before ellipsis, if any.
23610 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23611 tags on the first attempt, and only move to after the tags when
23612 the cursor is already beyond the end of the headline.
23614 With argument N not nil or 1, move forward N - 1 lines first."
23615 (interactive "^p")
23616 (let ((origin (point))
23617 (special (pcase org-special-ctrl-a/e
23618 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23619 deactivate-mark)
23620 ;; First move to a visible line.
23621 (if (bound-and-true-p visual-line-mode)
23622 (beginning-of-visual-line n)
23623 (move-beginning-of-line n))
23624 (cond
23625 ;; At a headline, with tags.
23626 ((and special
23627 (save-excursion
23628 (beginning-of-line)
23629 (let ((case-fold-search nil))
23630 (looking-at org-complex-heading-regexp)))
23631 (match-end 5))
23632 (let ((tags (save-excursion
23633 (goto-char (match-beginning 5))
23634 (skip-chars-backward " \t")
23635 (point)))
23636 (visual-end (and (bound-and-true-p visual-line-mode)
23637 (save-excursion
23638 (end-of-visual-line)
23639 (point)))))
23640 ;; If `end-of-visual-line' brings us before end of line or
23641 ;; even tags, i.e., the headline spans over multiple visual
23642 ;; lines, move there.
23643 (cond ((and visual-end
23644 (< visual-end tags)
23645 (<= origin visual-end))
23646 (goto-char visual-end))
23647 ((eq special 'reversed)
23648 (if (and (= origin (line-end-position))
23649 (eq this-command last-command))
23650 (goto-char tags)
23651 (end-of-line)))
23653 (if (or (< origin tags) (= origin (line-end-position)))
23654 (goto-char tags)
23655 (end-of-line))))))
23656 ((bound-and-true-p visual-line-mode)
23657 (let ((bol (line-beginning-position)))
23658 (end-of-visual-line)
23659 ;; If `end-of-visual-line' gets us past the ellipsis at the
23660 ;; end of a line, backtrack and use `end-of-line' instead.
23661 (when (/= bol (line-beginning-position))
23662 (goto-char bol)
23663 (end-of-line))))
23664 (t (end-of-line)))))
23666 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23667 (define-key org-mode-map "\C-e" 'org-end-of-line)
23669 (defun org-backward-sentence (&optional _arg)
23670 "Go to beginning of sentence, or beginning of table field.
23671 This will call `backward-sentence' or `org-table-beginning-of-field',
23672 depending on context."
23673 (interactive)
23674 (let* ((element (org-element-at-point))
23675 (contents-begin (org-element-property :contents-begin element))
23676 (table (org-element-lineage element '(table) t)))
23677 (if (and table
23678 (> (point) contents-begin)
23679 (<= (point) (org-element-property :contents-end table)))
23680 (call-interactively #'org-table-beginning-of-field)
23681 (save-restriction
23682 (when (and contents-begin
23683 (< (point-min) contents-begin)
23684 (> (point) contents-begin))
23685 (narrow-to-region contents-begin
23686 (org-element-property :contents-end element)))
23687 (call-interactively #'backward-sentence)))))
23689 (defun org-forward-sentence (&optional _arg)
23690 "Go to end of sentence, or end of table field.
23691 This will call `forward-sentence' or `org-table-end-of-field',
23692 depending on context."
23693 (interactive)
23694 (let* ((element (org-element-at-point))
23695 (contents-end (org-element-property :contents-end element))
23696 (table (org-element-lineage element '(table) t)))
23697 (if (and table
23698 (>= (point) (org-element-property :contents-begin table))
23699 (< (point) contents-end))
23700 (call-interactively #'org-table-end-of-field)
23701 (save-restriction
23702 (when (and contents-end
23703 (> (point-max) contents-end)
23704 ;; Skip blank lines between elements.
23705 (< (org-element-property :end element)
23706 (save-excursion (goto-char contents-end)
23707 (skip-chars-forward " \r\t\n"))))
23708 (narrow-to-region (org-element-property :contents-begin element)
23709 contents-end))
23710 (call-interactively #'forward-sentence)))))
23712 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23713 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23715 (defun org-kill-line (&optional _arg)
23716 "Kill line, to tags or end of line."
23717 (interactive)
23718 (cond
23719 ((or (not org-special-ctrl-k)
23720 (bolp)
23721 (not (org-at-heading-p)))
23722 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23723 org-ctrl-k-protect-subtree
23724 (or (eq org-ctrl-k-protect-subtree 'error)
23725 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23726 (user-error "C-k aborted as it would kill a hidden subtree"))
23727 (call-interactively
23728 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23729 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23730 (kill-region (point) (match-beginning 1))
23731 (org-set-tags nil t))
23732 (t (kill-region (point) (point-at-eol)))))
23734 (define-key org-mode-map "\C-k" 'org-kill-line)
23736 (defun org-yank (&optional arg)
23737 "Yank. If the kill is a subtree, treat it specially.
23738 This command will look at the current kill and check if is a single
23739 subtree, or a series of subtrees[1]. If it passes the test, and if the
23740 cursor is at the beginning of a line or after the stars of a currently
23741 empty headline, then the yank is handled specially. How exactly depends
23742 on the value of the following variables.
23744 `org-yank-folded-subtrees'
23745 By default, this variable is non-nil, which results in
23746 subtree(s) being folded after insertion, except if doing so
23747 would swallow text after the yanked text.
23749 `org-yank-adjusted-subtrees'
23750 When non-nil (the default value is nil), the subtree will be
23751 promoted or demoted in order to fit into the local outline tree
23752 structure, which means that the level will be adjusted so that it
23753 becomes the smaller one of the two *visible* surrounding headings.
23755 Any prefix to this command will cause `yank' to be called directly with
23756 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23757 will just
23758 plainly yank the text as it is.
23760 \[1] The test checks if the first non-white line is a heading
23761 and if there are no other headings with fewer stars."
23762 (interactive "P")
23763 (org-yank-generic 'yank arg))
23765 (defun org-yank-generic (command arg)
23766 "Perform some yank-like command.
23768 This function implements the behavior described in the `org-yank'
23769 documentation. However, it has been generalized to work for any
23770 interactive command with similar behavior."
23772 ;; pretend to be command COMMAND
23773 (setq this-command command)
23775 (if arg
23776 (call-interactively command)
23778 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23779 (and (org-kill-is-subtree-p)
23780 (or (bolp)
23781 (and (looking-at "[ \t]*$")
23782 (string-match
23783 "\\`\\*+\\'"
23784 (buffer-substring (point-at-bol) (point)))))))
23785 swallowp)
23786 (cond
23787 ((and subtreep org-yank-folded-subtrees)
23788 (let ((beg (point))
23789 end)
23790 (if (and subtreep org-yank-adjusted-subtrees)
23791 (org-paste-subtree nil nil 'for-yank)
23792 (call-interactively command))
23794 (setq end (point))
23795 (goto-char beg)
23796 (when (and (bolp) subtreep
23797 (not (setq swallowp
23798 (org-yank-folding-would-swallow-text beg end))))
23799 (org-with-limited-levels
23800 (or (looking-at org-outline-regexp)
23801 (re-search-forward org-outline-regexp-bol end t))
23802 (while (and (< (point) end) (looking-at org-outline-regexp))
23803 (outline-hide-subtree)
23804 (org-cycle-show-empty-lines 'folded)
23805 (condition-case nil
23806 (outline-forward-same-level 1)
23807 (error (goto-char end))))))
23808 (when swallowp
23809 (message
23810 "Inserted text not folded because that would swallow text"))
23812 (goto-char end)
23813 (skip-chars-forward " \t\n\r")
23814 (beginning-of-line 1)
23815 (push-mark beg 'nomsg)))
23816 ((and subtreep org-yank-adjusted-subtrees)
23817 (let ((beg (point-at-bol)))
23818 (org-paste-subtree nil nil 'for-yank)
23819 (push-mark beg 'nomsg)))
23821 (call-interactively command))))))
23823 (defun org-yank-folding-would-swallow-text (beg end)
23824 "Would hide-subtree at BEG swallow any text after END?"
23825 (let (level)
23826 (org-with-limited-levels
23827 (save-excursion
23828 (goto-char beg)
23829 (when (or (looking-at org-outline-regexp)
23830 (re-search-forward org-outline-regexp-bol end t))
23831 (setq level (org-outline-level)))
23832 (goto-char end)
23833 (skip-chars-forward " \t\r\n\v\f")
23834 (not (or (eobp)
23835 (and (bolp) (looking-at-p org-outline-regexp)
23836 (<= (org-outline-level) level))))))))
23838 (define-key org-mode-map "\C-y" 'org-yank)
23840 (defun org-truely-invisible-p ()
23841 "Check if point is at a character currently not visible.
23842 This version does not only check the character property, but also
23843 `visible-mode'."
23844 ;; Early versions of noutline don't have `outline-invisible-p'.
23845 (unless (bound-and-true-p visible-mode)
23846 (outline-invisible-p)))
23848 (defun org-invisible-p2 ()
23849 "Check if point is at a character currently not visible."
23850 (save-excursion
23851 (when (and (eolp) (not (bobp))) (backward-char 1))
23852 ;; Early versions of noutline don't have `outline-invisible-p'.
23853 (outline-invisible-p)))
23855 (defun org-back-to-heading (&optional invisible-ok)
23856 "Call `outline-back-to-heading', but provide a better error message."
23857 (condition-case nil
23858 (outline-back-to-heading invisible-ok)
23859 (error (error "Before first headline at position %d in buffer %s"
23860 (point) (current-buffer)))))
23862 (defun org-before-first-heading-p ()
23863 "Before first heading?"
23864 (save-excursion
23865 (end-of-line)
23866 (null (re-search-backward org-outline-regexp-bol nil t))))
23868 (defun org-at-heading-p (&optional ignored)
23869 (outline-on-heading-p t))
23871 (defun org-in-commented-heading-p (&optional no-inheritance)
23872 "Non-nil if point is under a commented heading.
23873 This function also checks ancestors of the current headline,
23874 unless optional argument NO-INHERITANCE is non-nil."
23875 (cond
23876 ((org-before-first-heading-p) nil)
23877 ((let ((headline (nth 4 (org-heading-components))))
23878 (and headline
23879 (let ((case-fold-search nil))
23880 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23881 headline)))))
23882 (no-inheritance nil)
23884 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23886 (defun org-at-comment-p nil
23887 "Is cursor in a commented line?"
23888 (save-excursion
23889 (save-match-data
23890 (beginning-of-line)
23891 (looking-at "^[ \t]*# "))))
23893 (defun org-at-drawer-p nil
23894 "Is cursor at a drawer keyword?"
23895 (save-excursion
23896 (move-beginning-of-line 1)
23897 (looking-at org-drawer-regexp)))
23899 (defun org-at-block-p nil
23900 "Is cursor at a block keyword?"
23901 (save-excursion
23902 (move-beginning-of-line 1)
23903 (looking-at org-block-regexp)))
23905 (defun org-point-at-end-of-empty-headline ()
23906 "If point is at the end of an empty headline, return t, else nil.
23907 If the heading only contains a TODO keyword, it is still still considered
23908 empty."
23909 (let ((case-fold-search nil))
23910 (and (looking-at "[ \t]*$")
23911 org-todo-line-regexp
23912 (save-excursion
23913 (beginning-of-line)
23914 (looking-at org-todo-line-regexp)
23915 (string= (match-string 3) "")))))
23917 (defun org-at-heading-or-item-p ()
23918 (or (org-at-heading-p) (org-at-item-p)))
23920 (defun org-at-target-p ()
23921 (or (org-in-regexp org-radio-target-regexp)
23922 (org-in-regexp org-target-regexp)))
23923 ;; Compatibility alias with Org versions < 7.8.03
23924 (defalias 'org-on-target-p 'org-at-target-p)
23926 (defun org-up-heading-all (arg)
23927 "Move to the heading line of which the present line is a subheading.
23928 This function considers both visible and invisible heading lines.
23929 With argument, move up ARG levels."
23930 (outline-up-heading arg t))
23932 (defun org-up-heading-safe ()
23933 "Move to the heading line of which the present line is a subheading.
23934 This version will not throw an error. It will return the level of the
23935 headline found, or nil if no higher level is found.
23937 Also, this function will be a lot faster than `outline-up-heading',
23938 because it relies on stars being the outline starters. This can really
23939 make a significant difference in outlines with very many siblings."
23940 (when (ignore-errors (org-back-to-heading t))
23941 (let ((level-up (1- (funcall outline-level))))
23942 (and (> level-up 0)
23943 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23944 (funcall outline-level)))))
23946 (defun org-first-sibling-p ()
23947 "Is this heading the first child of its parents?"
23948 (interactive)
23949 (let ((re org-outline-regexp-bol)
23950 level l)
23951 (unless (org-at-heading-p t)
23952 (user-error "Not at a heading"))
23953 (setq level (funcall outline-level))
23954 (save-excursion
23955 (if (not (re-search-backward re nil t))
23957 (setq l (funcall outline-level))
23958 (< l level)))))
23960 (defun org-goto-sibling (&optional previous)
23961 "Goto the next sibling, even if it is invisible.
23962 When PREVIOUS is set, go to the previous sibling instead. Returns t
23963 when a sibling was found. When none is found, return nil and don't
23964 move point."
23965 (let ((fun (if previous 're-search-backward 're-search-forward))
23966 (pos (point))
23967 (re org-outline-regexp-bol)
23968 level l)
23969 (when (ignore-errors (org-back-to-heading t))
23970 (setq level (funcall outline-level))
23971 (catch 'exit
23972 (or previous (forward-char 1))
23973 (while (funcall fun re nil t)
23974 (setq l (funcall outline-level))
23975 (when (< l level) (goto-char pos) (throw 'exit nil))
23976 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23977 (goto-char pos)
23978 nil))))
23980 (defun org-show-siblings ()
23981 "Show all siblings of the current headline."
23982 (save-excursion
23983 (while (org-goto-sibling) (org-flag-heading nil)))
23984 (save-excursion
23985 (while (org-goto-sibling 'previous)
23986 (org-flag-heading nil))))
23988 (defun org-goto-first-child ()
23989 "Goto the first child, even if it is invisible.
23990 Return t when a child was found. Otherwise don't move point and
23991 return nil."
23992 (let (level (pos (point)) (re org-outline-regexp-bol))
23993 (when (ignore-errors (org-back-to-heading t))
23994 (setq level (outline-level))
23995 (forward-char 1)
23996 (if (and (re-search-forward re nil t) (> (outline-level) level))
23997 (progn (goto-char (match-beginning 0)) t)
23998 (goto-char pos) nil))))
24000 (defun org-show-hidden-entry ()
24001 "Show an entry where even the heading is hidden."
24002 (save-excursion
24003 (org-show-entry)))
24005 (defun org-flag-heading (flag &optional entry)
24006 "Flag the current heading. FLAG non-nil means make invisible.
24007 When ENTRY is non-nil, show the entire entry."
24008 (save-excursion
24009 (org-back-to-heading t)
24010 ;; Check if we should show the entire entry
24011 (if entry
24012 (progn
24013 (org-show-entry)
24014 (save-excursion
24015 (and (outline-next-heading)
24016 (org-flag-heading nil))))
24017 (outline-flag-region (max (point-min) (1- (point)))
24018 (save-excursion (outline-end-of-heading) (point))
24019 flag))))
24021 (defun org-get-next-sibling ()
24022 "Move to next heading of the same level, and return point.
24023 If there is no such heading, return nil.
24024 This is like outline-next-sibling, but invisible headings are ok."
24025 (let ((level (funcall outline-level)))
24026 (outline-next-heading)
24027 (while (and (not (eobp)) (> (funcall outline-level) level))
24028 (outline-next-heading))
24029 (unless (or (eobp) (< (funcall outline-level) level))
24030 (point))))
24032 (defun org-get-last-sibling ()
24033 "Move to previous heading of the same level, and return point.
24034 If there is no such heading, return nil."
24035 (let ((opoint (point))
24036 (level (funcall outline-level)))
24037 (outline-previous-heading)
24038 (when (and (/= (point) opoint) (outline-on-heading-p t))
24039 (while (and (> (funcall outline-level) level)
24040 (not (bobp)))
24041 (outline-previous-heading))
24042 (unless (< (funcall outline-level) level)
24043 (point)))))
24045 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24046 "Goto to the end of a subtree."
24047 ;; This contains an exact copy of the original function, but it uses
24048 ;; `org-back-to-heading', to make it work also in invisible
24049 ;; trees. And is uses an invisible-ok argument.
24050 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24051 ;; Furthermore, when used inside Org, finding the end of a large subtree
24052 ;; with many children and grandchildren etc, this can be much faster
24053 ;; than the outline version.
24054 (org-back-to-heading invisible-ok)
24055 (let ((first t)
24056 (level (funcall outline-level)))
24057 (if (and (derived-mode-p 'org-mode) (< level 1000))
24058 ;; A true heading (not a plain list item), in Org
24059 ;; This means we can easily find the end by looking
24060 ;; only for the right number of stars. Using a regexp to do
24061 ;; this is so much faster than using a Lisp loop.
24062 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24063 (forward-char 1)
24064 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24065 ;; something else, do it the slow way
24066 (while (and (not (eobp))
24067 (or first (> (funcall outline-level) level)))
24068 (setq first nil)
24069 (outline-next-heading)))
24070 (unless to-heading
24071 (when (memq (preceding-char) '(?\n ?\^M))
24072 ;; Go to end of line before heading
24073 (forward-char -1)
24074 (when (memq (preceding-char) '(?\n ?\^M))
24075 ;; leave blank line before heading
24076 (forward-char -1)))))
24077 (point))
24079 (defun org-end-of-meta-data (&optional full)
24080 "Skip planning line and properties drawer in current entry.
24081 When optional argument FULL is non-nil, also skip empty lines,
24082 clocking lines and regular drawers at the beginning of the
24083 entry."
24084 (org-back-to-heading t)
24085 (forward-line)
24086 (when (looking-at-p org-planning-line-re) (forward-line))
24087 (when (looking-at org-property-drawer-re)
24088 (goto-char (match-end 0))
24089 (forward-line))
24090 (when (and full (not (org-at-heading-p)))
24091 (catch 'exit
24092 (let ((end (save-excursion (outline-next-heading) (point)))
24093 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24094 (while (not (eobp))
24095 (cond ((looking-at-p org-drawer-regexp)
24096 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24097 (forward-line)
24098 (throw 'exit t)))
24099 ((looking-at-p re) (forward-line))
24100 (t (throw 'exit t))))))))
24102 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24103 "Move forward to the ARG'th subheading at same level as this one.
24104 Stop at the first and last subheadings of a superior heading.
24105 Normally this only looks at visible headings, but when INVISIBLE-OK is
24106 non-nil it will also look at invisible ones."
24107 (interactive "p")
24108 (let ((backward? (and arg (< arg 0))))
24109 (if (org-before-first-heading-p)
24110 (if backward? (goto-char (point-min)) (outline-next-heading))
24111 (org-back-to-heading invisible-ok)
24112 (unless backward? (end-of-line)) ;do not match current headline
24113 (let ((level (- (match-end 0) (match-beginning 0) 1))
24114 (f (if backward? #'re-search-backward #'re-search-forward))
24115 (count (if arg (abs arg) 1))
24116 (result (point)))
24117 (while (and (> count 0)
24118 (funcall f org-outline-regexp-bol nil 'move))
24119 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24120 (cond ((< l level) (setq count 0))
24121 ((and (= l level)
24122 (or invisible-ok
24123 (not (outline-invisible-p
24124 (line-beginning-position)))))
24125 (cl-decf count)
24126 (when (= l level) (setq result (point)))))))
24127 (goto-char result))
24128 (beginning-of-line))))
24130 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24131 "Move backward to the ARG'th subheading at same level as this one.
24132 Stop at the first and last subheadings of a superior heading."
24133 (interactive "p")
24134 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24136 (defun org-next-visible-heading (arg)
24137 "Move to the next visible heading.
24139 This function wraps `outline-next-visible-heading' with
24140 `org-with-limited-levels' in order to skip over inline tasks and
24141 respect customization of `org-odd-levels-only'."
24142 (interactive "p")
24143 (org-with-limited-levels
24144 (outline-next-visible-heading arg)))
24146 (defun org-previous-visible-heading (arg)
24147 "Move to the previous visible heading.
24149 This function wraps `outline-previous-visible-heading' with
24150 `org-with-limited-levels' in order to skip over inline tasks and
24151 respect customization of `org-odd-levels-only'."
24152 (interactive "p")
24153 (org-with-limited-levels
24154 (outline-previous-visible-heading arg)))
24156 (defun org-next-block (arg &optional backward block-regexp)
24157 "Jump to the next block.
24159 With a prefix argument ARG, jump forward ARG many blocks.
24161 When BACKWARD is non-nil, jump to the previous block.
24163 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24164 Match data is set according to this regexp when the function
24165 returns.
24167 Return point at beginning of the opening line of found block.
24168 Throw an error if no block is found."
24169 (interactive "p")
24170 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24171 (case-fold-search t)
24172 (search-fn (if backward #'re-search-backward #'re-search-forward))
24173 (count (or arg 1))
24174 (origin (point))
24175 last-element)
24176 (if backward (beginning-of-line) (end-of-line))
24177 (while (and (> count 0) (funcall search-fn re nil t))
24178 (let ((element (save-excursion
24179 (goto-char (match-beginning 0))
24180 (save-match-data (org-element-at-point)))))
24181 (when (and (memq (org-element-type element)
24182 '(center-block comment-block dynamic-block
24183 example-block export-block quote-block
24184 special-block src-block verse-block))
24185 (<= (match-beginning 0)
24186 (org-element-property :post-affiliated element)))
24187 (setq last-element element)
24188 (cl-decf count))))
24189 (if (= count 0)
24190 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24191 (save-match-data (org-show-context)))
24192 (goto-char origin)
24193 (user-error "No %s code blocks" (if backward "previous" "further")))))
24195 (defun org-previous-block (arg &optional block-regexp)
24196 "Jump to the previous block.
24197 With a prefix argument ARG, jump backward ARG many source blocks.
24198 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24199 (interactive "p")
24200 (org-next-block arg t block-regexp))
24202 (defun org-forward-paragraph ()
24203 "Move forward to beginning of next paragraph or equivalent.
24205 The function moves point to the beginning of the next visible
24206 structural element, which can be a paragraph, a table, a list
24207 item, etc. It also provides some special moves for convenience:
24209 - On an affiliated keyword, jump to the beginning of the
24210 relative element.
24211 - On an item or a footnote definition, move to the second
24212 element inside, if any.
24213 - On a table or a property drawer, jump after it.
24214 - On a verse or source block, stop after blank lines."
24215 (interactive)
24216 (when (eobp) (user-error "Cannot move further down"))
24217 (let* ((deactivate-mark nil)
24218 (element (org-element-at-point))
24219 (type (org-element-type element))
24220 (post-affiliated (org-element-property :post-affiliated element))
24221 (contents-begin (org-element-property :contents-begin element))
24222 (contents-end (org-element-property :contents-end element))
24223 (end (let ((end (org-element-property :end element)) (parent element))
24224 (while (and (setq parent (org-element-property :parent parent))
24225 (= (org-element-property :contents-end parent) end))
24226 (setq end (org-element-property :end parent)))
24227 end)))
24228 (cond ((not element)
24229 (skip-chars-forward " \r\t\n")
24230 (or (eobp) (beginning-of-line)))
24231 ;; On affiliated keywords, move to element's beginning.
24232 ((< (point) post-affiliated)
24233 (goto-char post-affiliated))
24234 ;; At a table row, move to the end of the table. Similarly,
24235 ;; at a node property, move to the end of the property
24236 ;; drawer.
24237 ((memq type '(node-property table-row))
24238 (goto-char (org-element-property
24239 :end (org-element-property :parent element))))
24240 ((memq type '(property-drawer table)) (goto-char end))
24241 ;; Consider blank lines as separators in verse and source
24242 ;; blocks to ease editing.
24243 ((memq type '(src-block verse-block))
24244 (when (eq type 'src-block)
24245 (setq contents-end
24246 (save-excursion (goto-char end)
24247 (skip-chars-backward " \r\t\n")
24248 (line-beginning-position))))
24249 (beginning-of-line)
24250 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24251 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24252 (goto-char end)
24253 (skip-chars-forward " \r\t\n")
24254 (if (= (point) contents-end) (goto-char end)
24255 (beginning-of-line))))
24256 ;; With no contents, just skip element.
24257 ((not contents-begin) (goto-char end))
24258 ;; If contents are invisible, skip the element altogether.
24259 ((outline-invisible-p (line-end-position))
24260 (cl-case type
24261 (headline
24262 (org-with-limited-levels (outline-next-visible-heading 1)))
24263 ;; At a plain list, make sure we move to the next item
24264 ;; instead of skipping the whole list.
24265 (plain-list (forward-char)
24266 (org-forward-paragraph))
24267 (otherwise (goto-char end))))
24268 ((>= (point) contents-end) (goto-char end))
24269 ((>= (point) contents-begin)
24270 ;; This can only happen on paragraphs and plain lists.
24271 (cl-case type
24272 (paragraph (goto-char end))
24273 ;; At a plain list, try to move to second element in
24274 ;; first item, if possible.
24275 (plain-list (end-of-line)
24276 (org-forward-paragraph))))
24277 ;; When contents start on the middle of a line (e.g. in
24278 ;; items and footnote definitions), try to reach first
24279 ;; element starting after current line.
24280 ((> (line-end-position) contents-begin)
24281 (end-of-line)
24282 (org-forward-paragraph))
24283 (t (goto-char contents-begin)))))
24285 (defun org-backward-paragraph ()
24286 "Move backward to start of previous paragraph or equivalent.
24288 The function moves point to the beginning of the current
24289 structural element, which can be a paragraph, a table, a list
24290 item, etc., or to the beginning of the previous visible one if
24291 point is already there. It also provides some special moves for
24292 convenience:
24294 - On an affiliated keyword, jump to the first one.
24295 - On a table or a property drawer, move to its beginning.
24296 - On a verse or source block, stop before blank lines."
24297 (interactive)
24298 (when (bobp) (user-error "Cannot move further up"))
24299 (let* ((deactivate-mark nil)
24300 (element (org-element-at-point))
24301 (type (org-element-type element))
24302 (contents-begin (org-element-property :contents-begin element))
24303 (contents-end (org-element-property :contents-end element))
24304 (post-affiliated (org-element-property :post-affiliated element))
24305 (begin (org-element-property :begin element)))
24306 (cond
24307 ((not element) (goto-char (point-min)))
24308 ((= (point) begin)
24309 (backward-char)
24310 (org-backward-paragraph))
24311 ((<= (point) post-affiliated) (goto-char begin))
24312 ((memq type '(node-property table-row))
24313 (goto-char (org-element-property
24314 :post-affiliated (org-element-property :parent element))))
24315 ((memq type '(property-drawer table)) (goto-char begin))
24316 ((memq type '(src-block verse-block))
24317 (when (eq type 'src-block)
24318 (setq contents-begin
24319 (save-excursion (goto-char begin) (forward-line) (point))))
24320 (if (= (point) contents-begin) (goto-char post-affiliated)
24321 ;; Inside a verse block, see blank lines as paragraph
24322 ;; separators.
24323 (let ((origin (point)))
24324 (skip-chars-backward " \r\t\n" contents-begin)
24325 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24326 (skip-chars-forward " \r\t\n" origin)
24327 (if (= (point) origin) (goto-char contents-begin)
24328 (beginning-of-line))))))
24329 ((not contents-begin) (goto-char (or post-affiliated begin)))
24330 ((eq type 'paragraph)
24331 (goto-char contents-begin)
24332 ;; When at first paragraph in an item or a footnote definition,
24333 ;; move directly to beginning of line.
24334 (let ((parent-contents
24335 (org-element-property
24336 :contents-begin (org-element-property :parent element))))
24337 (when (and parent-contents (= parent-contents contents-begin))
24338 (beginning-of-line))))
24339 ;; At the end of a greater element, move to the beginning of the
24340 ;; last element within.
24341 ((>= (point) contents-end)
24342 (goto-char (1- contents-end))
24343 (org-backward-paragraph))
24344 (t (goto-char (or post-affiliated begin))))
24345 ;; Ensure we never leave point invisible.
24346 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24348 (defun org-forward-element ()
24349 "Move forward by one element.
24350 Move to the next element at the same level, when possible."
24351 (interactive)
24352 (cond ((eobp) (user-error "Cannot move further down"))
24353 ((org-with-limited-levels (org-at-heading-p))
24354 (let ((origin (point)))
24355 (goto-char (org-end-of-subtree nil t))
24356 (unless (org-with-limited-levels (org-at-heading-p))
24357 (goto-char origin)
24358 (user-error "Cannot move further down"))))
24360 (let* ((elem (org-element-at-point))
24361 (end (org-element-property :end elem))
24362 (parent (org-element-property :parent elem)))
24363 (cond ((and parent (= (org-element-property :contents-end parent) end))
24364 (goto-char (org-element-property :end parent)))
24365 ((integer-or-marker-p end) (goto-char end))
24366 (t (message "No element at point")))))))
24368 (defun org-backward-element ()
24369 "Move backward by one element.
24370 Move to the previous element at the same level, when possible."
24371 (interactive)
24372 (cond ((bobp) (user-error "Cannot move further up"))
24373 ((org-with-limited-levels (org-at-heading-p))
24374 ;; At a headline, move to the previous one, if any, or stay
24375 ;; here.
24376 (let ((origin (point)))
24377 (org-with-limited-levels (org-backward-heading-same-level 1))
24378 ;; When current headline has no sibling above, move to its
24379 ;; parent.
24380 (when (= (point) origin)
24381 (or (org-with-limited-levels (org-up-heading-safe))
24382 (progn (goto-char origin)
24383 (user-error "Cannot move further up"))))))
24385 (let* ((elem (org-element-at-point))
24386 (beg (org-element-property :begin elem)))
24387 (cond
24388 ;; Move to beginning of current element if point isn't
24389 ;; there already.
24390 ((null beg) (message "No element at point"))
24391 ((/= (point) beg) (goto-char beg))
24392 (t (goto-char beg)
24393 (skip-chars-backward " \r\t\n")
24394 (unless (bobp)
24395 (let ((prev (org-element-at-point)))
24396 (goto-char (org-element-property :begin prev))
24397 (while (and (setq prev (org-element-property :parent prev))
24398 (<= (org-element-property :end prev) beg))
24399 (goto-char (org-element-property :begin prev)))))))))))
24401 (defun org-up-element ()
24402 "Move to upper element."
24403 (interactive)
24404 (if (org-with-limited-levels (org-at-heading-p))
24405 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24406 (let* ((elem (org-element-at-point))
24407 (parent (org-element-property :parent elem)))
24408 (if parent (goto-char (org-element-property :begin parent))
24409 (if (org-with-limited-levels (org-before-first-heading-p))
24410 (user-error "No surrounding element")
24411 (org-with-limited-levels (org-back-to-heading)))))))
24413 (defun org-down-element ()
24414 "Move to inner element."
24415 (interactive)
24416 (let ((element (org-element-at-point)))
24417 (cond
24418 ((memq (org-element-type element) '(plain-list table))
24419 (goto-char (org-element-property :contents-begin element))
24420 (forward-char))
24421 ((memq (org-element-type element) org-element-greater-elements)
24422 ;; If contents are hidden, first disclose them.
24423 (when (outline-invisible-p (line-end-position)) (org-cycle))
24424 (goto-char (or (org-element-property :contents-begin element)
24425 (user-error "No content for this element"))))
24426 (t (user-error "No inner element")))))
24428 (defun org-drag-element-backward ()
24429 "Move backward element at point."
24430 (interactive)
24431 (let ((elem (or (org-element-at-point)
24432 (user-error "No element at point"))))
24433 (if (eq (org-element-type elem) 'headline)
24434 ;; Preserve point when moving a whole tree, even if point was
24435 ;; on blank lines below the headline.
24436 (let ((offset (skip-chars-backward " \t\n")))
24437 (unwind-protect (org-move-subtree-up)
24438 (forward-char (- offset))))
24439 (let ((prev-elem
24440 (save-excursion
24441 (goto-char (org-element-property :begin elem))
24442 (skip-chars-backward " \r\t\n")
24443 (unless (bobp)
24444 (let* ((beg (org-element-property :begin elem))
24445 (prev (org-element-at-point))
24446 (up prev))
24447 (while (and (setq up (org-element-property :parent up))
24448 (<= (org-element-property :end up) beg))
24449 (setq prev up))
24450 prev)))))
24451 ;; Error out if no previous element or previous element is
24452 ;; a parent of the current one.
24453 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24454 (user-error "Cannot drag element backward")
24455 (let ((pos (point)))
24456 (org-element-swap-A-B prev-elem elem)
24457 (goto-char (+ (org-element-property :begin prev-elem)
24458 (- pos (org-element-property :begin elem))))))))))
24460 (defun org-drag-element-forward ()
24461 "Move forward element at point."
24462 (interactive)
24463 (let* ((pos (point))
24464 (elem (or (org-element-at-point)
24465 (user-error "No element at point"))))
24466 (when (= (point-max) (org-element-property :end elem))
24467 (user-error "Cannot drag element forward"))
24468 (goto-char (org-element-property :end elem))
24469 (let ((next-elem (org-element-at-point)))
24470 (when (or (org-element-nested-p elem next-elem)
24471 (and (eq (org-element-type next-elem) 'headline)
24472 (not (eq (org-element-type elem) 'headline))))
24473 (goto-char pos)
24474 (user-error "Cannot drag element forward"))
24475 ;; Compute new position of point: it's shifted by NEXT-ELEM
24476 ;; body's length (without final blanks) and by the length of
24477 ;; blanks between ELEM and NEXT-ELEM.
24478 (let ((size-next (- (save-excursion
24479 (goto-char (org-element-property :end next-elem))
24480 (skip-chars-backward " \r\t\n")
24481 (forward-line)
24482 ;; Small correction if buffer doesn't end
24483 ;; with a newline character.
24484 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24485 (org-element-property :begin next-elem)))
24486 (size-blank (- (org-element-property :end elem)
24487 (save-excursion
24488 (goto-char (org-element-property :end elem))
24489 (skip-chars-backward " \r\t\n")
24490 (forward-line)
24491 (point)))))
24492 (org-element-swap-A-B elem next-elem)
24493 (goto-char (+ pos size-next size-blank))))))
24495 (defun org-drag-line-forward (arg)
24496 "Drag the line at point ARG lines forward."
24497 (interactive "p")
24498 (dotimes (_ (abs arg))
24499 (let ((c (current-column)))
24500 (if (< 0 arg)
24501 (progn
24502 (beginning-of-line 2)
24503 (transpose-lines 1)
24504 (beginning-of-line 0))
24505 (transpose-lines 1)
24506 (beginning-of-line -1))
24507 (org-move-to-column c))))
24509 (defun org-drag-line-backward (arg)
24510 "Drag the line at point ARG lines backward."
24511 (interactive "p")
24512 (org-drag-line-forward (- arg)))
24514 (defun org-mark-element ()
24515 "Put point at beginning of this element, mark at end.
24517 Interactively, if this command is repeated or (in Transient Mark
24518 mode) if the mark is active, it marks the next element after the
24519 ones already marked."
24520 (interactive)
24521 (let (deactivate-mark)
24522 (if (and (called-interactively-p 'any)
24523 (or (and (eq last-command this-command) (mark t))
24524 (and transient-mark-mode mark-active)))
24525 (set-mark
24526 (save-excursion
24527 (goto-char (mark))
24528 (goto-char (org-element-property :end (org-element-at-point)))))
24529 (let ((element (org-element-at-point)))
24530 (end-of-line)
24531 (push-mark (org-element-property :end element) t t)
24532 (goto-char (org-element-property :begin element))))))
24534 (defun org-narrow-to-element ()
24535 "Narrow buffer to current element."
24536 (interactive)
24537 (let ((elem (org-element-at-point)))
24538 (cond
24539 ((eq (car elem) 'headline)
24540 (narrow-to-region
24541 (org-element-property :begin elem)
24542 (org-element-property :end elem)))
24543 ((memq (car elem) org-element-greater-elements)
24544 (narrow-to-region
24545 (org-element-property :contents-begin elem)
24546 (org-element-property :contents-end elem)))
24548 (narrow-to-region
24549 (org-element-property :begin elem)
24550 (org-element-property :end elem))))))
24552 (defun org-transpose-element ()
24553 "Transpose current and previous elements, keeping blank lines between.
24554 Point is moved after both elements."
24555 (interactive)
24556 (org-skip-whitespace)
24557 (let ((end (org-element-property :end (org-element-at-point))))
24558 (org-drag-element-backward)
24559 (goto-char end)))
24561 (defun org-unindent-buffer ()
24562 "Un-indent the visible part of the buffer.
24563 Relative indentation (between items, inside blocks, etc.) isn't
24564 modified."
24565 (interactive)
24566 (unless (eq major-mode 'org-mode)
24567 (user-error "Cannot un-indent a buffer not in Org mode"))
24568 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24569 (unindent-tree
24570 (lambda (contents)
24571 (dolist (element (reverse contents))
24572 (if (memq (org-element-type element) '(headline section))
24573 (funcall unindent-tree (org-element-contents element))
24574 (save-excursion
24575 (save-restriction
24576 (narrow-to-region
24577 (org-element-property :begin element)
24578 (org-element-property :end element))
24579 (org-do-remove-indentation))))))))
24580 (funcall unindent-tree (org-element-contents parse-tree))))
24582 (defun org-show-children (&optional level)
24583 "Show all direct subheadings of this heading.
24584 Prefix arg LEVEL is how many levels below the current level
24585 should be shown. Default is enough to cause the following
24586 heading to appear."
24587 (interactive "p")
24588 ;; If `orgstruct-mode' is active, use the slower version.
24589 (if orgstruct-mode (call-interactively #'outline-show-children)
24590 (save-excursion
24591 (org-back-to-heading t)
24592 (let* ((current-level (funcall outline-level))
24593 (max-level (org-get-valid-level
24594 current-level
24595 (if level (prefix-numeric-value level) 1)))
24596 (end (save-excursion (org-end-of-subtree t t)))
24597 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24598 (past-first-child nil)
24599 ;; Make sure to skip inlinetasks.
24600 (re (format regexp-fmt
24601 current-level
24602 (cond
24603 ((not (featurep 'org-inlinetask)) "")
24604 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24606 (t (1- org-inlinetask-min-level))))))
24607 ;; Display parent heading.
24608 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24609 (forward-line)
24610 ;; Display children. First child may be deeper than expected
24611 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24612 ;; MAX-LEVEL accordingly.
24613 (while (re-search-forward re end t)
24614 (unless past-first-child
24615 (setq re (format regexp-fmt
24616 current-level
24617 (max (funcall outline-level) max-level)))
24618 (setq past-first-child t))
24619 (outline-flag-region
24620 (line-end-position 0) (line-end-position) nil))))))
24622 (defun org-show-subtree ()
24623 "Show everything after this heading at deeper levels."
24624 (interactive)
24625 (outline-flag-region
24626 (point)
24627 (save-excursion
24628 (org-end-of-subtree t t))
24629 nil))
24631 (defun org-show-entry ()
24632 "Show the body directly following this heading.
24633 Show the heading too, if it is currently invisible."
24634 (interactive)
24635 (save-excursion
24636 (ignore-errors
24637 (org-back-to-heading t)
24638 (outline-flag-region
24639 (max (point-min) (1- (point)))
24640 (save-excursion
24641 (if (re-search-forward
24642 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24643 (match-beginning 1)
24644 (point-max)))
24645 nil)
24646 (org-cycle-hide-drawers 'children))))
24648 (defun org-make-options-regexp (kwds &optional extra)
24649 "Make a regular expression for keyword lines.
24650 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24651 when non-nil, is a regexp matching keywords names."
24652 (concat "^[ \t]*#\\+\\("
24653 (regexp-opt kwds)
24654 (and extra (concat (and kwds "\\|") extra))
24655 "\\):[ \t]*\\(.*\\)"))
24657 ;;;; Integration with and fixes for other packages
24659 ;;; Imenu support
24661 (defvar-local org-imenu-markers nil
24662 "All markers currently used by Imenu.")
24664 (defun org-imenu-new-marker (&optional pos)
24665 "Return a new marker for use by Imenu, and remember the marker."
24666 (let ((m (make-marker)))
24667 (move-marker m (or pos (point)))
24668 (push m org-imenu-markers)
24671 (defun org-imenu-get-tree ()
24672 "Produce the index for Imenu."
24673 (dolist (x org-imenu-markers) (move-marker x nil))
24674 (setq org-imenu-markers nil)
24675 (let* ((case-fold-search nil)
24676 (n org-imenu-depth)
24677 (re (concat "^" (org-get-limited-outline-regexp)))
24678 (subs (make-vector (1+ n) nil))
24679 (last-level 0)
24680 m level head0 head)
24681 (org-with-wide-buffer
24682 (goto-char (point-max))
24683 (while (re-search-backward re nil t)
24684 (setq level (org-reduced-level (funcall outline-level)))
24685 (when (and (<= level n)
24686 (looking-at org-complex-heading-regexp)
24687 (setq head0 (match-string-no-properties 4)))
24688 (setq head (org-link-display-format head0)
24689 m (org-imenu-new-marker))
24690 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24691 (if (>= level last-level)
24692 (push (cons head m) (aref subs level))
24693 (push (cons head (aref subs (1+ level))) (aref subs level))
24694 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24695 (setq last-level level))))
24696 (aref subs 1)))
24698 (eval-after-load "imenu"
24699 '(progn
24700 (add-hook 'imenu-after-jump-hook
24701 (lambda ()
24702 (when (derived-mode-p 'org-mode)
24703 (org-show-context 'org-goto))))))
24705 (defun org-link-display-format (s)
24706 "Replace links in string S with their description.
24707 If there is no description, use the link target."
24708 (save-match-data
24709 (replace-regexp-in-string
24710 org-bracket-link-analytic-regexp
24711 (lambda (m)
24712 (if (match-end 5) (match-string 5 m)
24713 (concat (match-string 1 m) (match-string 3 m))))
24714 s nil t)))
24716 (defun org-toggle-link-display ()
24717 "Toggle the literal or descriptive display of links."
24718 (interactive)
24719 (if org-descriptive-links
24720 (progn (org-remove-from-invisibility-spec '(org-link))
24721 (org-restart-font-lock)
24722 (setq org-descriptive-links nil))
24723 (progn (add-to-invisibility-spec '(org-link))
24724 (org-restart-font-lock)
24725 (setq org-descriptive-links t))))
24727 ;; Speedbar support
24729 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24730 "Overlay marking the agenda restriction line in speedbar.")
24731 (overlay-put org-speedbar-restriction-lock-overlay
24732 'face 'org-agenda-restriction-lock)
24733 (overlay-put org-speedbar-restriction-lock-overlay
24734 'help-echo "Agendas are currently limited to this item.")
24735 (delete-overlay org-speedbar-restriction-lock-overlay)
24737 (defun org-speedbar-set-agenda-restriction ()
24738 "Restrict future agenda commands to the location at point in speedbar.
24739 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24740 (interactive)
24741 (require 'org-agenda)
24742 (let (p m tp np dir txt)
24743 (cond
24744 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24745 'org-imenu t))
24746 (setq m (get-text-property p 'org-imenu-marker))
24747 (with-current-buffer (marker-buffer m)
24748 (goto-char m)
24749 (org-agenda-set-restriction-lock 'subtree)))
24750 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24751 'speedbar-function 'speedbar-find-file))
24752 (setq tp (previous-single-property-change
24753 (1+ p) 'speedbar-function)
24754 np (next-single-property-change
24755 tp 'speedbar-function)
24756 dir (speedbar-line-directory)
24757 txt (buffer-substring-no-properties (or tp (point-min))
24758 (or np (point-max))))
24759 (with-current-buffer (find-file-noselect
24760 (let ((default-directory dir))
24761 (expand-file-name txt)))
24762 (unless (derived-mode-p 'org-mode)
24763 (user-error "Cannot restrict to non-Org mode file"))
24764 (org-agenda-set-restriction-lock 'file)))
24765 (t (user-error "Don't know how to restrict Org mode agenda")))
24766 (move-overlay org-speedbar-restriction-lock-overlay
24767 (point-at-bol) (point-at-eol))
24768 (setq current-prefix-arg nil)
24769 (org-agenda-maybe-redo)))
24771 (defvar speedbar-file-key-map)
24772 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24773 (eval-after-load "speedbar"
24774 '(progn
24775 (speedbar-add-supported-extension ".org")
24776 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24777 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24778 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24779 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24780 (add-hook 'speedbar-visiting-tag-hook
24781 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24783 ;;; Fixes and Hacks for problems with other packages
24785 (defun org--flyspell-object-check-p (element)
24786 "Non-nil when Flyspell can check object at point.
24787 ELEMENT is the element at point."
24788 (let ((object (save-excursion
24789 (when (looking-at-p "\\>") (backward-char))
24790 (org-element-context element))))
24791 (cl-case (org-element-type object)
24792 ;; Prevent checks in links due to keybinding conflict with
24793 ;; Flyspell.
24794 ((code entity export-snippet inline-babel-call
24795 inline-src-block line-break latex-fragment link macro
24796 statistics-cookie target timestamp verbatim)
24797 nil)
24798 (footnote-reference
24799 ;; Only in inline footnotes, within the definition.
24800 (and (eq (org-element-property :type object) 'inline)
24801 (< (save-excursion
24802 (goto-char (org-element-property :begin object))
24803 (search-forward ":" nil t 2))
24804 (point))))
24805 (otherwise t))))
24807 (defun org-mode-flyspell-verify ()
24808 "Function used for `flyspell-generic-check-word-predicate'."
24809 (if (org-at-heading-p)
24810 ;; At a headline or an inlinetask, check title only. This is
24811 ;; faster than relying on `org-element-at-point'.
24812 (and (save-excursion (beginning-of-line)
24813 (and (let ((case-fold-search t))
24814 (not (looking-at-p "\\*+ END[ \t]*$")))
24815 (let ((case-fold-search nil))
24816 (looking-at org-complex-heading-regexp))))
24817 (match-beginning 4)
24818 (>= (point) (match-beginning 4))
24819 (or (not (match-beginning 5))
24820 (< (point) (match-beginning 5))))
24821 (let* ((element (org-element-at-point))
24822 (post-affiliated (org-element-property :post-affiliated element)))
24823 (cond
24824 ;; Ignore checks in all affiliated keywords but captions.
24825 ((< (point) post-affiliated)
24826 (and (save-excursion
24827 (beginning-of-line)
24828 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24829 (> (point) (match-end 0))
24830 (org--flyspell-object-check-p element)))
24831 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24832 ((let ((log (org-log-into-drawer)))
24833 (and log
24834 (let ((drawer (org-element-lineage element '(drawer))))
24835 (and drawer
24836 (eq (compare-strings
24837 log nil nil
24838 (org-element-property :drawer-name drawer) nil nil t)
24839 t)))))
24840 nil)
24842 (cl-case (org-element-type element)
24843 ((comment quote-section) t)
24844 (comment-block
24845 ;; Allow checks between block markers, not on them.
24846 (and (> (line-beginning-position) post-affiliated)
24847 (save-excursion
24848 (end-of-line)
24849 (skip-chars-forward " \r\t\n")
24850 (< (point) (org-element-property :end element)))))
24851 ;; Arbitrary list of keywords where checks are meaningful.
24852 ;; Make sure point is on the value part of the element.
24853 (keyword
24854 (and (member (org-element-property :key element)
24855 '("DESCRIPTION" "TITLE"))
24856 (save-excursion
24857 (search-backward ":" (line-beginning-position) t))))
24858 ;; Check is globally allowed in paragraphs verse blocks and
24859 ;; table rows (after affiliated keywords) but some objects
24860 ;; must not be affected.
24861 ((paragraph table-row verse-block)
24862 (let ((cbeg (org-element-property :contents-begin element))
24863 (cend (org-element-property :contents-end element)))
24864 (and cbeg (>= (point) cbeg) (< (point) cend)
24865 (org--flyspell-object-check-p element))))))))))
24866 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24868 (defun org-remove-flyspell-overlays-in (beg end)
24869 "Remove flyspell overlays in region."
24870 (and (bound-and-true-p flyspell-mode)
24871 (fboundp 'flyspell-delete-region-overlays)
24872 (flyspell-delete-region-overlays beg end)))
24874 (defvar flyspell-delayed-commands)
24875 (eval-after-load "flyspell"
24876 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24878 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24879 (eval-after-load "bookmark"
24880 '(if (boundp 'bookmark-after-jump-hook)
24881 ;; We can use the hook
24882 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24883 ;; Hook not available, use advice
24884 (defadvice bookmark-jump (after org-make-visible activate)
24885 "Make the position visible."
24886 (org-bookmark-jump-unhide))))
24888 ;; Make sure saveplace shows the location if it was hidden
24889 (eval-after-load "saveplace"
24890 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24891 "Make the position visible."
24892 (org-bookmark-jump-unhide)))
24894 ;; Make sure ecb shows the location if it was hidden
24895 (eval-after-load "ecb"
24896 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24897 "Make hierarchy visible when jumping into location from ECB tree buffer."
24898 (when (derived-mode-p 'org-mode)
24899 (org-show-context))))
24901 (defun org-bookmark-jump-unhide ()
24902 "Unhide the current position, to show the bookmark location."
24903 (and (derived-mode-p 'org-mode)
24904 (or (outline-invisible-p)
24905 (save-excursion (goto-char (max (point-min) (1- (point))))
24906 (outline-invisible-p)))
24907 (org-show-context 'bookmark-jump)))
24909 (defun org-mark-jump-unhide ()
24910 "Make the point visible with `org-show-context' after jumping to the mark."
24911 (when (and (derived-mode-p 'org-mode)
24912 (outline-invisible-p))
24913 (org-show-context 'mark-goto)))
24915 (eval-after-load "simple"
24916 '(defadvice pop-to-mark-command (after org-make-visible activate)
24917 "Make the point visible with `org-show-context'."
24918 (org-mark-jump-unhide)))
24920 (eval-after-load "simple"
24921 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24922 "Make the point visible with `org-show-context'."
24923 (org-mark-jump-unhide)))
24925 (eval-after-load "simple"
24926 '(defadvice pop-global-mark (after org-make-visible activate)
24927 "Make the point visible with `org-show-context'."
24928 (org-mark-jump-unhide)))
24930 ;; Make session.el ignore our circular variable
24931 (defvar session-globals-exclude)
24932 (eval-after-load "session"
24933 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24935 ;;;; Finish up
24937 (provide 'org)
24939 (run-hooks 'org-load-hook)
24941 ;;; org.el ends here